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 |
|---|---|---|---|---|
populate_auto.py | import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'esite.settings')
import django
django.setup()
from auto.models import Car
#
def add_car(make, model, km, year, color, eng, drive,trans, icolor):
c = Car.objects.get_or_create(make=make, model=model, kilometers=km, year=year, color=color, engine_size=eng,... | # url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")
#
# add_page(cat=django_cat,
# title="Django Rocks",
# url="http://www.djangorocks.com/")
#
# add_page(cat=django_cat,
# title="How to Tango with Django",
# url="http://www.tangowithdjango.com/")
#
# ... | # add_page(cat=django_cat,
# title="Official Django Tutorial", | random_line_split |
populate_auto.py | import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'esite.settings')
import django
django.setup()
from auto.models import Car
#
def add_car(make, model, km, year, color, eng, drive,trans, icolor):
c = Car.objects.get_or_create(make=make, model=model, kilometers=km, year=year, color=color, engine_size=eng,... |
if __name__ == '__main__':
print "Starting Car population script..."
populate()
# def populate():
# python_cat = add_cat('Python')
#
# add_page(cat=python_cat,
# title="Official Python Tutorial",
# url="http://docs.python.org/2/tutorial/")
#
# add_page(cat=python_cat,
#... | add_car('Acura', 'TL', 74673, 2012, 'White', 3.7, 'AWD','MA','White')
add_car('Volkswagen', 'Touareg', 5344, 2015, 'Silver', 3.6, 'AWD','AU','White') | identifier_body |
populate_auto.py | import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'esite.settings')
import django
django.setup()
from auto.models import Car
#
def | (make, model, km, year, color, eng, drive,trans, icolor):
c = Car.objects.get_or_create(make=make, model=model, kilometers=km, year=year, color=color, engine_size=eng, drivetrain=drive, transmition=trans, interanl_color=icolor)
def populate():
# car = Car(make='Acura',model='TL', kilometers=74673, year=2012, ... | add_car | identifier_name |
populate_auto.py | import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'esite.settings')
import django
django.setup()
from auto.models import Car
#
def add_car(make, model, km, year, color, eng, drive,trans, icolor):
c = Car.objects.get_or_create(make=make, model=model, kilometers=km, year=year, color=color, engine_size=eng,... |
# def populate():
# python_cat = add_cat('Python')
#
# add_page(cat=python_cat,
# title="Official Python Tutorial",
# url="http://docs.python.org/2/tutorial/")
#
# add_page(cat=python_cat,
# title="How to Think like a Computer Scientist",
# url="http://www.greenteapr... | print "Starting Car population script..."
populate() | conditional_block |
tabIndex.spec.ts | // tslint:disable:max-line-length
import { Navigatable, Codes } from "./tabIndex"
import { expect } from "chai"
import { suite, test } from "mocha-typescript"
/**
* 0 1||1 2| 4| 0 1 2 |4 |2
* 0 1||1 2| 5| 1 2 3 |5 |2
* 0 1||1 2| 6| 2 |6 |2
*/
let navA = () => new Navigatable... |
@test
public "find next active in above/below row"() {
expect(navA().getActive().next(Codes.UP, true).index).to.eq(4)
expect(navA().getActive().next(Codes.DOWN, true).index).to.eq(6)
}
@test
public "parent indexOf"() {
let inner = new Navigatable("row", 6)
let cs = [new Navigatable("column"... | {
expect(navA().getActive().next(Codes.LEFT, true).index).to.eq(1)
expect(navA().getActive().next(Codes.RIGHT, true).index).to.eq(3)
} | identifier_body |
tabIndex.spec.ts | // tslint:disable:max-line-length
import { Navigatable, Codes } from "./tabIndex"
import { expect } from "chai"
import { suite, test } from "mocha-typescript"
/**
* 0 1||1 2| 4| 0 1 2 |4 |2
* 0 1||1 2| 5| 1 2 3 |5 |2
* 0 1||1 2| 6| 2 |6 |2
*/
let navA = () => new Navigatable... | {
@test
public "find active"() {
expect(navA().getActive().index).to.eq(2)
}
@test
public "find next active in same row"() {
expect(navA().getActive().next(Codes.LEFT, true).index).to.eq(1)
expect(navA().getActive().next(Codes.RIGHT, true).index).to.eq(3)
}
@test
public "find next active... | TabIndexSpec | identifier_name |
tabIndex.spec.ts | // tslint:disable:max-line-length
import { Navigatable, Codes } from "./tabIndex"
import { expect } from "chai"
import { suite, test } from "mocha-typescript"
/**
* 0 1||1 2| 4| 0 1 2 |4 |2
* 0 1||1 2| 5| 1 2 3 |5 |2
* 0 1||1 2| 6| 2 |6 |2
*/
let navA = () => new Navigatable... | }
} | random_line_split | |
svh.rs | traversal of the expression's
/// substructure by the visitor.
///
/// We know every Expr_ variant is covered by a variant because
/// `fn saw_expr` maps each to some case below. Ensuring that
/// each variant carries an appropriate payload has to be verified
/// by hand.
///
/// (Howe... | visit_view_item | identifier_name | |
svh.rs | ): This hash is still sensitive to e.g. the
// spans of the crate Attributes and their underlying
// MetaItems; we should make ContentHashable impl for those
// types and then use hash_content. But, since all crate
// attributes should appear near beginning of the file, it is
//... | impl InternKey for Ident {
fn get_content(self) -> token::InternedString { token::get_ident(self) }
} | random_line_split | |
svh.rs | // attributes should appear near beginning of the file, it is
// not such a big deal to be sensitive to their spans for now.
//
// We hash only the MetaItems instead of the entire Attribute
// to avoid hashing the AttrId
for attr in krate.attrs.iter() {
attr.n... | { k.get_content() } | identifier_body | |
service.py | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... |
# close otherwise
if fd not in range(3):
os.close(fd)
# Make us a daemon
pid = os.fork()
# end if not in child
if pid > 0:
os._exit(0)
# get new process session and detach
sid = os.setsid()
if sid == -1:
mod... | os.dup2(fd, num) | conditional_block |
service.py | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | (name):
'''
This function will return the expected path for an init script
corresponding to the service name supplied.
:arg name: name or path of the service to test for
'''
if name.startswith('/'):
result = name
else:
result = '/etc/init.d/%s' % name
return result
de... | get_sysv_script | identifier_name |
service.py | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... |
def fail_if_missing(module, found, service, msg=''):
'''
This function will return an error or exit gracefully depending on check mode status
and if the service is missing or not.
:arg module: is an AnsibleModule object, used for it's utility methods
:arg found: boolean indicating if services w... | '''
This function will return True or False depending on
the existence of an init script corresponding to the service name supplied.
:arg name: name of the service to test for
'''
return os.path.exists(get_sysv_script(name)) | identifier_body |
service.py | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | module.fail_json(msg="Unable to fork, no exception thrown, probably due to lack of resources, check logs.")
else:
# in parent
os.close(pipe[1])
os.waitpid(pid, 0)
# Grab response data after child finishes
return_data = b("")
while True:
rfd, wfd,... | # clean up
os.close(pipe[1])
os._exit(0)
elif pid == -1: | random_line_split |
0001_initial.py | from django.db import migrations, models
from django.conf import settings
from opaque_keys.edx.django.models import CourseKeyField
class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='CourseGoal',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
... | identifier_body | |
0001_initial.py | from django.db import migrations, models
from django.conf import settings |
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='CourseGoal',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto... | from opaque_keys.edx.django.models import CourseKeyField | random_line_split |
0001_initial.py | from django.db import migrations, models
from django.conf import settings
from opaque_keys.edx.django.models import CourseKeyField
class | (migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='CourseGoal',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, pr... | Migration | identifier_name |
core.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
*/ | * @module
* @description
* Entry point from which you should import all public core APIs.
*/
export * from './metadata';
export * from './version';
export {TypeDecorator} from './util/decorators';
export * from './di';
export {createPlatform, assertPlatform, destroyPlatform, getPlatform, PlatformRef, ApplicationRef... |
/** | random_line_split |
generation_size.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use crate::utils;
use crate::MononokeSQLBlobGCArgs;
use anyhow::Result;
use bytesize::ByteSize;
use clap::P... | (sizes: &HashMap<Option<u64>, u64>) {
let generations = {
let mut keys: Vec<_> = sizes.keys().collect();
keys.sort_unstable();
keys
};
println!("Generation | Size");
println!("-----------------");
for generation in generations {
let size = ByteSize::b(sizes[generati... | print_sizes | identifier_name |
generation_size.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use crate::utils;
use crate::MononokeSQLBlobGCArgs;
use anyhow::Result;
use bytesize::ByteSize;
use clap::P... | for (shard, sizes) in shard_sizes {
for (generation, (size, chunk_id_count)) in sizes.into_iter() {
let mut sample = scuba_sample_builder.clone();
sample.add("shard", shard);
sample.add_opt("generation", generation);
sample.add("size", size);
sampl... | {
let common_args: MononokeSQLBlobGCArgs = app.args()?;
let max_parallelism: usize = common_args.scheduled_max;
let (sqlblob, shard_range) = utils::get_sqlblob_and_shard_range(&app).await?;
let scuba_sample_builder = app.environment().scuba_sample_builder.clone();
let shard_sizes: Vec<(usize, Ha... | identifier_body |
generation_size.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use crate::utils;
use crate::MononokeSQLBlobGCArgs;
use anyhow::Result;
use bytesize::ByteSize;
use clap::P... | };
println!("{:>10} | {}", generation, size.to_string_as(true));
}
}
pub async fn run(app: MononokeApp, _args: CommandArgs) -> Result<()> {
let common_args: MononokeSQLBlobGCArgs = app.args()?;
let max_parallelism: usize = common_args.scheduled_max;
let (sqlblob, shard_range) = utils:... | Some(g) => g.to_string(), | random_line_split |
ast_util.rs | uint_ty_to_str(t: UintTy, val: Option<u64>) -> String {
let s = match t {
TyU if val.is_some() => "u",
TyU => "uint",
TyU8 => "u8",
TyU16 => "u16",
TyU32 => "u32",
TyU64 => "u64"
};
match val {
Some(n) => format!("{}{}", n, s),
None => s.to_s... |
/// Generate a "pretty" name for an `impl` from its type and trait.
/// This is designed so that symbols of `impl`'d methods give some
/// hint of where they came from, (previously they would all just be
/// listed as `__extensions__::method_name::hash`, with no indication
/// of the type).
pub fn impl_pretty_name(tr... | {
if is_unguarded(a) {
Some(/* FIXME (#2543) */ a.pats.clone())
} else {
None
}
} | identifier_body |
ast_util.rs | (),
Provided(ref m) => {
TypeMethod {
ident: m.ident,
attrs: m.attrs.clone(),
fn_style: m.fn_style,
decl: m.decl,
generics: m.generics.clone(),
explicit_self: m.explicit_self,
id: m.id,
... | result: Cell<IdRange>, | random_line_split | |
ast_util.rs | uint_ty_to_str(t: UintTy, val: Option<u64>) -> String {
let s = match t {
TyU if val.is_some() => "u",
TyU => "uint",
TyU8 => "u8",
TyU16 => "u16",
TyU32 => "u32",
TyU64 => "u64"
};
match val {
Some(n) => format!("{}{}", n, s),
None => s.to_s... | (trait_ref: &Option<TraitRef>, ty: &Ty) -> Ident {
let mut pretty = pprust::ty_to_str(ty);
match *trait_ref {
Some(ref trait_ref) => {
pretty.push_char('.');
pretty.push_str(pprust::path_to_str(&trait_ref.path).as_slice());
}
None => {}
}
token::gensym_ide... | impl_pretty_name | identifier_name |
solarSwitch.py | import omf.cosim
glw = omf.cosim.GridLabWorld('6267', 'localhost', 'GC-solarAdd.glm', '2000-01-01 0:00:00')
glw.start()
print (glw.readClock())
# Changing solar gen status.
print (glw.read('test_solar', 'generator_status'))
glw.write('test_solar','generator_status', 'OFFLINE')
print ('Switched off solar')
print (glw.r... | glw.write('test_solar_inverter','Q_Out', '1000')
print ('Change Q_Out')
print (glw.read('test_solar_inverter', 'Q_Out'))
#glw.waitUntil('2000-01-01 0:30:00')
#print ('Stepped ahead 12 hours')
print (glw.readClock())
glw.resume()
print (glw.readClock())
glw.shutdown() | print (glw.read('test_solar_inverter', 'Q_Out')) | random_line_split |
packageListContainer.js | import React from "react";
import { composeWithTracker } from "@reactioncommerce/reaction-components";
import { Template } from "meteor/templating";
import { Roles } from "meteor/alanning:roles";
import { Reaction } from "/client/api";
/**
* Push package into action view navigation stack
* @param {SyntheticEvent} e... | const dashboard = Reaction.Apps({ provides: "dashboard", enabled: true, audience })
.filter((d) => typeof Template[d.template] !== "undefined") || [];
onData(null, {
currentView: Reaction.getActionView(),
groupedPackages: {
actions: {
title: "Actions",
i18nKeyTitle: "admin.dashboa... | function composer(props, onData) {
const audience = Roles.getRolesForUser(Reaction.getUserId(), Reaction.getShopId());
const settings = Reaction.Apps({ provides: "settings", enabled: true, audience }) || [];
| random_line_split |
packageListContainer.js | import React from "react";
import { composeWithTracker } from "@reactioncommerce/reaction-components";
import { Template } from "meteor/templating";
import { Roles } from "meteor/alanning:roles";
import { Reaction } from "/client/api";
/**
* Push package into action view navigation stack
* @param {SyntheticEvent} e... | (event, app) {
Reaction.hideActionViewDetail();
Reaction.showActionView(app);
}
function composer(props, onData) {
const audience = Roles.getRolesForUser(Reaction.getUserId(), Reaction.getShopId());
const settings = Reaction.Apps({ provides: "settings", enabled: true, audience }) || [];
const dashboard = Re... | handleOpenShortcut | identifier_name |
packageListContainer.js | import React from "react";
import { composeWithTracker } from "@reactioncommerce/reaction-components";
import { Template } from "meteor/templating";
import { Roles } from "meteor/alanning:roles";
import { Reaction } from "/client/api";
/**
* Push package into action view navigation stack
* @param {SyntheticEvent} e... |
return composeWithTracker(composer)(CompositeComponent);
}
| {
return (
<Comp {...props} />
);
} | identifier_body |
sha1-hmac.py | # -*- coding: utf-8 -*-
"""
Auth-SHA1/HMAC
~~~~~~~~~~~~~~
Securing an Eve-powered API with Basic Authentication (RFC2617).
This script assumes that user accounts are stored in a MongoDB collection
('accounts'), and that passwords are stored as SHA1/HMAC hashes. All API
resources/methods will ... | (BasicAuth):
def check_auth(self, username, password, allowed_roles, resource, method):
# use Eve's own db driver; no additional connections/resources are used
accounts = app.data.driver.db['accounts']
account = accounts.find_one({'username': username})
return account and \
... | Sha1Auth | identifier_name |
sha1-hmac.py | # -*- coding: utf-8 -*-
"""
Auth-SHA1/HMAC
~~~~~~~~~~~~~~
Securing an Eve-powered API with Basic Authentication (RFC2617).
This script assumes that user accounts are stored in a MongoDB collection
('accounts'), and that passwords are stored as SHA1/HMAC hashes. All API
resources/methods will ... | app = Eve(auth=Sha1Auth, settings=SETTINGS)
app.run() | conditional_block | |
sha1-hmac.py | # -*- coding: utf-8 -*-
"""
Auth-SHA1/HMAC
~~~~~~~~~~~~~~
Securing an Eve-powered API with Basic Authentication (RFC2617).
This script assumes that user accounts are stored in a MongoDB collection
('accounts'), and that passwords are stored as SHA1/HMAC hashes. All API
resources/methods will ... |
if __name__ == '__main__':
app = Eve(auth=Sha1Auth, settings=SETTINGS)
app.run()
| accounts = app.data.driver.db['accounts']
account = accounts.find_one({'username': username})
return account and \
check_password_hash(account['password'], password) | identifier_body |
sha1-hmac.py | # -*- coding: utf-8 -*-
"""
Auth-SHA1/HMAC
~~~~~~~~~~~~~~
Securing an Eve-powered API with Basic Authentication (RFC2617).
This script assumes that user accounts are stored in a MongoDB collection
('accounts'), and that passwords are stored as SHA1/HMAC hashes. All API
resources/methods will ... | return account and \
check_password_hash(account['password'], password)
if __name__ == '__main__':
app = Eve(auth=Sha1Auth, settings=SETTINGS)
app.run() | def check_auth(self, username, password, allowed_roles, resource, method):
# use Eve's own db driver; no additional connections/resources are used
accounts = app.data.driver.db['accounts']
account = accounts.find_one({'username': username}) | random_line_split |
headerBarController.js | function(viewData) {
$scope.$broadcast('$atajoUiView.beforeEnter', viewData);
};
self.title = function(newTitleText) {
if (arguments.length && newTitleText !== titleText) {
getEle(TITLE).innerHTML = newTitleText;
titleText = newTitleText;
titleTextWidth = 0;
}
return titleText;
... |
if (c.classList.contains(HIDE)) {
continue;
}
if (isBackShown && c === backBtnEle) {
for (y = 0; y < c.childNodes.length; y++) {
b = c.childNodes[y];
if (b.nodeType == 1) {
if (b.classList.contains(BACK_TEXT)) {
for (... | random_line_split | |
headerBarController.js | Config.backButton.icon()) {
ele = getEle(BACK_BUTTON + ' .icon');
if (ele) {
self.backButtonIcon = $atajoUiConfig.backButton.icon();
ele.className = 'icon ' + self.backButtonIcon;
}
}
if (self.backButtonText !== $atajoUiConfig.backButton.text()) {
... | getEle | identifier_name | |
headerBarController.js | ele.className = 'icon ' + self.backButtonIcon;
}
}
if (self.backButtonText !== $atajoUiConfig.backButton.text()) {
ele = getEle(BACK_BUTTON + ' .back-text');
if (ele) {
ele.textContent = self.backButtonText = $atajoUiConfig.backButton.text();
... | {
if (!eleCache[className]) {
eleCache[className] = $element[0].querySelector('.' + className);
}
return eleCache[className];
} | identifier_body | |
headerBarController.js | (viewData) {
$scope.$broadcast('$atajoUiView.beforeEnter', viewData);
};
self.title = function(newTitleText) {
if (arguments.length && newTitleText !== titleText) {
getEle(TITLE).innerHTML = newTitleText;
titleText = newTitleText;
titleTextWidth = 0;
}
return titleText;
};
... |
return isBackEnabled;
};
self.showBack = function(shouldShow, disableReset) {
// different from enableBack() because this will always have the back
// visually hidden if false, even if the history says it should show
if (arguments.length) {
isBackShown = shouldShow;
if (!disableReset)... | {
isBackEnabled = shouldEnable;
if (!disableReset) self.updateBackButton();
} | conditional_block |
types.ts | at https://angular.io/license
*/
import {PipeTransform} from '../change_detection/change_detection';
import {QueryList} from '../linker/query_list';
import {TemplateRef} from '../linker/template_ref';
import {ViewContainerRef} from '../linker/view_container_ref';
import {RenderComponentType, Renderer, RootRenderer} ... | (view: ViewData, index: number): PureExpressionData {
return <any>view.nodes[index];
}
/**
* Accessor for view.nodes, enforcing that every usage site stays monomorphic.
*/
export function asQueryList(view: ViewData, index: number): QueryList<any> {
return <any>view.nodes[index];
}
export interface Services {
| asPureExpressionData | identifier_name |
types.ts | at https://angular.io/license
*/
import {PipeTransform} from '../change_detection/change_detection';
import {QueryList} from '../linker/query_list';
import {TemplateRef} from '../linker/template_ref';
import {ViewContainerRef} from '../linker/view_container_ref';
import {RenderComponentType, Renderer, RootRenderer} ... |
export type ViewUpdateFn = (updater: NodeUpdater, view: ViewData) => void;
export interface NodeUpdater {
checkInline(
view: ViewData, nodeIndex: number, v0?: any, v1?: any, v2?: any, v3?: any, v4?: any, v5?: any,
v6?: any, v7?: any, v8?: any, v9?: any): any;
checkDynamic(view: ViewData, nodeIndex: nu... | * This includes query ids from templates as well.
*/
nodeMatchedQueries: {[queryId: string]: boolean};
} | random_line_split |
repeated_letters.py | from pprint import pprint
from Conundrum.utils import sanitize
def decrypt(msg: str, repeated_letter: str) -> str:
"""
Extract every letter after an occurrence of the repeated letter
"""
msg = sanitize(msg)
result = []
remove_next = False
for letter in msg:
|
return ''.join(result)
def decrypt_try_all(msg: str) -> [str]:
msg = sanitize(msg)
letters_to_try = sorted({letter for letter in msg})
return {letter: decrypt(msg, letter) for letter in letters_to_try}
if __name__ == '__main__':
# Used in Movies 4
encrypted_msg = 'i bet pews or leisure chai... | take_this = remove_next
remove_next = letter == repeated_letter
if take_this:
result += letter | conditional_block |
repeated_letters.py | from pprint import pprint
from Conundrum.utils import sanitize
def | (msg: str, repeated_letter: str) -> str:
"""
Extract every letter after an occurrence of the repeated letter
"""
msg = sanitize(msg)
result = []
remove_next = False
for letter in msg:
take_this = remove_next
remove_next = letter == repeated_letter
if take_this:
... | decrypt | identifier_name |
repeated_letters.py | from pprint import pprint
from Conundrum.utils import sanitize
def decrypt(msg: str, repeated_letter: str) -> str:
"""
Extract every letter after an occurrence of the repeated letter
"""
msg = sanitize(msg)
result = []
remove_next = False
for letter in msg:
take_this = remove_nex... |
if __name__ == '__main__':
# Used in Movies 4
encrypted_msg = 'i bet pews or leisure chains can seem to stink of effort, george, under no illusions of vanity'
pprint(decrypt_try_all(encrypted_msg))
| msg = sanitize(msg)
letters_to_try = sorted({letter for letter in msg})
return {letter: decrypt(msg, letter) for letter in letters_to_try} | identifier_body |
xsel.py | # -*- coding: utf-8 -*-
"""
Display X selection.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0.5)
command: the clipboard command to run (default 'xsel -o')
format: display format for this module (default '{selection}')
max_size: strip the selection to this value (... | (self):
selection = self.py3.command_output(self.command)
if len(selection) >= self.max_size:
if self.symmetric is True:
split = int(self.max_size / 2) - 1
selection = selection[:split] + '..' + selection[-split:]
else:
selection = ... | xsel | identifier_name |
xsel.py | # -*- coding: utf-8 -*-
"""
Display X selection.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0.5)
command: the clipboard command to run (default 'xsel -o')
format: display format for this module (default '{selection}')
max_size: strip the selection to this value (... |
return {
'cached_until': self.py3.time_in(self.cache_timeout),
'full_text': self.py3.safe_format(self.format, {'selection': selection})
}
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(P... | selection = selection[:self.max_size] | conditional_block |
xsel.py | # -*- coding: utf-8 -*-
"""
Display X selection.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0.5)
command: the clipboard command to run (default 'xsel -o')
format: display format for this module (default '{selection}')
max_size: strip the selection to this value (... |
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
| selection = self.py3.command_output(self.command)
if len(selection) >= self.max_size:
if self.symmetric is True:
split = int(self.max_size / 2) - 1
selection = selection[:split] + '..' + selection[-split:]
else:
selection = selection[:self.... | identifier_body |
xsel.py | # -*- coding: utf-8 -*-
"""
Display X selection. | format: display format for this module (default '{selection}')
max_size: strip the selection to this value (default 15)
symmetric: show beginning and end of the selection string
with respect to configured max_size. (default True)
Format placeholders:
{selection} output from clipboard command
R... |
Configuration parameters:
cache_timeout: refresh interval for this module (default 0.5)
command: the clipboard command to run (default 'xsel -o') | random_line_split |
float.rs | 10 and the
/// exponent sign being `e` or `E`. For example, 1000 would be printed
/// 1e3.
ExpDec
}
/// The number of digits used for emitting the fractional part of a number, if
/// any.
pub enum SignificantDigits {
/// At most the given number of digits will be printed, truncating any
/// traili... | for j in range(i as uint + 1, end).rev() {
buf[j + 1] = buf[j];
}
buf[(i + 1) as uint] = value2ascii(1);
end += 1;
break;
}
// Skip... | || buf[i as uint] == b'-'
|| buf[i as uint] == b'+' { | random_line_split |
float.rs | use a capital letter for the exponent sign, if
* exponential notation is desired.
* - `f` - A closure to invoke with the bytes representing the
* float.
*
* # Failure
* - Fails if `radix` < 2 or `radix` > 36.
* - Fails if `radix` > 14 and `exp_format` is `ExpD... | write | identifier_name | |
dst-coerce-rc.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> i32 {
*self
}
}
fn main() {
let a: Rc<[i32; 3]> = Rc::new([1, 2, 3]);
let b: Rc<[i32]> = a;
assert_eq!(b[0], 1);
assert_eq!(b[1], 2);
assert_eq!(b[2], 3);
let a: Rc<i32> = Rc::new(42);
let b: Rc<Baz> = a.clone();
assert_eq!(b.get(), 42);
let _c = b.clone();
... | get | identifier_name |
dst-coerce-rc.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // 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
// except according to those terms.
// Test a very simple custom DST coercion.
#![feature(core)]
use std::rc::Rc;
trait B... | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
dst-coerce-rc.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
fn main() {
let a: Rc<[i32; 3]> = Rc::new([1, 2, 3]);
let b: Rc<[i32]> = a;
assert_eq!(b[0], 1);
assert_eq!(b[1], 2);
assert_eq!(b[2], 3);
let a: Rc<i32> = Rc::new(42);
let b: Rc<Baz> = a.clone();
assert_eq!(b.get(), 42);
let _c = b.clone();
}
| {
*self
} | identifier_body |
verboseRequester.ts | /*
* Copyright 2012-2015 Metamarkets Group Inc.
* Copyright 2015-2020 Imply Data, 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.org/licenses/LICENSE-2... | const ctx = param.context ? ` [context: ${JSON.stringify(param.context)}]` : '';
printLine(`Requester ${param.name} sending query ${param.queryNumber}:${ctx}`);
printLine(JSON.stringify(param.query, null, 2));
printLine('^^^^^^^^^^^^^^^^^^^^^^^^^^');
});
const onSuccess =
parameters.o... | {
const requester = parameters.requester;
const myName = parameters.name || 'rq' + String(Math.random()).substr(2, 5);
// Back compat.
if ((parameters as any).preQuery) {
console.warn('verboseRequesterFactory option preQuery has been renamed to onQuery');
parameters.onQuery = (parameters as any).preQue... | identifier_body |
verboseRequester.ts | /*
* Copyright 2012-2015 Metamarkets Group Inc.
* Copyright 2015-2020 Imply Data, 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.org/licenses/LICENSE-2... |
const printLine =
parameters.printLine ||
((line: string): void => {
console['log'](line);
});
const onQuery =
parameters.onQuery ||
((param: CallbackParameters): void => {
printLine('vvvvvvvvvvvvvvvvvvvvvvvvvv');
const ctx = param.context ? ` [context: ${JSON.stringify(para... | {
console.warn('verboseRequesterFactory option preQuery has been renamed to onQuery');
parameters.onQuery = (parameters as any).preQuery;
} | conditional_block |
verboseRequester.ts | /*
* Copyright 2012-2015 Metamarkets Group Inc.
* Copyright 2015-2020 Imply Data, 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.org/licenses/LICENSE-2... | const stream = requester(request);
let errorSeen = false;
stream.on('error', (error: Error) => {
errorSeen = true;
onError({
name: myName,
queryNumber: myQueryNumber,
query: request.query,
context: request.context,
time: Date.now() - startTime,
er... | const startTime = Date.now(); | random_line_split |
verboseRequester.ts | /*
* Copyright 2012-2015 Metamarkets Group Inc.
* Copyright 2015-2020 Imply Data, 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.org/licenses/LICENSE-2... | <T>(
parameters: VerboseRequesterParameters<T>,
): PlywoodRequester<any> {
const requester = parameters.requester;
const myName = parameters.name || 'rq' + String(Math.random()).substr(2, 5);
// Back compat.
if ((parameters as any).preQuery) {
console.warn('verboseRequesterFactory option preQuery has bee... | verboseRequesterFactory | identifier_name |
location.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
*/
import {EventEmitter, Injectable} from '@angular/core';
import {LocationStrategy} from './location_strategy';
/** ... |
if (end.startsWith('/')) {
slashes++;
}
if (slashes == 2) {
return start + end.substring(1);
}
if (slashes == 1) {
return start + end;
}
return start + '/' + end;
}
/**
* If url has a trailing slash, remove it, otherwise return url as is.
*/
public static stri... | {
slashes++;
} | conditional_block |
location.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
*/
import {EventEmitter, Injectable} from '@angular/core';
import {LocationStrategy} from './location_strategy';
/** ... | (url: string): string {
return url.replace(/\/index.html$/, '');
}
| _stripIndexHtml | identifier_name |
location.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
*/
import {EventEmitter, Injectable} from '@angular/core';
import {LocationStrategy} from './location_strategy';
/** ... |
/**
* Given a string representing a URL, returns the platform-specific external URL path.
* If the given URL doesn't begin with a leading slash (`'/'`), this method adds one
* before normalizing. This method will also add a hash if `HashLocationStrategy` is
* used, or the `APP_BASE_HREF` if the `PathLoc... | {
return Location.stripTrailingSlash(_stripBaseHref(this._baseHref, _stripIndexHtml(url)));
} | identifier_body |
location.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
*/
import {EventEmitter, Injectable} from '@angular/core';
import {LocationStrategy} from './location_strategy';
/** ... |
/**
* Given a string representing a URL, returns the platform-specific external URL path.
* If the given URL doesn't begin with a leading slash (`'/'`), this method adds one
* before normalizing. This method will also add a hash if `HashLocationStrategy` is
* used, or the `APP_BASE_HREF` if the `PathLoca... | } | random_line_split |
ant_move.py | from edge import DummyEdgeEnd
from simulation_event import AbstractSimulationEvent
from stats import TripStats
class AbstractAntMove(AbstractSimulationEvent):
| changed.append(self.destination.point)
self.trip_stats.food_found()
self.destination.point.food -= 1
self.ant.food += 1
stats.food_found(self.trip_stats)
stats.present()
elif self.destination.point.is_anthill(): # ant has returned to the an... | def __init__(self, ant, origin, destination, end_time, pheromone_to_drop, trip_stats):
self.ant = ant
self.origin = origin
self.destination = destination
if self.origin is not None and self.destination is not None:
if self.origin.edge is not None and self.destination.edge is ... | identifier_body |
ant_move.py | from edge import DummyEdgeEnd
from simulation_event import AbstractSimulationEvent
from stats import TripStats
class AbstractAntMove(AbstractSimulationEvent):
def __init__(self, ant, origin, destination, end_time, pheromone_to_drop, trip_stats):
self.ant = ant
self.origin = origin
self.dest... |
self.end_time = end_time
self.pheromone_to_drop = pheromone_to_drop
self.trip_stats = trip_stats
def process_start(self):
self.origin.drop_pheromone(self.pheromone_to_drop)
return frozenset((self.origin.edge, self.origin.point))
def process_end(self, reality, stats):
... | assert self.origin.edge == self.destination.edge | conditional_block |
ant_move.py | from edge import DummyEdgeEnd
from simulation_event import AbstractSimulationEvent
from stats import TripStats
class AbstractAntMove(AbstractSimulationEvent):
def __init__(self, ant, origin, destination, end_time, pheromone_to_drop, trip_stats):
self.ant = ant
self.origin = origin
self.dest... | (AbstractAntMove):
def __init__(self, ant, anthill, end_time):
super(AntRestartMove, self).__init__(ant, None, anthill, end_time=end_time, pheromone_to_drop=0, trip_stats=TripStats())
def process_start(self):
return frozenset()
class AntStartMove(AntRestartMove):
def __init__(self, ant, ant... | AntRestartMove | identifier_name |
ant_move.py | from edge import DummyEdgeEnd
from simulation_event import AbstractSimulationEvent
from stats import TripStats
class AbstractAntMove(AbstractSimulationEvent):
def __init__(self, ant, origin, destination, end_time, pheromone_to_drop, trip_stats):
self.ant = ant
self.origin = origin
self.dest... | stats.present()
elif self.destination.point.is_anthill(): # ant has returned to the anthill
if self.ant.food: # with food
changed.append(self.destination.point)
self.destination.point.food += self.ant.food
self.trip_stats.back_home()
... | self.ant.food += 1
stats.food_found(self.trip_stats) | random_line_split |
index.ts | 'use strict';
type SidebarOnClickFunction = () => any;
import BaseComponent, { BaseOptions } from '../base';
import { asyncFor } from 'then-utils';
const componentReady = Symbol.for('component.ready');
interface SidebarOptions extends BaseOptions {};
interface SidebarItemObject {
name?: string;
onclick?: Sideba... |
}
export default SidebarComponent;
| {
return asyncFor(this.links, (i: number, link: HTMLAnchorElement) => {
if (link.classList.contains('active')) link.classList.remove('active');
return Promise.resolve();
}).then(() => {
this.links[index].classList.add('active');
});
} | identifier_body |
index.ts | 'use strict';
type SidebarOnClickFunction = () => any;
import BaseComponent, { BaseOptions } from '../base';
import { asyncFor } from 'then-utils';
const componentReady = Symbol.for('component.ready');
interface SidebarOptions extends BaseOptions {};
interface SidebarItemObject {
name?: string;
onclick?: Sideba... | extends BaseComponent {
elm: HTMLElement;
links: HTMLAnchorElement[];
constructor(opts: SidebarOptions) {
super(opts);
// Element Creation
this.elm = document.createElement('nav');
// Element Classes
this.elm.className = 'component sidebar';
// Class Properties
this.links = [];
... | SidebarComponent | identifier_name |
index.ts | 'use strict';
type SidebarOnClickFunction = () => any;
import BaseComponent, { BaseOptions } from '../base';
import { asyncFor } from 'then-utils';
const componentReady = Symbol.for('component.ready');
interface SidebarOptions extends BaseOptions {};
interface SidebarItemObject {
name?: string;
onclick?: Sideba... |
this[componentReady]();
}
addItem({ name = 'Item', onclick = null, index = null }: SidebarItemObject = {}): Promise<void> {
return new Promise((resolve, reject) => {
// Element Creation
const a = document.createElement('a');
// Element Properties
a.href = '#';
//
a.oncl... | // Element Classes
this.elm.className = 'component sidebar';
// Class Properties
this.links = []; | random_line_split |
appthread.rs | Sender};
use heap::{Object, TraceStack};
use journal;
use trace::Trace;
/// Each thread gets it's own EntrySender
thread_local!(
static GC_JOURNAL: Cell<*const EntrySender> = Cell::new(null())
);
/// GcBox struct and traits: a boxed object that is GC managed
pub struct GcBox<T: Trace> {
value: T,
}
/// Ro... | <T: Trace>(object: &T) -> TraitObject {
let trace: &Trace = object;
unsafe { transmute(trace) }
}
/// Write a reference count increment to the journal for a newly allocated object
#[inline]
fn write<T: Trace>(object: &T, is_new: bool, flags: usize) {
GC_JOURNAL.with(|j| {
let tx = unsafe { &*j.get... | as_traitobject | identifier_name |
appthread.rs | Sender};
use heap::{Object, TraceStack};
use journal;
use trace::Trace;
/// Each thread gets it's own EntrySender
thread_local!(
static GC_JOURNAL: Cell<*const EntrySender> = Cell::new(null())
);
/// GcBox struct and traits: a boxed object that is GC managed
pub struct GcBox<T: Trace> {
value: T,
}
/// Ro... | }
// GcBox implementation
impl<T: Trace> GcBox<T> {
fn new(value: T) -> GcBox<T> {
GcBox {
value: value,
}
}
}
unsafe impl<T: Trace> Trace for GcBox<T> {
#[inline]
fn traversible(&self) -> bool {
self.value.traversible()
}
#[inline]
unsafe fn trace(&... | {
GC_JOURNAL.with(|j| {
let tx = unsafe { &*j.get() };
let tobj = as_traitobject(object);
// set the refcount-increment bit
let ptr = (tobj.data as usize) | flags;
// set the traversible bit
let mut vtable = tobj.vtable as usize;
if is_new && object.travers... | identifier_body |
appthread.rs | Sender};
use heap::{Object, TraceStack};
use journal;
use trace::Trace;
/// Each thread gets it's own EntrySender
thread_local!(
static GC_JOURNAL: Cell<*const EntrySender> = Cell::new(null())
);
/// GcBox struct and traits: a boxed object that is GC managed
pub struct GcBox<T: Trace> {
value: T,
}
/// Ro... | }
}
fn ptr(&self) -> *mut GcBox<T> {
self.ptr
}
fn value(&self) -> &T {
unsafe { &(*self.ptr).value }
}
fn value_mut(&mut self) -> &mut T {
unsafe { &mut (*self.ptr).value }
}
}
impl<T: Trace> Deref for Gc<T> {
type Target = T;
fn deref(&self) ->... | ptr: ptr, | random_line_split |
appthread.rs | Sender};
use heap::{Object, TraceStack};
use journal;
use trace::Trace;
/// Each thread gets it's own EntrySender
thread_local!(
static GC_JOURNAL: Cell<*const EntrySender> = Cell::new(null())
);
/// GcBox struct and traits: a boxed object that is GC managed
pub struct GcBox<T: Trace> {
value: T,
}
/// Ro... |
}
/// Pointer equality comparison.
pub fn is(&self, other: Gc<T>) -> bool {
self.ptr == other.ptr
}
fn from_raw(ptr: *mut GcBox<T>) -> Gc<T> {
Gc {
ptr: ptr,
}
}
fn ptr(&self) -> *mut GcBox<T> {
self.ptr
}
fn value(&self) -> &T {
... | {
Some(self.ptr)
} | conditional_block |
test_voxel.py | import unittest
import decodes.core as dc
from decodes.core import *
from decodes.extensions.voxel import *
class Tests(unittest.TestCase):
def test_constructor(self):
bounds = Bounds(center=Point(),dim_x=8,dim_y=8,dim_z=8)
vf = VoxelField(bounds,4,4,4)
vf.set(0,0,0,10.0)
vf.set(3... | (self):
bounds = Bounds(center=Point(),dim_x=8,dim_y=8,dim_z=8)
vf = VoxelField(bounds,4,4,4)
self.assertEqual(vf.dim_pixel,Vec(2,2,2))
self.assertEqual(vf.cpt_at(0,0,0),Point(-3,-3,-3))
vf.bounds = Bounds(center=Point(),dim_x=12,dim_y=12,dim_z=8)
self.assertEqual(vf.di... | test_bounds_and_cpt | identifier_name |
test_voxel.py | import unittest
import decodes.core as dc
from decodes.core import *
from decodes.extensions.voxel import *
class Tests(unittest.TestCase):
| def test_constructor(self):
bounds = Bounds(center=Point(),dim_x=8,dim_y=8,dim_z=8)
vf = VoxelField(bounds,4,4,4)
vf.set(0,0,0,10.0)
vf.set(3,3,3,10.0)
self.assertEqual(vf.get(0,0,0),10.0)
self.assertEqual(vf.get(3,3,3),10.0)
self.assertEqual(vf.get(2,2,2),0.... | random_line_split | |
test_voxel.py | import unittest
import decodes.core as dc
from decodes.core import *
from decodes.extensions.voxel import *
class Tests(unittest.TestCase):
| def test_constructor(self):
bounds = Bounds(center=Point(),dim_x=8,dim_y=8,dim_z=8)
vf = VoxelField(bounds,4,4,4)
vf.set(0,0,0,10.0)
vf.set(3,3,3,10.0)
self.assertEqual(vf.get(0,0,0),10.0)
self.assertEqual(vf.get(3,3,3),10.0)
self.assertEqual(vf.get(2,2,2),0.0)
... | identifier_body | |
factories.py | import factory
from ...models import Dashboard, Link, ModuleType, Module
from ....organisation.tests.factories import NodeFactory, NodeTypeFactory
class DashboardFactory(factory.DjangoModelFactory):
class Meta:
model = Dashboard
status = 'published'
title = "title"
slug = factory.Sequence(l... | (NodeFactory):
name = factory.Sequence(lambda n: 'agency-%s' % n)
typeOf = factory.SubFactory(AgencyTypeFactory)
class AgencyWithDepartmentFactory(AgencyFactory):
parent = factory.SubFactory(DepartmentFactory)
class ServiceFactory(NodeFactory):
parent = factory.SubFactory(AgencyWithDepartmentFactory... | AgencyFactory | identifier_name |
factories.py | import factory
from ...models import Dashboard, Link, ModuleType, Module
from ....organisation.tests.factories import NodeFactory, NodeTypeFactory
class DashboardFactory(factory.DjangoModelFactory):
class Meta:
model = Dashboard
status = 'published'
title = "title"
slug = factory.Sequence(l... |
name = factory.Sequence(lambda n: 'name %s' % n)
schema = {}
class ModuleFactory(factory.DjangoModelFactory):
class Meta:
model = Module
type = factory.SubFactory(ModuleTypeFactory)
dashboard = factory.SubFactory(DashboardFactory)
slug = factory.Sequence(lambda n: 'slug{}'.format(n... | model = ModuleType | identifier_body |
factories.py | import factory
from ...models import Dashboard, Link, ModuleType, Module
from ....organisation.tests.factories import NodeFactory, NodeTypeFactory
class DashboardFactory(factory.DjangoModelFactory):
class Meta:
model = Dashboard
status = 'published'
title = "title"
slug = factory.Sequence(l... | name = factory.Sequence(lambda n: 'name %s' % n)
schema = {}
class ModuleFactory(factory.DjangoModelFactory):
class Meta:
model = Module
type = factory.SubFactory(ModuleTypeFactory)
dashboard = factory.SubFactory(DashboardFactory)
slug = factory.Sequence(lambda n: 'slug{}'.format(n))... | random_line_split | |
withFieldWillValidateEventEmitter.ts | import { Constructor } from './Constructor';
import { EventEmitter } from './EventEmitter';
export const FieldWillValidateEvent = 'FIELD_WILL_VALIDATE_EVENT';
// [TypeScript 2.2 Support for Mix-in classes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html)
// eslint-disable-next-line @typ... | addFieldWillValidateEventListener(listener: Listener) {
this.fieldWillValidateEventEmitter.addListener(FieldWillValidateEvent, listener);
}
removeFieldWillValidateEventListener(listener: Listener) {
this.fieldWillValidateEventEmitter.removeListener(FieldWillValidateEvent, listener);
}
};
... | random_line_split | |
withFieldWillValidateEventEmitter.ts | import { Constructor } from './Constructor';
import { EventEmitter } from './EventEmitter';
export const FieldWillValidateEvent = 'FIELD_WILL_VALIDATE_EVENT';
// [TypeScript 2.2 Support for Mix-in classes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html)
// eslint-disable-next-line @typ... | }
| {
type ListenerArg = string;
type ListenerReturnType = void;
type Listener = (fieldName: ListenerArg) => ListenerReturnType;
return class FieldWillValidateEventEmitter extends Base {
fieldWillValidateEventEmitter = new EventEmitter<[ListenerArg], ListenerReturnType>();
emitFieldWillValidateEvent(field... | identifier_body |
withFieldWillValidateEventEmitter.ts | import { Constructor } from './Constructor';
import { EventEmitter } from './EventEmitter';
export const FieldWillValidateEvent = 'FIELD_WILL_VALIDATE_EVENT';
// [TypeScript 2.2 Support for Mix-in classes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html)
// eslint-disable-next-line @typ... | (fieldName: string) {
return this.fieldWillValidateEventEmitter.emitSync(FieldWillValidateEvent, fieldName);
}
addFieldWillValidateEventListener(listener: Listener) {
this.fieldWillValidateEventEmitter.addListener(FieldWillValidateEvent, listener);
}
removeFieldWillValidateEventListener(li... | emitFieldWillValidateEvent | identifier_name |
reacher.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
def get_observation(self, physics):
"""Returns an observation of the state and the target position."""
obs = collections.OrderedDict()
obs['position'] = physics.position()
obs['to_target'] = physics.finger_to_target()
obs['velocity'] = physics.velocity()
return obs
def get_reward(self, ph... | """Sets the state of the environment at the start of each episode."""
physics.named.model.geom_size['target', 0] = self._target_size
randomizers.randomize_limited_and_rotational_joints(physics, self.random)
# Randomize target position
angle = self.random.uniform(0, 2 * np.pi)
radius = self.random.u... | identifier_body |
reacher.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | (time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns reacher with sparse reward with 1e-2 tol and randomized target."""
physics = Physics.from_xml_string(*get_model_and_assets())
task = Reacher(target_size=_SMALL_TARGET, random=random)
environment_kwargs = environment_kwargs or {}
... | hard | identifier_name |
reacher.py | # Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
def initialize_episode(self, physics):
"""Sets the state of the environment at the start of each episode."""
physics.named.model.geom_size['target', 0] = self._target_size
randomizers.randomize_limited_and_rotational_joints(physics, self.random)
# Randomize target position
angle = self.random.un... | automatically (default).
"""
self._target_size = target_size
super().__init__(random=random) | random_line_split |
Score.js | (function() {
function Score() |
// Basically: ... Button extends Container ... (below returns a prototype)
var p = createjs.extend(Score, createjs.Container);
p.setup = function() {
var fontSize = this.height * 0.40;
var font = fontSize + "px " + properties.FONT; // TODO: make a global font
var text = new createjs.Text("0", font, "#FFF");
te... | {
this.Container_constructor(); // Basically: super();
// Layout
this.width = properties.TOP1_WIDTH;
this.height = properties.TOP1_HEIGHT;
this.txt;
this.setup();
} | identifier_body |
Score.js | this.Container_constructor(); // Basically: super();
// Layout
this.width = properties.TOP1_WIDTH;
this.height = properties.TOP1_HEIGHT;
this.txt;
this.setup();
}
// Basically: ... Button extends Container ... (below returns a prototype)
var p = createjs.extend(Score, createjs.Container);
p.setup = fun... | (function() {
function Score() { | random_line_split | |
Score.js | (function() {
function | () {
this.Container_constructor(); // Basically: super();
// Layout
this.width = properties.TOP1_WIDTH;
this.height = properties.TOP1_HEIGHT;
this.txt;
this.setup();
}
// Basically: ... Button extends Container ... (below returns a prototype)
var p = createjs.extend(Score, createjs.Container);
p.setup ... | Score | identifier_name |
bamReader.js | /*
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 The Regents of the University of California
* Author: Jim Robinson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without res... | {
constructor(config, genome) {
this.config = config
this.genome = genome
this.bamPath = config.url
this.baiPath = config.indexURL
BamUtils.setReaderDefaults(this, config)
}
async readAlignments(chr, bpStart, bpEnd) {
const chrToIndex = await this.getChrIn... | BamReader | identifier_name |
bamReader.js | /*
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 The Regents of the University of California
* Author: Jim Robinson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without res... |
}
}
export default BamReader
| {
const header = await this.getHeader()
this.chrToIndex = header.chrToIndex
this.indexToChr = header.chrNames
this.chrAliasTable = header.chrAliasTable
return this.chrToIndex
} | conditional_block |
bamReader.js | /*
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 The Regents of the University of California
* Author: Jim Robinson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without res... | }
async getIndex() {
const genome = this.genome
if (!this.index) {
this.index = await loadIndex(this.baiPath, this.config, genome)
}
return this.index
}
async getChrIndex() {
if (this.chrToIndex) {
return this.chrToIndex
} else {
... | }
return this.header | random_line_split |
wsgi.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# di... |
# Need to register global_opts
from jacket.common.storage import config
from jacket import rpc
from jacket.storage import version
CONF = cfg.CONF
def initialize_application():
storage.register_all()
CONF(sys.argv[1:], project='storage',
version=version.version_string())
logging.setup(CONF, "sto... | random_line_split | |
wsgi.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# di... | ():
storage.register_all()
CONF(sys.argv[1:], project='storage',
version=version.version_string())
logging.setup(CONF, "storage")
config.set_middleware_defaults()
rpc.init(CONF)
return wsgi.Loader(CONF).load_app(name='osapi_volume')
| initialize_application | identifier_name |
wsgi.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# di... | storage.register_all()
CONF(sys.argv[1:], project='storage',
version=version.version_string())
logging.setup(CONF, "storage")
config.set_middleware_defaults()
rpc.init(CONF)
return wsgi.Loader(CONF).load_app(name='osapi_volume') | identifier_body | |
String.js | function humanize(string) {
string = string.replace(/-/g, ' ');
string = string.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
return string;
}
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var st... | };
token = S4()+S4()+S4()+S4()+S4()+S4();
m_conn.set( memcachePrefix + token, '1', memcache_memorize_time, function( err ) {
if (err) {
if (debug) console.log("MEMCACHE ERROR DURING SET");
}
});
return token;
} | random_line_split | |
String.js | function humanize(string) {
string = string.replace(/-/g, ' ');
string = string.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
return string;
}
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var st... |
var generateUserToken = function( m_conn ) {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
token = S4()+S4()+S4()+S4()+S4()+S4();
m_conn.set( memcachePrefix + token, '1', memcache_memorize_time, function( err ) {
if (err) {
if ... | {
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
} | identifier_body |
String.js | function humanize(string) {
string = string.replace(/-/g, ' ');
string = string.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
return string;
}
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var st... | (d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var generateUserToken = function( m_conn ) {
va... | ISODateString | identifier_name |
urls.py | """SocialNewspaper URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
... | url(r'^editorial/$', views.editorial, name="editorial"),
url(r'^$', views.editorial, name="home")
] | url(r'^share_article/$', views.share_article, name="share_article"),
url(r'^print_sharing/(?P<article_id>[0-9]+)$', views.print_sharing, name="print_sharing"),
url(r'^insert_article/$', views.insert_article, name="insert_article"),
url(r'^add_interesting/(?P<article_id>[0-9]+)$', views.add_interesting, ... | random_line_split |
Condicional.py | from Estructura import espaceado
from Instrucciones.Arbol_Sintactico_Abstracto import Arbol_Sintactico_Abstracto
class Condicional:
def __init__(self,expresion,if_lista_controladores,else_lista_controladores=None):
self.expresion = expresion
self.if_lista_controladores = if_lista_controladores
self.else_lista_c... | print " - Fracaso: "
instr_list_der = Arbol_Sintactico_Abstracto(self.else_lista_controladores)
instr_list_der.imprimir(" " + espaceado(tabulacion)) | conditional_block | |
Condicional.py | self.expresion = expresion
self.if_lista_controladores = if_lista_controladores
self.else_lista_controladores = else_lista_controladores
self.tipo = 'CONDICIONAL'
def imprimir(self,tabulacion):
print tabulacion + self.tipo
print tabulacion + " - Guardia:",
self.expresion.imprimir(espaceado(tabulacion))... | from Estructura import espaceado
from Instrucciones.Arbol_Sintactico_Abstracto import Arbol_Sintactico_Abstracto
class Condicional:
def __init__(self,expresion,if_lista_controladores,else_lista_controladores=None): | random_line_split | |
Condicional.py | from Estructura import espaceado
from Instrucciones.Arbol_Sintactico_Abstracto import Arbol_Sintactico_Abstracto
class Condicional:
def | (self,expresion,if_lista_controladores,else_lista_controladores=None):
self.expresion = expresion
self.if_lista_controladores = if_lista_controladores
self.else_lista_controladores = else_lista_controladores
self.tipo = 'CONDICIONAL'
def imprimir(self,tabulacion):
print tabulacion + self.tipo
print tabula... | __init__ | identifier_name |
Condicional.py | from Estructura import espaceado
from Instrucciones.Arbol_Sintactico_Abstracto import Arbol_Sintactico_Abstracto
class Condicional:
def __init__(self,expresion,if_lista_controladores,else_lista_controladores=None):
|
def imprimir(self,tabulacion):
print tabulacion + self.tipo
print tabulacion + " - Guardia:",
self.expresion.imprimir(espaceado(tabulacion))
print tabulacion + " - Exito: "
instr_list_izq = Arbol_Sintactico_Abstracto(self.if_lista_controladores)
instr_list_izq.imprimir(" " + espaceado(tabulacion)) ... | self.expresion = expresion
self.if_lista_controladores = if_lista_controladores
self.else_lista_controladores = else_lista_controladores
self.tipo = 'CONDICIONAL' | identifier_body |
self-impl-2.rs | // run-pass
#![allow(dead_code)]
#![allow(unused_variables)]
// Test that we can use `Self` types in impls in the expected way.
// pretty-expanded FIXME #23616
struct Foo;
// Test uses on inherent impl.
impl Foo {
fn | (_x: Self, _y: &Self, _z: Box<Self>) -> Self {
Foo
}
fn baz() {
// Test that Self cannot be shadowed.
type Foo = i32;
// There is no empty method on i32.
Self::empty();
let _: Self = Foo;
}
fn empty() {}
}
// Test uses when implementing a trait and wit... | foo | identifier_name |
self-impl-2.rs | // run-pass
#![allow(dead_code)]
#![allow(unused_variables)]
// Test that we can use `Self` types in impls in the expected way.
// pretty-expanded FIXME #23616
struct Foo;
// Test uses on inherent impl.
impl Foo {
fn foo(_x: Self, _y: &Self, _z: Box<Self>) -> Self {
Foo
}
fn baz() {
// T... | impl SuperBar for Box<Baz<isize>> {
type SuperQux = bool;
}
impl Bar<isize> for Box<Baz<isize>> {
type Qux = i32;
fn bar(_x: Self, _y: &Self, _z: Box<Self>, _: Self::SuperQux) -> Self {
let _: Self::Qux = 42;
let _: <Self as Bar<isize>>::Qux = 42;
let _: Self::SuperQux = true;
... | fn bar(x: Self, y: &Self, z: Box<Self>, _: Self::SuperQux) -> Self;
fn dummy(&self, x: X) { }
}
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.