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 |
|---|---|---|---|---|
core.js | id.substring(elements[x].id.length - 4, elements[x].id.length) === '-div') {
func(document, formId, elements[x].id.substring(4, elements[x].id.length - 4));
}
}
return false;
}
function | (doc, formId, tabKey) {
if (!doc.getElementById('tab-' + tabKey + '-div') || !doc.getElementById('tab-' + tabKey + '-imageToggle')) {
return false;
}
// replaced 'block' with '' to make budgetExpensesRow.tag happy.
doc.getElementById('tab-' + tabKey + '-div').style.display = '';
doc.getElem... | showTab | identifier_name |
observablemixin.d.ts | export interface BindChain {
to(observable: Observable, ...bindProperties: Array<Observable | string | (() => void)>): void;
toMany(observable: Observable[], ...bindProperties: Array<Observable | string | (() => void)>): void;
}
export interface Observable {
/**
* Creates and sets the value of an obse... | *
* button.bind( 'isEnabled' ).to( command, 'value', value => value === 'heading1' );
*
* It is also possible to bind to the same property in an array of observables.
* To bind a `button` to multiple commands (also `Observables`) so that each and every one of them
* must be enabled for ... | * button.bind( 'isEnabled' ).to( command, 'isEnabled', ui, 'isVisible',
* ( isCommandEnabled, isUIVisible ) => isCommandEnabled && isUIVisible );
*
* Using a custom callback allows processing the value before passing it to the target property: | random_line_split |
notes.py | tg_bot.modules.disable import DisableAbleCommandHandler
from tg_bot.modules.helper_funcs.chat_status import user_admin
from tg_bot.modules.helper_funcs.misc import build_keyboard, revert_buttons
from tg_bot.modules.helper_funcs.msg_types import get_note_type
FILE_MATCHER = re.compile(r"^###file_id(!photo)?###:(.*?)(?... |
@run_async
@user_admin
def save(bot: Bot, update: Update):
chat_id = update.effective_chat.id
msg = update.effective_message # type: Optional[Message]
note_name, text, data_type, content, buttons = get_note_type(msg)
if data_type is None:
msg.reply_text("Dude, there's no note")
ret... | message = update.effective_message.text
fst_word = message.split()[0]
no_hash = fst_word[1:]
get(bot, update, no_hash, show_none=False) | identifier_body |
notes.py | dispatcher.bot.send_sticker,
sql.Types.DOCUMENT.value: dispatcher.bot.send_document,
sql.Types.PHOTO.value: dispatcher.bot.send_photo,
sql.Types.AUDIO.value: dispatcher.bot.send_audio,
sql.Types.VOICE.value: dispatcher.bot.send_voice,
sql.Types.VIDEO.value: dispatcher.bot.send_video
}
# Do not as... | __mod_name__ = "Notes"
| random_line_split | |
notes.py | tg_bot.modules.disable import DisableAbleCommandHandler
from tg_bot.modules.helper_funcs.chat_status import user_admin
from tg_bot.modules.helper_funcs.misc import build_keyboard, revert_buttons
from tg_bot.modules.helper_funcs.msg_types import get_note_type
FILE_MATCHER = re.compile(r"^###file_id(!photo)?###:(.*?)(?... | (chat_id, data):
failures = []
for notename, notedata in data.get('extra', {}).items():
match = FILE_MATCHER.match(notedata)
if match:
failures.append(notename)
notedata = notedata[match.end():].strip()
if notedata:
sql.add_note_to_db(chat_id,... | __import_data__ | identifier_name |
notes.py | tg_bot.modules.disable import DisableAbleCommandHandler
from tg_bot.modules.helper_funcs.chat_status import user_admin
from tg_bot.modules.helper_funcs.misc import build_keyboard, revert_buttons
from tg_bot.modules.helper_funcs.msg_types import get_note_type
FILE_MATCHER = re.compile(r"^###file_id(!photo)?###:(.*?)(?... |
return
@run_async
@user_admin
def clear(bot: Bot, update: Update, args: List[str]):
chat_id = update.effective_chat.id
if len(args) >= 1:
notename = args[0]
if sql.rm_note(chat_id, notename):
update.effective_message.reply_text("Successfully removed note.")
else:
... | msg.reply_text("Bots are kinda handicapped by telegram, making it hard for bots to "
"interact with other bots, so I can't save this message "
"like I usually would - do you mind forwarding it and "
"then saving that new message? Thanks!") | conditional_block |
main.rs | #![feature(slice_patterns, convert, vec_push_all)]
extern crate md5;
mod keys;
use keys::*;
fn | () {
// capture arguments
let key = match get_key_from_args() {
Ok(k) => k,
Err(why) => {
handle_errors(why);
return;
},
};
// separate key into segments xxxxx-xxxxx-xxxxx
let segments = match get_key_segments(key.as_ref()) {
Ok(s) => s,
Err(why) => {
handle_errors(why);
return;
},
};
/... | main | identifier_name |
main.rs | #![feature(slice_patterns, convert, vec_push_all)]
extern crate md5;
mod keys;
use keys::*;
fn main() {
// capture arguments
let key = match get_key_from_args() {
Ok(k) => k,
Err(why) => {
handle_errors(why);
return;
},
};
// separate key into segments xxxxx-xxxxx-xxxxx
let segments = match get_key_... | },
};
// check segment 3
let _ = match check_segment3(segments.as_ref(), &mut mod_key) {
Ok(_) => {},
Err(why) => {
handle_errors(why);
return;
},
};
if check_final(mod_key.as_ref()) {
print_key(&segments);
print_key(&mod_key);
} else {
println!("You failed to enter the correct key");
}
} | Ok(_) => {},
Err(why) => {
handle_errors(why);
return; | random_line_split |
main.rs | #![feature(slice_patterns, convert, vec_push_all)]
extern crate md5;
mod keys;
use keys::*;
fn main() | let mut mod_key = match check_segment1(segments.as_ref()) {
Ok(s) => s,
Err(why) => {
handle_errors(why);
return;
},
};
// check segment 2 and store result in seg
let _ = match check_segment2(segments.as_ref(), &mut mod_key) {
Ok(_) => {},
Err(why) => {
handle_errors(why);
return;
},
};
... | {
// capture arguments
let key = match get_key_from_args() {
Ok(k) => k,
Err(why) => {
handle_errors(why);
return;
},
};
// separate key into segments xxxxx-xxxxx-xxxxx
let segments = match get_key_segments(key.as_ref()) {
Ok(s) => s,
Err(why) => {
handle_errors(why);
return;
},
};
// c... | identifier_body |
ICeraonModelAPI.ts | import UserSessionInfo from '../State/Identity/UserSessionInfo';
import Meal from '../State/Meal/Meal';
import Review from '../State/Meal/Review';
import Location from '../State/Meal/Location';
import Tag from '../State/Meal/Tag';
import MealSearchFilter from '../State/Meal/Filters/MealSearchFilter';
import UserIdentit... | success: boolean;
errorCode: ModelUpdateErrorCode;
errorString: string;
modelOnServer: ModelType;
}
export interface ICeraonModelAPI {
getUserSessionInfo() : UserSessionInfo;
getStripeKey() : string;
updatePaymentInfo(stripeToken: string): Promise<ModelUpdateResult<string>>;
updateUserInfo(userInfo: P... | NotFound,
NotAuthorized
}
export interface ModelUpdateResult<ModelType> { | random_line_split |
setup.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (t... | [allura.importers]
github-tracker = forgeimporters.github.tracker:GitHubTrackerImporter
github-wiki = forgeimporters.github.wiki:GitHubWikiImporter
github-repo = forgeimporters.github.code:GitHubRepoImporter
trac-tickets = forgeimporters.trac.tickets:TracTicketImporter
forge-tracker ... | github = forgeimporters.github.project:GitHubProjectImporter
| random_line_split |
np_mask_ops.py | # Copyright 2017 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... |
def intersection(masks1, masks2):
"""Compute pairwise intersection areas between masks.
Args:
masks1: a numpy array with shape [N, height, width] holding N masks. Masks
values are of type np.uint8 and values are in {0,1}.
masks2: a numpy array with shape [M, height, width] holding M masks. Masks
... | """Computes area of masks.
Args:
masks: Numpy array with shape [N, height, width] holding N masks. Masks
values are of type np.uint8 and values are in {0,1}.
Returns:
a numpy array with shape [N*1] representing mask areas.
Raises:
ValueError: If masks.dtype is not np.uint8
"""
if masks.dt... | identifier_body |
np_mask_ops.py | # Copyright 2017 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... |
return answer
def iou(masks1, masks2):
"""Computes pairwise intersection-over-union between mask collections.
Args:
masks1: a numpy array with shape [N, height, width] holding N masks. Masks
values are of type np.uint8 and values are in {0,1}.
masks2: a numpy array with shape [M, height, width] ... | for j in np.arange(m):
answer[i, j] = np.sum(np.minimum(masks1[i], masks2[j]), dtype=np.float32) | conditional_block |
np_mask_ops.py | # Copyright 2017 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... | if masks1.dtype != np.uint8 or masks2.dtype != np.uint8:
raise ValueError('masks1 and masks2 should be of type np.uint8')
intersect = intersection(masks1, masks2)
areas = np.expand_dims(area(masks2), axis=0)
return intersect / (areas + EPSILON) | """ | random_line_split |
np_mask_ops.py | # Copyright 2017 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... | (masks1, masks2):
"""Compute pairwise intersection areas between masks.
Args:
masks1: a numpy array with shape [N, height, width] holding N masks. Masks
values are of type np.uint8 and values are in {0,1}.
masks2: a numpy array with shape [M, height, width] holding M masks. Masks
values are of ... | intersection | identifier_name |
urls.py | import re
from django.conf.urls import url, patterns, include
from django.conf import settings
from django.contrib import admin
from django.views.generic import TemplateView
from django.template import add_to_builtins
from fabrydb.admin import fadmin
add_to_builtins('avocado.templatetags.avocado_tags')
admin.autodisc... | '',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
)
# In production, these two locations must be served up statically
urlpatterns += patterns('django.views.static',
url(r'^{0}(?P<path>.*)$'.format(re.escape(settings.MEDIA_URL.lstrip('/'))), 'serve', {
... | # if not settings.DEBUG:
urlpatterns += patterns( | random_line_split |
Spinner.tsx | import React from 'react';
export interface ISpinnerProps {
size?: 'nano' | 'small' | 'medium' | 'large';
message?: string;
}
export class Spinner extends React.Component<ISpinnerProps> {
public getBarRows(): React.ReactNode[] |
public render(): React.ReactElement<Spinner> {
const { size, message } = this.props;
const mainClassNames = `load ${size || 'small'}`;
const messageClassNames = `message color-text-accent ${size === 'medium' ? 'heading-4' : 'heading-2'}`;
const messageNode = ['medium', 'large'].includes(size) && (
... | {
const { size } = this.props;
let count = 3;
if (size) {
if (size === 'nano') {
count = 1;
} else if (size === 'large') {
count = 5;
}
}
const rows = [];
let i: number;
for (i = 0; i < count; i++) {
rows.push(<div key={i} className="bar" />);
}
... | identifier_body |
Spinner.tsx | import React from 'react';
export interface ISpinnerProps {
size?: 'nano' | 'small' | 'medium' | 'large';
message?: string; | const { size } = this.props;
let count = 3;
if (size) {
if (size === 'nano') {
count = 1;
} else if (size === 'large') {
count = 5;
}
}
const rows = [];
let i: number;
for (i = 0; i < count; i++) {
rows.push(<div key={i} className="bar" />);
}
... | }
export class Spinner extends React.Component<ISpinnerProps> {
public getBarRows(): React.ReactNode[] { | random_line_split |
Spinner.tsx | import React from 'react';
export interface ISpinnerProps {
size?: 'nano' | 'small' | 'medium' | 'large';
message?: string;
}
export class Spinner extends React.Component<ISpinnerProps> {
public | (): React.ReactNode[] {
const { size } = this.props;
let count = 3;
if (size) {
if (size === 'nano') {
count = 1;
} else if (size === 'large') {
count = 5;
}
}
const rows = [];
let i: number;
for (i = 0; i < count; i++) {
rows.push(<div key={i} class... | getBarRows | identifier_name |
Spinner.tsx | import React from 'react';
export interface ISpinnerProps {
size?: 'nano' | 'small' | 'medium' | 'large';
message?: string;
}
export class Spinner extends React.Component<ISpinnerProps> {
public getBarRows(): React.ReactNode[] {
const { size } = this.props;
let count = 3;
if (size) {
if (size... |
return rows;
}
public render(): React.ReactElement<Spinner> {
const { size, message } = this.props;
const mainClassNames = `load ${size || 'small'}`;
const messageClassNames = `message color-text-accent ${size === 'medium' ? 'heading-4' : 'heading-2'}`;
const messageNode = ['medium', 'large']... | {
rows.push(<div key={i} className="bar" />);
} | conditional_block |
test_recurr.py | from sympy import Function, symbols, S, sqrt, rf, factorial
from sympy.solvers.recurr import rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper
y = Function('y')
n, k = symbols('n,k', integer=True)
C0, C1, C2 = symbols('C0,C1,C2')
def test_rsolve_poly():
assert rsolve_poly([-1, -1, 1], 0, n) == 0
assert rsolve_p... | for c in coeffs:
q = recurrence_term(c, p)
if p.is_polynomial(n):
yield rsolve_bulk_checker, rsolve_poly, c, q, p
#if p.is_hypergeometric(n):
# yield rsolve_bulk_checker, rsolve_hyper, c, q, p
def test_rsolve():
f = y(n+2) - y(n+1) - y(n)
... | funcs = [ n, n+1, n**2, n**3, n**4, n+n**2, 27*n + 52*n**2 - 3*n**3 + 12*n**4 - 52*n**5 ]
coeffs = [ [-2, 1], [-2, -1, 1], [-1, 1, 1, -1, 1], [-n, 1], [n**2-n+12, 1] ]
for p in funcs:
# compute difference | random_line_split |
test_recurr.py | from sympy import Function, symbols, S, sqrt, rf, factorial
from sympy.solvers.recurr import rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper
y = Function('y')
n, k = symbols('n,k', integer=True)
C0, C1, C2 = symbols('C0,C1,C2')
def test_rsolve_poly():
assert rsolve_poly([-1, -1, 1], 0, n) == 0
assert rsolve_p... |
def test_rsolve_hyper():
assert rsolve_hyper([-1, -1, 1], 0, n) in [
C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n,
C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n,
]
assert rsolve_hyper([n**2-2, -2*n-1, 1], 0, n) in [
C0*rf(sqrt(2), n) + C1*r... | solution = rsolve_ratio([-2*n**3+n**2+2*n-1, 2*n**3+n**2-6*n,
-2*n**3-11*n**2-18*n-9, 2*n**3+13*n**2+22*n+8], 0, n)
assert solution in [
C1*((-2*n + 3)/(n**2 - 1))/3,
(S(1)/2)*(C1*(-3 + 2*n)/(-1 + n**2)),
(S(1)/2)*(C1*( 3 - 2*n)/( 1 - n**2)),
(S(1)/2)*(C2*(-3 + 2*n... | identifier_body |
test_recurr.py | from sympy import Function, symbols, S, sqrt, rf, factorial
from sympy.solvers.recurr import rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper
y = Function('y')
n, k = symbols('n,k', integer=True)
C0, C1, C2 = symbols('C0,C1,C2')
def test_rsolve_poly():
assert rsolve_poly([-1, -1, 1], 0, n) == 0
assert rsolve_p... |
#if p.is_hypergeometric(n):
# yield rsolve_bulk_checker, rsolve_hyper, c, q, p
def test_rsolve():
f = y(n+2) - y(n+1) - y(n)
h = sqrt(5)*(S.Half + S.Half*sqrt(5))**n \
- sqrt(5)*(S.Half - S.Half*sqrt(5))**n
assert rsolve(f, y(n)) in [
C0*(S.Half - S.Half*sqrt(5))*... | yield rsolve_bulk_checker, rsolve_poly, c, q, p | conditional_block |
test_recurr.py | from sympy import Function, symbols, S, sqrt, rf, factorial
from sympy.solvers.recurr import rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper
y = Function('y')
n, k = symbols('n,k', integer=True)
C0, C1, C2 = symbols('C0,C1,C2')
def test_rsolve_poly():
assert rsolve_poly([-1, -1, 1], 0, n) == 0
assert rsolve_p... | ():
assert rsolve_hyper([-1, -1, 1], 0, n) in [
C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n,
C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n,
]
assert rsolve_hyper([n**2-2, -2*n-1, 1], 0, n) in [
C0*rf(sqrt(2), n) + C1*rf(-sqrt(2), n),
... | test_rsolve_hyper | identifier_name |
apic.rs | use common::*;
use arch::init::{LOCAL_APIC_PAGE_VADDR, IO_APIC_PAGE_VADDR};
use util::{Mutex};
use super::{InterruptVector};
/// Local APIC pointer.
#[derive(Debug)]
pub struct LocalAPIC {
address: VAddr,
}
/// I/O APIC pointer.
#[derive(Debug)]
pub struct IOAPIC {
address: VAddr,
}
/// The local APIC static... | /// `reg` must be valid.
unsafe fn write(&mut self, reg: u32, value: u32) {
use core::intrinsics::{volatile_store};
volatile_store((self.address.into(): usize + reg as usize) as *mut u32, value);
}
/// APIC id.
pub fn id(&self) -> u32 {
unsafe { self.read(0x20) }
}
... | /// Write a value to the local APIC.
///
/// # Safety
/// | random_line_split |
apic.rs | use common::*;
use arch::init::{LOCAL_APIC_PAGE_VADDR, IO_APIC_PAGE_VADDR};
use util::{Mutex};
use super::{InterruptVector};
/// Local APIC pointer.
#[derive(Debug)]
pub struct LocalAPIC {
address: VAddr,
}
/// I/O APIC pointer.
#[derive(Debug)]
pub struct IOAPIC {
address: VAddr,
}
/// The local APIC static... | (&self) -> u32 {
unsafe { self.read(0x1) }
}
/// I/O APIC arbitration id.
pub fn arbitration_id(&self) -> u32 {
unsafe { self.read(0x2) }
}
/// Set IRQ to an interrupt vector.
pub fn set_irq(&mut self, irq: u8, apic_id: u8, vector: InterruptVector) {
let vector = vector... | version | identifier_name |
apic.rs | use common::*;
use arch::init::{LOCAL_APIC_PAGE_VADDR, IO_APIC_PAGE_VADDR};
use util::{Mutex};
use super::{InterruptVector};
/// Local APIC pointer.
#[derive(Debug)]
pub struct LocalAPIC {
address: VAddr,
}
/// I/O APIC pointer.
#[derive(Debug)]
pub struct IOAPIC {
address: VAddr,
}
/// The local APIC static... |
/// I/O APIC arbitration id.
pub fn arbitration_id(&self) -> u32 {
unsafe { self.read(0x2) }
}
/// Set IRQ to an interrupt vector.
pub fn set_irq(&mut self, irq: u8, apic_id: u8, vector: InterruptVector) {
let vector = vector as u8;
let low_index: u32 = 0x10 + (irq as u32... | {
unsafe { self.read(0x1) }
} | identifier_body |
scan.py | from __future__ import print_function
import os
import sys
from datetime import datetime
import portage
import gentoolkit.pprinter as pp
from gentoolkit.query import Query
from gentoolkit.package import Package
from euscan import CONFIG, BLACKLIST_PACKAGES
from euscan import handlers, output
from euscan.out import ... | matches = []
if query.endswith(".ebuild"):
cpv = package_from_ebuild(query)
reload_gentoolkit()
if cpv:
matches = [Package(cpv)]
else:
matches = Query(query).find(
include_masked=True,
in_installed=False,
)
if not matches:
... | """
Scans the upstream searching new versions for the given query
""" | random_line_split |
scan.py | from __future__ import print_function
import os
import sys
from datetime import datetime
import portage
import gentoolkit.pprinter as pp
from gentoolkit.query import Query
from gentoolkit.package import Package
from euscan import CONFIG, BLACKLIST_PACKAGES
from euscan import handlers, output
from euscan.out import ... | return None
matches = sorted(matches)
pkg = matches.pop()
while '9999' in pkg.version and len(matches):
pkg = matches.pop()
if not pkg:
output.ewarn(
pp.warn("Package '%s' only have a dev version (9999)"
% pp.pkgquery(pkg.cp))
)
... | """
Scans the upstream searching new versions for the given query
"""
matches = []
if query.endswith(".ebuild"):
cpv = package_from_ebuild(query)
reload_gentoolkit()
if cpv:
matches = [Package(cpv)]
else:
matches = Query(query).find(
include_m... | identifier_body |
scan.py | from __future__ import print_function
import os
import sys
from datetime import datetime
import portage
import gentoolkit.pprinter as pp
from gentoolkit.query import Query
from gentoolkit.package import Package
from euscan import CONFIG, BLACKLIST_PACKAGES
from euscan import handlers, output
from euscan.out import ... |
ebuild_path = pkg.ebuild_path()
if ebuild_path:
output.metadata(
"ebuild", pp.path(os.path.normpath(ebuild_path))
)
uris, homepage, description = pkg.environment(
('SRC_URI', 'HOMEPAGE', 'DESCRIPTION')
)
output.metadata("rep... | output.metadata("overlay", pp.section(pkg.repo_name())) | conditional_block |
scan.py | from __future__ import print_function
import os
import sys
from datetime import datetime
import portage
import gentoolkit.pprinter as pp
from gentoolkit.query import Query
from gentoolkit.package import Package
from euscan import CONFIG, BLACKLIST_PACKAGES
from euscan import handlers, output
from euscan.out import ... | ():
import gentoolkit
# Not used in recent versions
if not hasattr(gentoolkit.package, 'PORTDB'):
return
PORTDB = portage.db[portage.root]["porttree"].dbapi
if hasattr(gentoolkit.dbapi, 'PORTDB'):
gentoolkit.dbapi.PORTDB = PORTDB
if hasattr(gentoolkit.package, 'PORTDB'):
... | reload_gentoolkit | identifier_name |
ngtools_impl.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* This is a private API for the ngtools toolkit.
*
* This API should be stable for NG 2. It can be removed in... | }, []);
}
/**
* Return the loadChildren values of a list of Route.
* @private
*/
function _collectLoadChildren(routes: Route[]): string[] {
return routes.reduce((m, r) => {
if (r.loadChildren && typeof r.loadChildren === 'string') {
return m.concat(r.loadChildren);
} else if (Array.isArray(r)) {
... | } else if (Array.isArray(p)) {
return routeList.concat(_collectRoutes(p, reflector, ROUTES));
} else {
return routeList;
} | random_line_split |
ngtools_impl.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* This is a private API for the ngtools toolkit.
*
* This API should be stable for NG 2. It can be removed in... |
return ngModules[0];
}
/**
* Return the routes from the provider list.
* @private
*/
function _collectRoutes(
providers: any[], reflector: StaticReflector, ROUTES: StaticSymbol): Route[] {
return providers.reduce((routeList: Route[], p: any) => {
if (p.provide === ROUTES) {
return routeList.conc... | {
throw new Error(`${staticSymbol.name} is not an NgModule`);
} | conditional_block |
ngtools_impl.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* This is a private API for the ngtools toolkit.
*
* This API should be stable for NG 2. It can be removed in... | (entry: string): RouteDef {
const split = entry.split('#');
return new RouteDef(split[0], split[1] || null);
}
}
/**
*
* @returns {LazyRouteMap}
* @private
*/
export function listLazyRoutesOfModule(
entryModule: string, host: AotCompilerHost, reflector: StaticReflector): LazyRouteMap {
const entry... | fromString | identifier_name |
ngtools_impl.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* This is a private API for the ngtools toolkit.
*
* This API should be stable for NG 2. It can be removed in... | return i.ngModule;
}) as StaticSymbol[];
return importedSymbols
.reduce(
(acc: LazyRoute[], i: StaticSymbol) => {
return acc.concat(_extractLazyRoutesFromStaticModule(i, reflector, host, ROUTES));
},
[])
.concat(lazyRoutes);
}
/**
* Get ... | {
const moduleMetadata = _getNgModuleMetadata(staticSymbol, reflector);
const imports = flatten(moduleMetadata.imports || []);
const allRoutes: any = imports.filter(i => 'providers' in i).reduce((mem: Route[], m: any) => {
return mem.concat(_collectRoutes(m.providers || [], reflector, ROUTES));
}, _collectR... | identifier_body |
issue-29037.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 b<'r, 'w>(x: &'w &'static str) -> &'w &'r str {
x
}
fn c<'r>(x: Arc<&'static str>) -> Arc<&'r str> {
x
}
fn d<'r>(x: Rc<&'static str>) -> Rc<&'r str> {
x
}
fn main() {} | x
} | random_line_split |
issue-29037.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() {}
| {
x
} | identifier_body |
issue-29037.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 ... | () {}
| main | identifier_name |
bootstrap-notify.js | define(function(require, exports, module) {
var showMessage = function(type, message, duration) {
var $exist = $('.bootstrap-notify-bar');
if ($exist.length > 0) {
$exist.remove();
}
var html = '<div class="alert alert-' + type + ' bootstrap-notify-bar" style="display:n... |
warning: function(message, duration) {
showMessage('warning', message, duration);
},
danger: function(message, duration) {
showMessage('danger', message, duration);
},
info: function(message, duration) {
showMessage('info', message, duration... | }, | random_line_split |
bootstrap-notify.js | define(function(require, exports, module) {
var showMessage = function(type, message, duration) {
var $exist = $('.bootstrap-notify-bar');
if ($exist.length > 0) |
var html = '<div class="alert alert-' + type + ' bootstrap-notify-bar" style="display:none;">'
html += '<button type="button" class="close" data-dismiss="alert">×</button>';
html += message;
html += '</div>';
var $html = $(html);
$html.appendTo('body');
$html.... | {
$exist.remove();
} | conditional_block |
main.rs | // Copyright 2015 Google Inc. All rights reserved.
//
// 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 restriction, including without limitation the rights
// to use, copy, modify, ... | (text: &str, opts: Options) -> String {
let mut s = String::with_capacity(text.len() * 3 / 2);
let p = Parser::new_ext(&text, opts);
html::push_html(&mut s, p);
s
}
fn dry_run(text:&str, opts: Options) {
let p = Parser::new_ext(&text, opts);
/*
let events = p.collect::<Vec<_>>();
let co... | render_html | identifier_name |
main.rs | // Copyright 2015 Google Inc. All rights reserved.
//
// 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 restriction, including without limitation the rights
// to use, copy, modify, ... | else if line_count > 0 {
print!(" ");
}
print!("[{}]", test_number);
} else if line_count > 0 && (test_number % 10) == 5 {
print!(" ");
}
let our_html = render_html(&source.replace("→", "\t").replace("\n", "\r\n"), ... | {
println!("");
line_count = 0;
} | conditional_block |
main.rs | // Copyright 2015 Google Inc. All rights reserved.
//
// 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 restriction, including without limitation the rights
// to use, copy, modify, ... | run_spec(&read_file(&filename), &matches.free, opts);
} else if let Some(filename) = matches.opt_str("bench") {
let inp = read_file(&filename);
for _ in 0..1000 {
let _ = render_html(&inp, opts);
}
} else {
let mut input = String::new();
match io::stdi... | let args: Vec<_> = env::args().collect();
let mut opts = getopts::Options::new();
opts.optflag("d", "dry-run", "dry run, produce no output");
opts.optflag("e", "events", "print event sequence instead of rendering");
opts.optflag("T", "enable-tables", "enable GitHub-style tables");
opts.optflag("... | identifier_body |
main.rs | // Copyright 2015 Google Inc. All rights reserved.
//
// 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 restriction, including without limitation the rights
// to use, copy, modify, ... | } else {
print!("X");
}
tests_failed += 1;
}
let _ = io::stdout().flush();
tests_run += 1;
line_count += 1;
}
tail = rest;
test_number += 1;
}
println!("\n{}/{} tests passe... | if tests_failed == 0 {
print!("FAIL {}:\n---input---\n{}\n---wanted---\n{}\n---got---\n{}",
test_number, source, html, our_html); | random_line_split |
chunks.rs | use std::ops::{ Index, IndexMut };
use std::collections::HashMap;
use cgmath::{ Point, Point3 };
use super::chunk::Chunk;
pub type ChunkPos = Point3<i32>;
#[derive(Debug)]
pub struct Chunks {
chunks: HashMap<ChunkPos, Chunk>,
empty: Chunk,
}
impl Chunks {
pub fn new() -> Chunks {
Chunks {
... |
}
| {
self.chunks.entry(index).or_insert_with(Chunk::new)
} | identifier_body |
chunks.rs | use std::ops::{ Index, IndexMut };
use std::collections::HashMap;
use cgmath::{ Point, Point3 };
use super::chunk::Chunk;
pub type ChunkPos = Point3<i32>;
#[derive(Debug)]
pub struct Chunks {
chunks: HashMap<ChunkPos, Chunk>,
empty: Chunk,
}
impl Chunks {
pub fn | () -> Chunks {
Chunks {
chunks: HashMap::new(),
empty: Chunk::new(),
}
}
pub fn around(dist: u8, center: ChunkPos) -> Vec<ChunkPos> {
let mut res = Vec::new();
let dist = dist as i32;
for x in -dist + 1..dist {
for y in -dist + 1..dist... | new | identifier_name |
chunks.rs | use std::ops::{ Index, IndexMut };
use std::collections::HashMap;
use cgmath::{ Point, Point3 };
use super::chunk::Chunk;
pub type ChunkPos = Point3<i32>;
#[derive(Debug)]
pub struct Chunks {
chunks: HashMap<ChunkPos, Chunk>,
empty: Chunk,
} | Chunks {
chunks: HashMap::new(),
empty: Chunk::new(),
}
}
pub fn around(dist: u8, center: ChunkPos) -> Vec<ChunkPos> {
let mut res = Vec::new();
let dist = dist as i32;
for x in -dist + 1..dist {
for y in -dist + 1..dist {
... |
impl Chunks {
pub fn new() -> Chunks { | random_line_split |
build.rs | use std::env;
use std::process::Command;
fn main() {
if std::env::var("DOCS_RS").is_ok() {
// Skip everything when building docs on docs.rs
return;
}
// On Windows Rust always links against release version of MSVC runtime, thus requires Release
// build here.
let build_type = if cf... | println!("cargo:rustc-link-lib=static=mediasoup-worker");
println!("cargo:rustc-link-search=native={}", out_dir);
}
| // Clean
if !Command::new("make")
.arg("clean-all")
.env("MEDIASOUP_OUT_DIR", &mediasoup_out_dir)
.spawn()
.expect("Failed to start")
.wait()
.expect("Wasn't running")
.success()
{
panic!("Failed to cl... | conditional_block |
build.rs | use std::env;
use std::process::Command;
fn | () {
if std::env::var("DOCS_RS").is_ok() {
// Skip everything when building docs on docs.rs
return;
}
// On Windows Rust always links against release version of MSVC runtime, thus requires Release
// build here.
let build_type = if cfg!(all(debug_assertions, not(windows))) {
... | main | identifier_name |
build.rs | use std::env;
use std::process::Command;
fn main() | {
let path = Command::new(env::var("CXX").unwrap_or_else(|_| "c++".to_string()))
.arg("--print-file-name=libstdc++.a")
.output()
.expect("Failed to start")
.stdout;
println!(
"cargo:rustc-link-search=native={}",
String::from_utf... | {
if std::env::var("DOCS_RS").is_ok() {
// Skip everything when building docs on docs.rs
return;
}
// On Windows Rust always links against release version of MSVC runtime, thus requires Release
// build here.
let build_type = if cfg!(all(debug_assertions, not(windows))) {
"D... | identifier_body |
build.rs | use std::env; |
fn main() {
if std::env::var("DOCS_RS").is_ok() {
// Skip everything when building docs on docs.rs
return;
}
// On Windows Rust always links against release version of MSVC runtime, thus requires Release
// build here.
let build_type = if cfg!(all(debug_assertions, not(windows))) {... | use std::process::Command; | random_line_split |
test_subscriptions.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015 Digi International Inc. All Rights Reserved.
import json
from wva.test.test_utilities import WVAT... | 'uri': 'vehicle/data/VehicleSpeed'}
})
sub = self.wva.get_subscription("speedy")
self.assertEqual(sub.get_metadata(), {
'buffer': 'queue',
'interval': 1,
'uri': 'vehicle/data/VehicleSpeed',
})
def test_delete(self):
... | self.prepare_json_response("GET", "/ws/subscriptions/speedy", {
'subscription': {'buffer': 'queue',
'interval': 1, | random_line_split |
test_subscriptions.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015 Digi International Inc. All Rights Reserved.
import json
from wva.test.test_utilities import WVAT... | 'buffer': 'queue',
'interval': 1,
'uri': 'vehicle/data/VehicleSpeed',
})
def test_delete(self):
self.prepare_response("DELETE", "/ws/subscriptions/short-name", "")
sub = self.wva.get_subscription("short-name")
sub.delete()
self.assertEqual... | def test_get_subscriptions(self):
self.prepare_json_response("GET", "/ws/subscriptions", {
"subscriptions": [
"subscriptions/a",
"subscriptions/b",
]
})
subs = self.wva.get_subscriptions()
self.assertEqual(len(subs), 2)
self... | identifier_body |
test_subscriptions.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015 Digi International Inc. All Rights Reserved.
import json
from wva.test.test_utilities import WVAT... | (self):
self.prepare_response("PUT", "/ws/subscriptions/new-short-name", "")
sub = self.wva.get_subscription("new-short-name")
sub.create("vehicle/data/EngineSpeed", buffer="drop", interval=5)
req = self._get_last_request()
self.assertDictEqual(json.loads(req.body.decode('utf-8')... | test_create | identifier_name |
radixal.py | def radixsort(mylist):
if mylist == []:
return []
answerdict = {}
for item in mylist:
try:
answerdict[item%10].append(item)
except KeyError:
answerdict[item%10] = [item, ]
i = 1
while len(answerdict.keys()) > 1:
answerdict = radixhelper(answerd... |
return outdict
def radixsortstring(mylist):
if mylist == []:
return []
answerdict={'input':mylist}
maxlength = 0
for singlestring in mylist:
maxlength = max(maxlength, len(singlestring))
for i in xrange(maxlength):
answerdict = radixstringhelper(answerdict, maxlength-(... | for number in bucketlist:
exactdigit = number
for i in xrange(digit):
exactdigit = exactdigit // 10
exactdigit %= 10
try:
outdict[exactdigit].append(number)
except KeyError:
outdict[exactdigit] = [number, ] | conditional_block |
radixal.py | def radixsort(mylist):
|
def radixhelper(indict, digit):
outdict={}
for bucketlist in indict.values():
for number in bucketlist:
exactdigit = number
for i in xrange(digit):
exactdigit = exactdigit // 10
exactdigit %= 10
try:
outdict[exactdigit].ap... | if mylist == []:
return []
answerdict = {}
for item in mylist:
try:
answerdict[item%10].append(item)
except KeyError:
answerdict[item%10] = [item, ]
i = 1
while len(answerdict.keys()) > 1:
answerdict = radixhelper(answerdict, i)
i += 1
... | identifier_body |
radixal.py | def radixsort(mylist):
if mylist == []:
return []
answerdict = {}
for item in mylist:
try:
answerdict[item%10].append(item)
except KeyError:
answerdict[item%10] = [item, ]
i = 1
while len(answerdict.keys()) > 1:
answerdict = radixhelper(answerd... | (indict, index):
shorties = indict.pop('shorties', [])
outdict = {'shorties':[]}
buckets = [shorties, ]
for key in sorted(indict.keys()):
buckets.append(indict[key])
for bucketlist in buckets:
for onestring in bucketlist:
try:
outdict[onestring[index]].app... | radixstringhelper | identifier_name |
radixal.py | def radixsort(mylist):
if mylist == []:
return []
answerdict = {}
for item in mylist:
try:
answerdict[item%10].append(item)
except KeyError:
answerdict[item%10] = [item, ]
i = 1
while len(answerdict.keys()) > 1:
answerdict = radixhelper(answerd... | outdict[onestring[index]] = [onestring, ]
except IndexError:
outdict['shorties'].append(onestring)
worthlessstring = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu"
return outdict | outdict[onestring[index]].append(onestring)
except KeyError: | random_line_split |
test_did.py | # coding: utf-8
""" Tests for the command line script """
from __future__ import unicode_literals, absolute_import
import os
import re
import did.cli
import did.utils
# Prepare path and config examples
PATH = os.path.dirname(os.path.realpath(__file__))
MINIMAL = did.base.Config.example()
EXAMPLE = "".join(open(PATH ... |
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Example Config
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def test_help_example():
""" Help message with example config """
did.base.Config(config=EXAMPLE)
try:
did.cli.main(["-... | """ Help message with minimal config """
did.base.Config(config=MINIMAL)
try:
did.cli.main(["--help"])
except SystemExit:
pass | identifier_body |
test_did.py | # coding: utf-8
""" Tests for the command line script """
from __future__ import unicode_literals, absolute_import
import os
import re
import did.cli
import did.utils
# Prepare path and config examples
PATH = os.path.dirname(os.path.realpath(__file__))
MINIMAL = did.base.Config.example()
EXAMPLE = "".join(open(PATH ... | ():
""" Help message with minimal config """
did.base.Config(config=MINIMAL)
try:
did.cli.main(["--help"])
except SystemExit:
pass
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Example Config
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | test_help_minimal | identifier_name |
test_did.py | # coding: utf-8
""" Tests for the command line script """
from __future__ import unicode_literals, absolute_import
import os
import re
import did.cli
import did.utils
# Prepare path and config examples
PATH = os.path.dirname(os.path.realpath(__file__))
MINIMAL = did.base.Config.example()
EXAMPLE = "".join(open(PATH ... | pass | did.base.Config(config=EXAMPLE)
try:
did.cli.main(["--help"])
except SystemExit: | random_line_split |
ircensus_channel_bot.py | #!/usr/bin/env python3
"""
A simple bot to gather some census data in IRC channels.
It is intended to sit in a channel and collect the data for statistics.
:author: tpltnt
:license: AGPLv3
"""
import irc.bot
import irc.strings
from irc.client import ip_numstr_to_quad, ip_quad_to_numstr
class | (irc.bot.SingleServerIRCBot):
"""
The class implementing the census bot.
"""
def __init__(self, channel, nickname, server, port=6667):
"""
The constructor for the CensusBot class.
:param channel: name of the channel to join
:type channel: str
:param nickname: ni... | CensusBot | identifier_name |
ircensus_channel_bot.py | #!/usr/bin/env python3
"""
A simple bot to gather some census data in IRC channels.
It is intended to sit in a channel and collect the data for statistics.
:author: tpltnt
:license: AGPLv3
"""
import irc.bot
import irc.strings
from irc.client import ip_numstr_to_quad, ip_quad_to_numstr
class CensusBot(irc.bot.Singl... | main() | conditional_block | |
ircensus_channel_bot.py | #!/usr/bin/env python3
"""
A simple bot to gather some census data in IRC channels.
It is intended to sit in a channel and collect the data for statistics.
:author: tpltnt
:license: AGPLv3
"""
import irc.bot
import irc.strings
from irc.client import ip_numstr_to_quad, ip_quad_to_numstr
class CensusBot(irc.bot.Singl... |
if __name__ == "__main__":
main()
| import sys
if len(sys.argv) != 4:
print("Usage: " + sys.argv[0] + " <server[:port]> <channel> <nickname>")
sys.exit(1)
server = sys.argv[1].split(":", 1)
host = server[0]
if len(server) == 2:
try:
port = int(server[1])
except ValueError:
print("Er... | identifier_body |
ircensus_channel_bot.py | #!/usr/bin/env python3
"""
A simple bot to gather some census data in IRC channels.
It is intended to sit in a channel and collect the data for statistics.
:author: tpltnt
:license: AGPLv3
"""
import irc.bot
import irc.strings
from irc.client import ip_numstr_to_quad, ip_quad_to_numstr
class CensusBot(irc.bot.Singl... | else:
port = 6667
channel = sys.argv[2]
nickname = sys.argv[3]
bot = CensusBot(channel, nickname, server, port)
bot.start()
if __name__ == "__main__":
main() | except ValueError:
print("Error: Erroneous port.")
sys.exit(1) | random_line_split |
effects.ts | import { call, put, takeEvery } from 'redux-saga/effects';
import { format } from '@waldur/core/ErrorMessageFormatter';
import { translate } from '@waldur/i18n';
import * as api from '@waldur/issues/security-incident/api';
import { closeModalDialog } from '@waldur/modal/actions';
import { showError, showSuccess } from... |
yield put(showSuccess('Security incident has been successfully reported.'));
yield put(constants.REPORT_INCIDENT.success());
yield put(closeModalDialog());
} catch (error) {
const errorMessage = `${translate(
'Unable to report security incident.',
)} ${format(error)}`;
yield put(showErr... | {
yield call(
api.uploadAttachments,
response.data.url,
action.payload.files,
);
} | conditional_block |
effects.ts | import { call, put, takeEvery } from 'redux-saga/effects';
import { format } from '@waldur/core/ErrorMessageFormatter';
import { translate } from '@waldur/i18n';
import * as api from '@waldur/issues/security-incident/api';
import { closeModalDialog } from '@waldur/modal/actions';
import { showError, showSuccess } from... | } catch (error) {
const errorMessage = `${translate(
'Unable to report security incident.',
)} ${format(error)}`;
yield put(showError(errorMessage));
yield put(constants.REPORT_INCIDENT.failure());
}
}
export default function* () {
yield takeEvery(constants.REPORT_INCIDENT.REQUEST, reportIn... | yield put(showSuccess('Security incident has been successfully reported.'));
yield put(constants.REPORT_INCIDENT.success());
yield put(closeModalDialog()); | random_line_split |
Storage.spec.ts | import { expect } from 'chai';
import * as sinon from 'sinon';
import 'mocha';
import Storage from '@src/Storage'
describe('Storage', function() {
let storage;
before(function() {
storage = new Storage();
})
after(function() {
storage.getBackend().clear(); |
it('should mark storage as not conform');
it('should mark storage as conform');
it('should return the right prefix', function() {
expect(storage.getPrefix()).equals('jsxc2:');
})
it('should properly generate keys', function() {
expect(storage.generateKey('foo')).equals('foo');
... | }) | random_line_split |
Storage.spec.ts | import { expect } from 'chai';
import * as sinon from 'sinon';
import 'mocha';
import Storage from '@src/Storage'
describe('Storage', function() {
let storage;
before(function() {
storage = new Storage();
})
after(function() {
storage.getBackend().clear();
})
it('should mark... |
expect(spy.args[index][0]).equals('jsxc2:' + key);
expect(spy.args[index][1]).equals(expectedStoredValue);
});
})
it('should save key/value pairs of a specific type')
it('should properly retrieve key/value pairs')
it('should properly retrieve key/value pairs of a spe... | {
expectedStoredValue = JSON.stringify(value);
} | conditional_block |
cookieParser.js |
var cookieParser = require('..')
var http = require('http')
var request = require('supertest')
var signature = require('cookie-signature')
describe('connect.cookieParser()', function(){
var server
before(function(){
server = createServer('keyboard cat')
})
describe('when no cookies are sent',... | (secret) {
var _parser = cookieParser(secret)
return http.createServer(function(req, res){
_parser(req, res, function(err){
if (err) {
res.statusCode = 500
res.end(err.message)
return
}
var cookies = '/signed' === req.url
? req.signedCookies
... | createServer | identifier_name |
cookieParser.js |
var cookieParser = require('..')
var http = require('http')
var request = require('supertest')
var signature = require('cookie-signature')
describe('connect.cookieParser()', function(){
var server
before(function(){
server = createServer('keyboard cat')
})
describe('when no cookies are sent',... | {
var _parser = cookieParser(secret)
return http.createServer(function(req, res){
_parser(req, res, function(err){
if (err) {
res.statusCode = 500
res.end(err.message)
return
}
var cookies = '/signed' === req.url
? req.signedCookies
: req.co... | identifier_body | |
cookieParser.js | var cookieParser = require('..')
var http = require('http')
var request = require('supertest')
var signature = require('cookie-signature')
describe('connect.cookieParser()', function(){
var server
before(function(){
server = createServer('keyboard cat')
})
describe('when no cookies are sent', f... | request(server)
.get('/signed')
.set('Cookie', 'foo=s:' + val)
.expect(200, '{"foo":"foobarbaz"}', done)
})
it('should remove the signed value from req.cookies', function(done){
request(server)
.get('/')
.set('Cookie', 'foo=s:' + val)
.expect(200, '{}',... | describe('when a secret is given', function(){
var val = signature.sign('foobarbaz', 'keyboard cat');
// TODO: "bar" fails...
it('should populate req.signedCookies', function(done){
| random_line_split |
AboutHudsonnotifierDialog.py | # -*- coding: utf-8 -*-
### BEGIN LICENSE
# Copyright (C) 2009 Philip Peitsch <philip.peitsch@gmail.com>
#This program is free software: you can redistribute it and/or modify it
#under the terms of the GNU General Public License version 3, as published
#by the Free Software Foundation.
#
#This program is distributed ... | (self, builder):
"""finish_initalizing should be called after parsing the ui definition
and creating a AboutHudsonnotifierDialog object with it in order to finish
initializing the start of the new AboutHudsonnotifierDialog instance.
"""
#get a reference to the builder and se... | finish_initializing | identifier_name |
AboutHudsonnotifierDialog.py | # -*- coding: utf-8 -*-
### BEGIN LICENSE
# Copyright (C) 2009 Philip Peitsch <philip.peitsch@gmail.com>
#This program is free software: you can redistribute it and/or modify it
#under the terms of the GNU General Public License version 3, as published
#by the Free Software Foundation.
#
#This program is distributed ... |
def finish_initializing(self, builder):
"""finish_initalizing should be called after parsing the ui definition
and creating a AboutHudsonnotifierDialog object with it in order to finish
initializing the start of the new AboutHudsonnotifierDialog instance.
"""
#get a re... | """__init__ - This function is typically not called directly.
Creation of a AboutHudsonnotifierDialog requires redeading the associated ui
file and parsing the ui definition extrenally,
and then calling AboutHudsonnotifierDialog.finish_initializing().
Use the convenience function N... | identifier_body |
AboutHudsonnotifierDialog.py | # -*- coding: utf-8 -*-
### BEGIN LICENSE
# Copyright (C) 2009 Philip Peitsch <philip.peitsch@gmail.com>
#This program is free software: you can redistribute it and/or modify it
#under the terms of the GNU General Public License version 3, as published
#by the Free Software Foundation.
#
#This program is distributed ... | #PURPOSE. See the GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License along
#with this program. If not, see <http://www.gnu.org/licenses/>.
### END LICENSE
import sys
import os
import gtk
from hudsonnotifier.hudsonnotifierconfig import getdatapath
clas... | #WITHOUT ANY WARRANTY; without even the implied warranties of
#MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR | random_line_split |
AboutHudsonnotifierDialog.py | # -*- coding: utf-8 -*-
### BEGIN LICENSE
# Copyright (C) 2009 Philip Peitsch <philip.peitsch@gmail.com>
#This program is free software: you can redistribute it and/or modify it
#under the terms of the GNU General Public License version 3, as published
#by the Free Software Foundation.
#
#This program is distributed ... | dialog = NewAboutHudsonnotifierDialog()
dialog.show()
gtk.main() | conditional_block | |
LimitSet.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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 restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | """Specifies a set of Limits that are associated with a Measurement. A Measurement may have several LimitSets corresponding to seasonal or other changing conditions. The condition is captured in the name and description attributes. The same LimitSet may be used for several Measurements. In particular percentage limits ... | identifier_body | |
LimitSet.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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 restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | (IdentifiedObject):
"""Specifies a set of Limits that are associated with a Measurement. A Measurement may have several LimitSets corresponding to seasonal or other changing conditions. The condition is captured in the name and description attributes. The same LimitSet may be used for several Measurements. In parti... | LimitSet | identifier_name |
LimitSet.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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 restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | def __init__(self, isPercentageLimits=False, *args, **kw_args):
"""Initialises a new 'LimitSet' instance.
@param isPercentageLimits: Tells if the limit values are in percentage of normalValue or the specified Unit for Measurements and Controls.
"""
#: Tells if the limit values are ... | """Specifies a set of Limits that are associated with a Measurement. A Measurement may have several LimitSets corresponding to seasonal or other changing conditions. The condition is captured in the name and description attributes. The same LimitSet may be used for several Measurements. In particular percentage lim... | random_line_split |
veteran-address.js | import cloneDeep from 'platform/utilities/data/cloneDeep';
import emailUI from 'platform/forms-system/src/js/definitions/email';
import { veteranInformation } from '../../../utilities';
import { buildAddressSchema, addressUISchema } from '../../../address-schema';
const veteranContactInformationSchema = cloneDeep(
v... | }; | return emailAddress;
},
},
},
}, | random_line_split |
veteran-address.js | import cloneDeep from 'platform/utilities/data/cloneDeep';
import emailUI from 'platform/forms-system/src/js/definitions/email';
import { veteranInformation } from '../../../utilities';
import { buildAddressSchema, addressUISchema } from '../../../address-schema';
const veteranContactInformationSchema = cloneDeep(
v... |
},
],
'ui:title': 'Confirm email address',
'ui:options': {
expandUnder: 'emailAddress',
expandUnderCondition: emailAddress => {
return emailAddress;
},
},
},
},
};
| {
errors.addError('Please ensure your emails match');
} | conditional_block |
buildsettings.py | # settings file for builds.
# if you want to have custom builds, copy this file to "localbuildsettings.py" and make changes there.
# possible fields:
# resourceBaseUrl - optional - the URL base for external resources (all resources embedded in standard IITC)
# distUrlBase - optional - the base URL to use for update c... |
# defaultBuild - the name of the default build to use if none is specified on the build.py command line
# (in here as an example - it only works in localbuildsettings.py)
#defaultBuild = 'local' | random_line_split | |
conf.py | # -*- coding: utf-8 -*-
#
# flask_slack documentation build configuration file, created by
# sphinx-quickstart on Sun Oct 19 16:31:35 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#... | # If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting... | # If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
| random_line_split |
setup.py | # This file is part of HDL Checker.
#
# Copyright (c) 2015 - 2019 suoto (Andre Souto)
#
# HDL Checker is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | 'six>=1.10.0',
'tabulate>=0.8.5',
'typing>=3.7.4',
'waitress>=0.9.0', ],
cmdclass = versioneer.get_cmdclass(),
entry_points = ... | 'future>=0.14.0',
'futures; python_version<"3.2"',
'prettytable>=0.7.2',
'pygls==0.9.1',
'requests>=2.20.0', | random_line_split |
Primitive.ts | import { isTranslucent } from './Util';
declare var Cesium;
/**
* This is the default implementation of a primitive, all primitives extend this class.
*/
export abstract class Primitive{
protected _show:boolean;
protected _modelMatrix: any;
protected _renderState: any;
protected _drawCommand: any;
protected _po... | (drawCommand, vertexArray, primitiveType, translucent:boolean = false, debugShowBoundingVolume: boolean = false) {
drawCommand.modelMatrix = this._modelMatrix;
drawCommand.renderState = this._renderState;
drawCommand.shaderProgram = this._shaderProgram;
drawCommand.boundingVolume = this._boundingVolume;
drawC... | setupDrawCommand | identifier_name |
Primitive.ts | import { isTranslucent } from './Util';
declare var Cesium;
/**
* This is the default implementation of a primitive, all primitives extend this class.
*/
export abstract class Primitive{
protected _show:boolean; | protected _drawCommand: any;
protected _points: any;
protected _indicesArray: number[];
protected _boundingVolume: any;
protected _dirty: boolean = true;
protected _lastMode: any;
protected _color: number[];
protected _vertexArray: any;
protected _shaderProgram: any;
constructor(options: {show?: boolean, col... | protected _modelMatrix: any;
protected _renderState: any; | random_line_split |
Primitive.ts | import { isTranslucent } from './Util';
declare var Cesium;
/**
* This is the default implementation of a primitive, all primitives extend this class.
*/
export abstract class Primitive{
protected _show:boolean;
protected _modelMatrix: any;
protected _renderState: any;
protected _drawCommand: any;
protected _po... |
set show(value: boolean) {
this._show = value;
}
public isTranslucent(){
return isTranslucent(this._color);
}
protected shouldRender() {
return this._show;
}
protected setupDrawCommand(drawCommand, vertexArray, primitiveType, translucent:boolean = false, debugShowBoundingVolume: boolean = false) {
d... | {
return this._show;
} | identifier_body |
Polygon.js | license. */
/**
* @requires OpenLayers/Handler/Path.js
* @requires OpenLayers/Geometry/Polygon.js
*/
/**
* Class: OpenLayers.Handler.Polygon
* Handler to draw a polygon on the map. Polygon is displayed on mouse down,
* moves on mouse move, and is finished on mouse up.
*
* Inherits from:
* - <OpenLayers.H... |
}
if (modified) {
if (this.polygon.state !== OpenLayers.State.INSERT) {
this.polygon.state = OpenLayers.State.UPDATE;
}
} else {
this.polygon.geometry.removeComponent(ring);
}
this.restoreFeature();
return false;
},... | {
// ensure that new ring doesn't contain any other rings
var target;
outer: for (var i=rings.length-2; i>0; --i) {
var points = rings[i].components;
for (var j=0, jj=points.length; j<jj; ++j) {
if (ring.cont... | conditional_block |
Polygon.js | license. */
/**
* @requires OpenLayers/Handler/Path.js
* @requires OpenLayers/Geometry/Polygon.js
*/
/**
* Class: OpenLayers.Handler.Polygon
* Handler to draw a polygon on the map. Polygon is displayed on mouse down,
* moves on mouse move, and is finished on mouse up.
*
* Inherits from:
* - <OpenLayers.H... | * rules are enforced in <finalizeInteriorRing> to allow drawing of
* rings that intersect only during the sketch (e.g. a "C" shaped ring
* that nearly encloses another ring).
*/
enforceTopology: function(event) {
var point = event.vertex;
var components = this.line.g... | /**
* Method: enforceTopology
* Simple topology enforcement for drawing interior rings. Ensures vertices
* of interior rings are contained by exterior ring. Other topology | random_line_split |
config.rs | // Copyright 2020 The Exonum Team
//
// 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... | .build();
(testkit, mock_provider)
}
/// Creates block with `ConfigPropose` tx and returns `Result` with new
/// configuration or corresponding `ExecutionError`.
async fn propose_configuration(
testkit: &mut TestKit,
config: Config,
) -> Result<(), ExecutionError> {
let tx = ConfigPropose::im... | {
let mock_provider = MockTimeProvider::new(SystemTime::now().into());
let time_service = TimeServiceFactory::with_provider(mock_provider.clone());
let mut time_service =
Spec::new(time_service).with_instance(TIME_SERVICE_ID, TIME_SERVICE_NAME, ());
if second_time_service {
time_service ... | identifier_body |
config.rs | // Copyright 2020 The Exonum Team
//
// 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... | (second_time_service: bool) -> (TestKit, MockTimeProvider) {
let mock_provider = MockTimeProvider::new(SystemTime::now().into());
let time_service = TimeServiceFactory::with_provider(mock_provider.clone());
let mut time_service =
Spec::new(time_service).with_instance(TIME_SERVICE_ID, TIME_SERVICE_NA... | init_testkit | identifier_name |
config.rs | // Copyright 2020 The Exonum Team
//
// 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... |
// Propose configuration with invalid time service name.
let err = propose_configuration(&mut testkit, config)
.await
.expect_err("Configuration proposal should fail.");
let expected_err =
ErrorMatch::from_fail(&CoreError::IncorrectInstanceId).with_any_descr... | random_line_split | |
config.rs | // Copyright 2020 The Exonum Team
//
// 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... |
let config = Config {
time_service_name: TIME_SERVICE_NAME.to_owned(),
};
let timestamping =
Spec::new(TimestampingService).with_instance(SERVICE_ID, SERVICE_NAME, config);
let testkit = TestKitBuilder::validator()
.with(Supervisor::simple())
.with(time_service)
... | {
time_service =
time_service.with_instance(SECOND_TIME_SERVICE_ID, SECOND_TIME_SERVICE_NAME, ());
} | conditional_block |
list_comprehension.py | # Fluent Python Book
# List comprehensions are faster than for-loops
import time
from random import choices
symbols = list('abcdefghijklmn')
print(symbols)
symbols_big = choices(symbols, k=2000000)
# print(symbols_big)
start = time.time()
ord_list1 = []
for sym in symbols_big:
|
# print('ord list1:', ord_list1)
end = time.time()
print('for loop ran in %f s' % (end - start))
start = time.time()
# list comprehension
ord_list2 = [ord(sym) for sym in symbols_big]
# print('ord list2:', ord_list2)
end = time.time()
print('for loop ran in %f s' % (end - start))
# let's do a performance benchmark o... | ord_list1.append(ord(sym)) | conditional_block |
list_comprehension.py | # Fluent Python Book
# List comprehensions are faster than for-loops
import time
from random import choices
symbols = list('abcdefghijklmn')
print(symbols)
symbols_big = choices(symbols, k=2000000)
# print(symbols_big)
start = time.time()
ord_list1 = []
for sym in symbols_big:
ord_list1.append(ord(sym))
# print... | sq_nums = []
for i in l_nums:
sq_nums.append(i ** 2)
end = time.time()
print('for loop ran in %f s' % (end - start))
start = time.time()
sq_nums = [i ** 2 for i in range(1000000)]
end = time.time()
print('list comp ran in %f s' % (end - start)) | # let's do a performance benchmark of this list comprehension
l_nums = [i for i in range(1000000)]
start = time.time() | random_line_split |
PowerLost.py | from __future__ import absolute_import
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Components.config import config
import Screens.Standby
from boxbranding import getMachineBrand, getMachineName
class PowerLost(Screen):
def __init__(self, session):
Screen.__init__(self, session)
... |
def MsgBoxClosed(self, ret):
if ret:
if config.usage.shutdownNOK_action.value == 'deepstandby' and not config.usage.shutdownOK.value:
self.session.open(Screens.Standby.TryQuitMainloop, 1)
elif not Screens.Standby.inStandby:
self.session.open(Screens.Standby.Standby)
self.close()
| if config.usage.boot_action.value == 'normal':
message = _("Your %s %s was not shutdown properly.\n\n"
"Do you want to put it in %s?") % (getMachineBrand(), getMachineName(), config.usage.shutdownNOK_action.value)
self.session.openWithCallback(self.MsgBoxClosed, MessageBox, message, MessageBox.TYPE_YESNO, ti... | identifier_body |
PowerLost.py | from __future__ import absolute_import
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Components.config import config
import Screens.Standby
from boxbranding import getMachineBrand, getMachineName
class PowerLost(Screen):
def __init__(self, session):
Screen.__init__(self, session)
... | self.session.openWithCallback(self.MsgBoxClosed, MessageBox, message, MessageBox.TYPE_YESNO, timeout = int(config.usage.shutdown_msgbox_timeout.value), default = True)
else:
self.MsgBoxClosed(True)
def MsgBoxClosed(self, ret):
if ret:
if config.usage.shutdownNOK_action.value == 'deepstandby' and not conf... | def showMessageBox(self):
if config.usage.boot_action.value == 'normal':
message = _("Your %s %s was not shutdown properly.\n\n"
"Do you want to put it in %s?") % (getMachineBrand(), getMachineName(), config.usage.shutdownNOK_action.value) | random_line_split |
PowerLost.py | from __future__ import absolute_import
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Components.config import config
import Screens.Standby
from boxbranding import getMachineBrand, getMachineName
class PowerLost(Screen):
def __init__(self, session):
Screen.__init__(self, session)
... | (self):
if config.usage.boot_action.value == 'normal':
message = _("Your %s %s was not shutdown properly.\n\n"
"Do you want to put it in %s?") % (getMachineBrand(), getMachineName(), config.usage.shutdownNOK_action.value)
self.session.openWithCallback(self.MsgBoxClosed, MessageBox, message, MessageBox.TYPE... | showMessageBox | identifier_name |
PowerLost.py | from __future__ import absolute_import
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Components.config import config
import Screens.Standby
from boxbranding import getMachineBrand, getMachineName
class PowerLost(Screen):
def __init__(self, session):
Screen.__init__(self, session)
... |
self.close()
| if config.usage.shutdownNOK_action.value == 'deepstandby' and not config.usage.shutdownOK.value:
self.session.open(Screens.Standby.TryQuitMainloop, 1)
elif not Screens.Standby.inStandby:
self.session.open(Screens.Standby.Standby) | conditional_block |
list_property.py | # -*- coding: utf-8 -*-
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**metadata module.**
Contact : ole.moller.nielsen@gmail.com
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Sof... |
@property
def xml_value(self):
if self.python_type is list:
return json.dumps(self.value)
elif self.python_type is NoneType:
return ''
else:
raise RuntimeError('self._allowed_python_types and self.xml_value'
'are out of... | try:
return json.loads(value)
except ValueError as e:
raise MetadataCastError(e) | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.