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
start-webpack-server.ts
import openurl from "better-opn" import report from "gatsby-cli/lib/reporter" import chalk from "chalk" import { Compiler } from "webpack" import { Stage } from "../commands/types" import { reportWebpackWarnings, structureWebpackErrors, } from "../utils/webpack-error-utils" import { printDeprecationWarnings } fro...
} isFirstCompile = false if (webpackActivity) { if (stats.hasWarnings()) { const rawMessages = stats.toJson({ moduleTrace: false }) reportWebpackWarnings(rawMessages.warnings, report) } if (!isSuccessful) { const errors = stru...
{ // Show notices to users about potential experiments/feature flags they could // try. showExperimentNotices() printInstructions( program.sitePackageJson.name || `(Unnamed package)`, urls ) printDeprecationWarnings() if (prog...
conditional_block
start-webpack-server.ts
import openurl from "better-opn" import report from "gatsby-cli/lib/reporter" import chalk from "chalk" import { Compiler } from "webpack" import { Stage } from "../commands/types" import { reportWebpackWarnings, structureWebpackErrors, } from "../utils/webpack-error-utils" import { printDeprecationWarnings } fro...
resolve({ compiler, websocketManager, webpackWatching }) } ) }) }
random_line_split
lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} }; let s = match expr.node { // expression is a literal ast::ExprLit(ref lit) => match lit.node { // string literal ast::LitStr(ref s, _) => { s.clone() } _ => { cx.span_err(expr.span, "unsupported litera...
{ cx.span_err(span, "invalid floating point type in hexfloat!"); None }
conditional_block
lib.rs
// Copyright 2014 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 ...
() { }
dummy_test
identifier_name
lib.rs
// Copyright 2014 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 ...
//Check if the literal is valid (as LLVM expects), //and return a descriptive error if not. fn hex_float_lit_err(s: &str) -> Option<(uint, String)> { let mut chars = s.chars().peekable(); let mut i = 0; if chars.peek() == Some(&'-') { chars.next(); i+= 1 } if chars.next() != Some('0') { return...
{ reg.register_macro("hexfloat", expand_syntax_ext); }
identifier_body
lib.rs
// Copyright 2014 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 ...
"f32" => Some(ast::TyF32), "f64" => Some(ast::TyF64), _ => { cx.span_err(span, "invalid floating point type in hexfloat!"); None } } }; let s = match expr.node { // expression is a literal ast::ExprLit(ref l...
let ty = match ty_lit { None => None, Some(Ident{ident, span}) => match token::get_ident(ident).get() {
random_line_split
summary-body.py
#!/usr/bin/python ################################################################################ ##3456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 ## 10 20 30 40 50 60 70 80 ## ## Info: ## Example of how to use libnotify correctl...
## ## Author: ## Mirco "MacSlow" Mueller <mirco.mueller@canonical.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 in the hope that it w...
## ## Copyright 2009 Canonical Ltd.
random_line_split
summary-body.py
#!/usr/bin/python ################################################################################ ##3456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 ## 10 20 30 40 50 60 70 80 ## ## Info: ## Example of how to use libnotify correctl...
def printCaps (): info = pynotify.get_server_info () print "Name: " + info["name"] print "Vendor: " + info["vendor"] print "Version: " + info["version"] print "Spec. Version: " + info["spec-version"] caps = pynotify.get_server_caps () if caps is None: print "Failed to receive se...
caps = pynotify.get_server_caps () if caps is None: print "Failed to receive server caps." sys.exit (1) for cap in caps: capabilities[cap] = True
identifier_body
summary-body.py
#!/usr/bin/python ################################################################################ ##3456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 ## 10 20 30 40 50 60 70 80 ## ## Info: ## Example of how to use libnotify correctl...
if capabilities['x-canonical-append']: print "\tx-canonical-append" if capabilities['x-canonical-private-icon-only']: print "\tx-canonical-private-icon-only" if capabilities['x-canonical-truncation']: print "\tx-canonical-truncation" print "Notes:" if info["name"] == "notify-osd": print "\tx- and y-coord...
print "\tx-canonical-private-synchronous"
conditional_block
summary-body.py
#!/usr/bin/python ################################################################################ ##3456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 ## 10 20 30 40 50 60 70 80 ## ## Info: ## Example of how to use libnotify correctl...
(): info = pynotify.get_server_info () print "Name: " + info["name"] print "Vendor: " + info["vendor"] print "Version: " + info["version"] print "Spec. Version: " + info["spec-version"] caps = pynotify.get_server_caps () if caps is None: print "Failed to receive server caps." s...
printCaps
identifier_name
function-arguments.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 ...
// CHECK: @mutable_unsafe_borrow(%UnsafeInner* noalias dereferenceable(2)) // ... unless this is a mutable borrow, those never alias #[no_mangle] pub fn mutable_unsafe_borrow(_: &mut UnsafeInner) { } // CHECK: @mutable_borrow(i32* noalias dereferenceable(4)) // FIXME #25759 This should also have `nocapture` #[no_man...
{ }
identifier_body
function-arguments.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 ...
() -> S { S { _field: [0, 0, 0, 0] } } // CHECK: noalias i8* @allocator() #[no_mangle] #[allocator] pub fn allocator() -> *const i8 { std::ptr::null() }
struct_return
identifier_name
function-arguments.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 ...
} } // CHECK: noalias i8* @allocator() #[no_mangle] #[allocator] pub fn allocator() -> *const i8 { std::ptr::null() }
// CHECK: @struct_return(%S* noalias nocapture sret dereferenceable(32)) #[no_mangle] pub fn struct_return() -> S { S { _field: [0, 0, 0, 0]
random_line_split
dojoConfiguration.js
/*global dojoConfig:true */ /*jslint browser:true,sloppy:true,nomen:true,unparam:true,plusplus:true,indent:4 */ /* | Copyright 2013 Esri | | 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 ...
async: true, baseURL: root, packages: [{ name: "application", location: root }, { name: "widgets", location: root + '/js/library/widgets' }, { name: "coreLibrary", location: root + '/js/library/coreLibrary' }] };
var root = location.href.slice(0, location.href.lastIndexOf('/')); dojoConfig = { parseOnLoad: true,
random_line_split
abstract_method.d.ts
declare namespace ಠ_ಠ.clutz.abstract_method { class Chil
ends Child_Instance { } class Child_Instance extends ಠ_ಠ.clutz.abstract_method.Clazz_Instance { bar (a : number ) : string ; } } declare namespace goog { function require(name: 'abstract_method.Child'): typeof ಠ_ಠ.clutz.abstract_method.Child; } declare module 'goog:abstract_method.Child' { import alias = ...
d ext
identifier_name
abstract_method.d.ts
declare namespace ಠ_ಠ.clutz.abstract_method { class Child extends Child_Instance { } class Child_Instance extends ಠ_ಠ.clutz.abstract_method.Clazz_Instance { bar (a : number ) : string ; } } declare namespace goog { function require(name: 'abstract_method.Child'): typeof ಠ_ಠ.clutz.abstract_method.Child; } ...
declare module 'goog:abstract_method.Clazz' { import alias = ಠ_ಠ.clutz.abstract_method.Clazz; export default alias; } declare namespace ಠ_ಠ.clutz.abstract_method { interface Interface { bar (a : number ) : string ; foo ( ) : string ; } } declare module 'goog:abstract_method.Interface' { import alias =...
declare namespace goog { function require(name: 'abstract_method.Clazz'): typeof ಠ_ಠ.clutz.abstract_method.Clazz; }
random_line_split
Flow.tsx
/** * Created by yanming on 17/6/29. */ import * as React from 'react' import classnames from 'classnames' import { Icon } from '../index' import { FlowItemProps as FlowItemBaseProps, FlowProps as FlowBaseProps } from './PropTypes' export interface FlowPropsType extends FlowBaseProps { prefixCls?: string; classN...
extends React.Component<FlowPropsType, {}> { static defaultProps = { prefixCls: 'NEUI', current: 0, direction: 'horizontal', children: [] } static Item = FlowItem render () { const {className, prefixCls, children, current, direction, ...others} = this.props const cls = classnames({ ...
Flow
identifier_name
Flow.tsx
/** * Created by yanming on 17/6/29. */ import * as React from 'react' import classnames from 'classnames' import { Icon } from '../index' import { FlowItemProps as FlowItemBaseProps, FlowProps as FlowBaseProps } from './PropTypes' export interface FlowPropsType extends FlowBaseProps { prefixCls?: string; classN...
[className as string]: !!className }) return ( <div className={cls} {...others}> { React.Children.map(children, (el, index) => { const props = { number: index + 1, key: (typeof el !== 'string' && typeof el !== 'number' && el.key) || index, ...
const cls = classnames({ [`${prefixCls}_flow`]: true, [`${prefixCls}_flow_vertical`]: direction === 'vertical',
random_line_split
Flow.tsx
/** * Created by yanming on 17/6/29. */ import * as React from 'react' import classnames from 'classnames' import { Icon } from '../index' import { FlowItemProps as FlowItemBaseProps, FlowProps as FlowBaseProps } from './PropTypes' export interface FlowPropsType extends FlowBaseProps { prefixCls?: string; classN...
<p className={`${prefixCls}_flow_body_title`}>{title}</p> </div> <div className={`${prefixCls}_flow_tail`} /> </div> ) } } export default class Flow extends React.Component<FlowPropsType, {}> { static defaultProps = { prefixCls: 'NEUI', current: 0, direction: 'hori...
{ const {prefixCls, title, status, className, number} = this.props const cls = classnames({ [`${prefixCls}_flow_item`]: true, [`${prefixCls}_flow_item_${status}`]: true, [className as string]: !!className }) return ( <div className={cls}> <div className={`${prefixCls}_f...
identifier_body
package_integrity_test.py
import os import unittest from conans.model.ref import ConanFileReference, PackageReference from conans.test.utils.conanfile import TestConanFile from conans.test.utils.tools import TestClient, TestServer,\ NO_SETTINGS_PACKAGE_ID from conans.util.files import set_dirty class PackageIngrityTest(unittest.TestCase)...
(self): client = TestClient() client.save({"conanfile.py": str(TestConanFile())}) client.run("create . lasote/testing") self.assertNotIn('does not contain a number!', client.out) ref = ConanFileReference.loads("Hello/0.1@lasote/testing") conan_folder = client.cache.packag...
remove_locks_test
identifier_name
package_integrity_test.py
import os import unittest from conans.model.ref import ConanFileReference, PackageReference from conans.test.utils.conanfile import TestConanFile from conans.test.utils.tools import TestClient, TestServer,\ NO_SETTINGS_PACKAGE_ID from conans.util.files import set_dirty class PackageIngrityTest(unittest.TestCase)...
ref = ConanFileReference.loads("Hello/0.1@lasote/testing") pref = PackageReference(ref, NO_SETTINGS_PACKAGE_ID) package_folder = client.cache.package_layout(pref.ref).package(pref) set_dirty(package_folder) client.run("upload * --all --confirm", assert_error=True) self.a...
users={"default": [("lasote", "mypass")]}) client.save({"conanfile.py": str(TestConanFile())}) client.run("create . lasote/testing")
random_line_split
package_integrity_test.py
import os import unittest from conans.model.ref import ConanFileReference, PackageReference from conans.test.utils.conanfile import TestConanFile from conans.test.utils.tools import TestClient, TestServer,\ NO_SETTINGS_PACKAGE_ID from conans.util.files import set_dirty class PackageIngrityTest(unittest.TestCase)...
test_server = TestServer([], users={"lasote": "mypass"}) client = TestClient(servers={"default": test_server}, users={"default": [("lasote", "mypass")]}) client.save({"conanfile.py": str(TestConanFile())}) client.run("create . lasote/testing") ref = Co...
def remove_locks_test(self): client = TestClient() client.save({"conanfile.py": str(TestConanFile())}) client.run("create . lasote/testing") self.assertNotIn('does not contain a number!', client.out) ref = ConanFileReference.loads("Hello/0.1@lasote/testing") conan_folder ...
identifier_body
_tceparser.py
""" Tensor Contraction Engine output parser. This module provides parsers of the output of the Tensor Contraction Engine of So Hirata into Tensor objects in drudge. """ import collections import itertools import re from sympy import nsimplify, sympify, Symbol from drudge import Term # # The driver function # --...
# Iterate over the factors. terms = [] for match_res in re.finditer(regex, factors_str): # Test if the result matches a factor. if match_res.group('factor') is None: raise ValueError('Invalid factor string', factors_str) # The value of the factor. factor_value =...
factor_regex, mismatch_regex )
random_line_split
_tceparser.py
""" Tensor Contraction Engine output parser. This module provides parsers of the output of the Tensor Contraction Engine of So Hirata into Tensor objects in drudge. """ import collections import itertools import re from sympy import nsimplify, sympify, Symbol from drudge import Term # # The driver function # --...
(line, range_cb, base_cb, free_vars): """Parse a TCE output line into a list of terms. """ # Get the initial part in the bracket and the actual term specification # part after it. match_res = re.match( r'^\s*\[(?P<factors>.*)\](?P<term>[^\[\]]+)$', line ) if match_res is Non...
_parse_tce_line
identifier_name
_tceparser.py
""" Tensor Contraction Engine output parser. This module provides parsers of the output of the Tensor Contraction Engine of So Hirata into Tensor objects in drudge. """ import collections import itertools import re from sympy import nsimplify, sympify, Symbol from drudge import Term # # The driver function # --...
else: subs = {} # Add the result. terms.append(raw_term.subst(subs).scale(factor_value)) # Continue to the next factor. continue return terms
from_vars = match_res.group('perm_from').split() to_vars = match_res.group('perm_to').split() subs = { Symbol(from_var): Symbol(to_var) for from_var, to_var in zip(from_vars, to_vars) }
conditional_block
_tceparser.py
""" Tensor Contraction Engine output parser. This module provides parsers of the output of the Tensor Contraction Engine of So Hirata into Tensor objects in drudge. """ import collections import itertools import re from sympy import nsimplify, sympify, Symbol from drudge import Term # # The driver function # --...
# # Internal functions # ------------------ # def _parse_tce_line(line, range_cb, base_cb, free_vars): """Parse a TCE output line into a list of terms. """ # Get the initial part in the bracket and the actual term specification # part after it. match_res = re.match( r'^\s*\[(?P<factors...
"""Parse a TCE output into a list of terms. A list of terms, and a dictionary of free symbols will be returned. """ lines = [] for line in tce_out.splitlines(): stripped = line.strip() if len(stripped) > 0: lines.append(stripped) continue free_vars = collection...
identifier_body
forms.py
"""Forms to render HTML input & validate request data.""" from wtforms import Form, BooleanField, DateTimeField, PasswordField from wtforms import TextAreaField, TextField from wtforms.validators import Length, required class
(Form): """Render HTML input for Appointment model & validate submissions. This matches the models.Appointment class very closely. Where models.Appointment represents the domain and its persistence, this class represents how to display a form in HTML & accept/reject the results. """ title = Tex...
AppointmentForm
identifier_name
forms.py
"""Forms to render HTML input & validate request data.""" from wtforms import Form, BooleanField, DateTimeField, PasswordField from wtforms import TextAreaField, TextField from wtforms.validators import Length, required class AppointmentForm(Form): """Render HTML input for Appointment model & validate submission...
end = DateTimeField('End') allday = BooleanField('All Day') location = TextField('Location', [Length(max=255)]) description = TextAreaField('Description') class LoginForm(Form): """Render HTML input for user login form. Authentication (i.e. password verification) happens in the view function....
start = DateTimeField('Start', [required()])
random_line_split
forms.py
"""Forms to render HTML input & validate request data.""" from wtforms import Form, BooleanField, DateTimeField, PasswordField from wtforms import TextAreaField, TextField from wtforms.validators import Length, required class AppointmentForm(Form):
class LoginForm(Form): """Render HTML input for user login form. Authentication (i.e. password verification) happens in the view function. """ username = TextField('Username', [required()]) password = PasswordField('Password', [required()])
"""Render HTML input for Appointment model & validate submissions. This matches the models.Appointment class very closely. Where models.Appointment represents the domain and its persistence, this class represents how to display a form in HTML & accept/reject the results. """ title = TextField('Titl...
identifier_body
controllers.py
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from flask import jsonify, session from marshmallow import INCLUDE, fields from marshmallow_enum import En...
class RHCategorySearchDisplay(RHDisplayCategoryBase): def _process(self): return WPCategorySearch.render_template('category_search.html', self.category) class RHEventSearchDisplay(RHDisplayEventBase): def _process(self): return WPEventSearch.render_template('event_search.html', self.event) ...
return WPSearch.render_template('search.html')
identifier_body
controllers.py
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from flask import jsonify, session from marshmallow import INCLUDE, fields from marshmallow_enum import En...
(RH): def _process(self): return WPSearch.render_template('search.html') class RHCategorySearchDisplay(RHDisplayCategoryBase): def _process(self): return WPCategorySearch.render_template('category_search.html', self.category) class RHEventSearchDisplay(RHDisplayEventBase): def _process(s...
RHSearchDisplay
identifier_name
controllers.py
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from flask import jsonify, session from marshmallow import INCLUDE, fields from marshmallow_enum import En...
class RHAPISearch(RH): """API for searching across all records with the current search provider. Besides pagination, filters or placeholders may be passed as query parameters. Since `type` may be a list, the results from the search provider are not mixed with the InternalSearch. """ @use_kwa...
def _process(self): return WPEventSearch.render_template('event_search.html', self.event)
random_line_split
controllers.py
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from flask import jsonify, session from marshmallow import INCLUDE, fields from marshmallow_enum import En...
result = search_provider().search(q, session.user, page, type, **params) return ResultSchema().dump(result) class RHAPISearchOptions(RH): def _process(self): search_provider = get_search_provider()() placeholders = search_provider.get_placeholders() sort_options = search_p...
search_provider = InternalSearch
conditional_block
setup.py
from setuptools import setup version = 'y.dev0' long_description = '\n\n'.join([ open('README.rst').read(), open('TODO.rst').read(), open('CREDITS.rst').read(), open('CHANGES.rst').read(), ]) install_requires = [ 'pkginfo', 'setuptools', 'nens', ], tests_require = [ ] setup(...
long_description=long_description, # Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[], keywords=[], author='Pieter Swinkels', author_email='pieter.swinkels@nelen-schuurmans.nl', url='', license='GPL', packages=['timeseries'], ...
version=version, description="Package to implement time series and generic operations on time series.",
random_line_split
forStatementsMultipleInvalidDecl.ts
interface I { id: number; } class
implements I { id: number; valid: boolean; } class C2 extends C { name: string; } class D<T>{ source: T; recurse: D<T>; wrapped: D<D<T>> } function F(x: string): number { return 42; } module M { export class A { name: string; } export function F2(x...
C
identifier_name
forStatementsMultipleInvalidDecl.ts
interface I { id: number; } class C implements I { id: number; valid: boolean; } class C2 extends C { name: string; }
} function F(x: string): number { return 42; } module M { export class A { name: string; } export function F2(x: number): string { return x.toString(); } } // all of these are errors for( var a: any;;){} for( var a = 1;;){} for( var a = 'a string';;){} for( var a = new C();;){} ...
class D<T>{ source: T; recurse: D<T>; wrapped: D<D<T>>
random_line_split
forStatementsMultipleInvalidDecl.ts
interface I { id: number; } class C implements I { id: number; valid: boolean; } class C2 extends C { name: string; } class D<T>{ source: T; recurse: D<T>; wrapped: D<D<T>> } function F(x: string): number { return 42; } module M { export class A { name...
} // all of these are errors for( var a: any;;){} for( var a = 1;;){} for( var a = 'a string';;){} for( var a = new C();;){} for( var a = new D<string>();;){} for( var a = M;;){} for( var b: I;;){} for( var b = new C();;){} for( var b = new C2();;){} for(var f = F;;){} for( var f = (x: number) => ''...
{ return x.toString(); }
identifier_body
forStatementsMultipleInvalidDecl.ts
interface I { id: number; } class C implements I { id: number; valid: boolean; } class C2 extends C { name: string; } class D<T>{ source: T; recurse: D<T>; wrapped: D<D<T>> } function F(x: string): number { return 42; } module M { export class A { name...
for( var b: I;;){} for( var b = new C();;){} for( var b = new C2();;){} for(var f = F;;){} for( var f = (x: number) => '';;){} for(var arr: string[];;){} for( var arr = [1, 2, 3, 4];;){} for( var arr = [new C(), new C2(), new D<string>()];;){} for(var arr2 = [new D<string>()];;){} for( var arr2 = new...
{}
conditional_block
expr-match-generic.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { test_bool(); test_rec(); }
{ fn compare_rec(t1: Pair, t2: Pair) -> bool { t1.a == t2.a && t1.b == t2.b } test_generic::<Pair>(Pair {a: 1, b: 2}, compare_rec); }
identifier_body
expr-match-generic.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
, _ => fail!("wat") }; assert!((eq(expected, actual))); } fn test_bool() { fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; } test_generic::<bool>(true, compare_bool); } #[deriving(Clone)] struct Pair { a: int, b: int, } fn test_rec() { fn compare_rec(t1: Pair, t2: Pair) -> bool...
{ expected.clone() }
conditional_block
expr-match-generic.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T:Clone>(expected: T, eq: compare<T>) { let actual: T = match true { true => { expected.clone() }, _ => fail!("wat") }; assert!((eq(expected, actual))); } fn test_bool() { fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; } test_generic::<bool>(true, compare_bool); } #[deriving(Clone)] str...
test_generic
identifier_name
expr-match-generic.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[deriving(Clone)] struct Pair { a: int, b: int, } fn test_rec() { fn compare_rec(t1: Pair, t2: Pair) -> bool { t1.a == t2.a && t1.b == t2.b } test_generic::<Pair>(Pair {a: 1, b: 2}, compare_rec); } pub fn main() { test_bool(); test_rec(); }
fn test_bool() { fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; } test_generic::<bool>(true, compare_bool); }
random_line_split
0001_initial.py
# -*- coding: utf-8 -*- from south.db import db from south.v2 import SchemaMigration try: from django.contrib.auth import get_user_model except ImportError: # django < 1.5 from django.contrib.auth.models import User else: User = get_user_model() class Migration(SchemaMigration): def forwards(self, ...
models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.model...
db.delete_table('authtoken_token')
identifier_body
0001_initial.py
# -*- coding: utf-8 -*- from south.db import db from south.v2 import SchemaMigration try: from django.contrib.auth import get_user_model except ImportError: # django < 1.5 from django.contrib.auth.models import User else: User = get_user_model() class Migration(SchemaMigration): def forwards(self, ...
(self, orm): # Deleting model 'Token' db.delete_table('authtoken_token') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [...
backwards
identifier_name
0001_initial.py
# -*- coding: utf-8 -*- from south.db import db from south.v2 import SchemaMigration try: from django.contrib.auth import get_user_model except ImportError: # django < 1.5 from django.contrib.auth.models import User else:
class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Token' db.create_table('authtoken_token', ( ('key', self.gf('django.db.models.fields.CharField')(max_length=40, primary_key=True)), ('user', self.gf('django.db.models.fields.related.OneToOneField')...
User = get_user_model()
conditional_block
0001_initial.py
# -*- coding: utf-8 -*- from south.db import db from south.v2 import SchemaMigration try: from django.contrib.auth import get_user_model except ImportError: # django < 1.5 from django.contrib.auth.models import User else: User = get_user_model() class Migration(SchemaMigration): def forwards(self, ...
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['authtoken']
random_line_split
utils.py
""" A universal module with functions / classes without dependencies. """ import sys import contextlib import functools import re import os from jedi._compatibility import reraise _sep = os.path.sep if os.path.altsep is not None: _sep += os.path.altsep _path_re = re.compile('(?:\.[^{0}]+|[{0}]__init__\.py)$'.for...
def safe_property(func): return property(reraise_uncaught(func)) def reraise_uncaught(func): """ Re-throw uncaught `AttributeError`. Usage: Put ``@rethrow_uncaught`` in front of the function which does **not** suppose to raise `AttributeError`. AttributeError is easily get caught by `has...
""" Important, because `__getattr__` and `hasattr` catch AttributeErrors implicitly. This is really evil (mainly because of `__getattr__`). `hasattr` in Python 2 is even more evil, because it catches ALL exceptions. Therefore this class originally had to be derived from `BaseException` instead of `E...
identifier_body
utils.py
""" A universal module with functions / classes without dependencies. """ import sys import contextlib import functools import re import os from jedi._compatibility import reraise _sep = os.path.sep if os.path.altsep is not None: _sep += os.path.altsep _path_re = re.compile('(?:\.[^{0}]+|[{0}]__init__\.py)$'.for...
(self): if self.pushes: self.current = self.pushes.pop() else: self.current = next(self.iterator) return self.current @contextlib.contextmanager def ignored(*exceptions): """ Context manager that ignores all of the specified exceptions. This will be in the s...
__next__
identifier_name
utils.py
""" A universal module with functions / classes without dependencies. """ import sys import contextlib import functools import re import os from jedi._compatibility import reraise _sep = os.path.sep if os.path.altsep is not None:
_path_re = re.compile('(?:\.[^{0}]+|[{0}]__init__\.py)$'.format(re.escape(_sep))) del _sep def to_list(func): def wrapper(*args, **kwargs): return list(func(*args, **kwargs)) return wrapper def unite(iterable): """Turns a two dimensional array into a one dimensional.""" return set(typ for t...
_sep += os.path.altsep
conditional_block
utils.py
""" A universal module with functions / classes without dependencies. """ import sys import contextlib import functools import re import os from jedi._compatibility import reraise _sep = os.path.sep if os.path.altsep is not None: _sep += os.path.altsep _path_re = re.compile('(?:\.[^{0}]+|[{0}]__init__\.py)$'.for...
""" Context manager that ignores all of the specified exceptions. This will be in the standard library starting with Python 3.4. """ try: yield except exceptions: pass def indent_block(text, indention=' '): """This function indents a text block with a default of four spa...
@contextlib.contextmanager def ignored(*exceptions):
random_line_split
Root.tsx
import * as React from 'react'; import * as ViewMessage from './elements/ViewMessage/ViewMessage'; import ExternalLink from './elements/ExternalLink/ExternalLink'; interface State { hasError: boolean; } class Root extends React.Component<{}, State> { constructor(props: {}) { super(props); this.state = { ...
export default Root;
} }
random_line_split
Root.tsx
import * as React from 'react'; import * as ViewMessage from './elements/ViewMessage/ViewMessage'; import ExternalLink from './elements/ExternalLink/ExternalLink'; interface State { hasError: boolean; } class Root extends React.Component<{}, State> { constructor(props: {}) { super(props); this.state = { ...
render() { if (this.state.hasError) { return ( <ViewMessage.Notice> <p> <span role='img' aria-label='boom'> 💥 </span>{' '} Something wrong happened </p> <ViewMessage.Sub> If it happens again, please{' '} ...
{ // RIP this.setState({ hasError: true }); }
identifier_body
Root.tsx
import * as React from 'react'; import * as ViewMessage from './elements/ViewMessage/ViewMessage'; import ExternalLink from './elements/ExternalLink/ExternalLink'; interface State { hasError: boolean; } class Root extends React.Component<{}, State> { constructor(props: {}) { super(props); this.state = { ...
() { if (this.state.hasError) { return ( <ViewMessage.Notice> <p> <span role='img' aria-label='boom'> 💥 </span>{' '} Something wrong happened </p> <ViewMessage.Sub> If it happens again, please{' '} ...
render
identifier_name
Root.tsx
import * as React from 'react'; import * as ViewMessage from './elements/ViewMessage/ViewMessage'; import ExternalLink from './elements/ExternalLink/ExternalLink'; interface State { hasError: boolean; } class Root extends React.Component<{}, State> { constructor(props: {}) { super(props); this.state = { ...
return this.props.children; } } export default Root;
{ return ( <ViewMessage.Notice> <p> <span role='img' aria-label='boom'> 💥 </span>{' '} Something wrong happened </p> <ViewMessage.Sub> If it happens again, please{' '} <ExternalLink href='https://githu...
conditional_block
app.component.ts
/* * Angular 2 decorators and services */ import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { AppState } from './app.service'; /* * App Component * Top Level Component */ @Component({ selector: 'app', encapsulation: ViewEncapsulation.None, styleUrls: [ './app.component.c...
implements OnInit { public angularclassLogo = 'agit ssets/img/angularclass-avatar.png'; public name = 'Angular 2 Webpack Starter'; public url = 'https://twitter.com/AngularClass'; /* constructor( // public appState: AppState ) {} */ public ngOnInit() { // console.log('Initial App State', this.a...
AppComponent
identifier_name
app.component.ts
/* * Angular 2 decorators and services */ import { Component,
OnInit, ViewEncapsulation } from '@angular/core'; import { AppState } from './app.service'; /* * App Component * Top Level Component */ @Component({ selector: 'app', encapsulation: ViewEncapsulation.None, styleUrls: [ './app.component.css' ], templateUrl: 'app.component.html' }) export class AppCo...
random_line_split
internalAliasClassInsideLocalModuleWithExport.js
//// [internalAliasClassInsideLocalModuleWithExport.js] (function (x) { var c = (function () { function c() { } c.prototype.foo = function (a) { return a; };
})(exports.x || (exports.x = {})); var x = exports.x; (function (m2) { (function (m3) { var c = x.c; m3.c = c; m3.cProp = new c(); var cReturnVal = m3.cProp.foo(10); })(m2.m3 || (m2.m3 = {})); var m3 = m2.m3; })(exports.m2 || (exports.m2 = {})); var m2 = exports....
return c; })(); x.c = c;
random_line_split
internalAliasClassInsideLocalModuleWithExport.js
//// [internalAliasClassInsideLocalModuleWithExport.js] (function (x) { var c = (function () { function
() { } c.prototype.foo = function (a) { return a; }; return c; })(); x.c = c; })(exports.x || (exports.x = {})); var x = exports.x; (function (m2) { (function (m3) { var c = x.c; m3.c = c; m3.cProp = new c(); var cR...
c
identifier_name
internalAliasClassInsideLocalModuleWithExport.js
//// [internalAliasClassInsideLocalModuleWithExport.js] (function (x) { var c = (function () { function c()
c.prototype.foo = function (a) { return a; }; return c; })(); x.c = c; })(exports.x || (exports.x = {})); var x = exports.x; (function (m2) { (function (m3) { var c = x.c; m3.c = c; m3.cProp = new c(); var cReturnVal = m3.c...
{ }
identifier_body
plugin-install.js
/* global plugininstallL10n, tb_click */ /* Plugin Browser Thickbox related JS*/ var tb_position; jQuery( document ).ready( function( $ ) { tb_position = function() { var tbWindow = $( '#TB_window' ), width = $( window ).width(), H = $( window ).height() - ( ( 792 < width ) ? 60 : 20 ), W = ( 792 ...
href = href.replace( /&width=[0-9]+/g, '' ); href = href.replace( /&height=[0-9]+/g, '' ); $(this).attr( 'href', href + '&width=' + W + '&height=' + ( H ) ); }); }; $( window ).resize( function() { tb_position(); }); $( '.plugin-card, .plugins .column-description' ).on( 'click', 'a.thickb...
{ return; }
conditional_block
plugin-install.js
/* global plugininstallL10n, tb_click */ /* Plugin Browser Thickbox related JS*/ var tb_position; jQuery( document ).ready( function( $ ) { tb_position = function() { var tbWindow = $( '#TB_window' ), width = $( window ).width(), H = $( window ).height() - ( ( 792 < width ) ? 60 : 20 ), W = ( 792 ...
event.preventDefault(); // Flip the tab $( '#plugin-information-tabs a.current' ).removeClass( 'current' ); $( this ).addClass( 'current' ); // Only show the fyi box in the description section, on smaller screen, where it's otherwise always displayed at the top. if ( 'description' !== tab && $( win...
$( '#plugin-information-tabs a' ).click( function( event ) { var tab = $( this ).attr( 'name' );
random_line_split
i18n.test.ts
(str: string): string { let hex; let result = ""; for (let i = 0; i < str.length; i++) { hex = str.charCodeAt(i).toString(16); result += "\\u00" + hex; } return result; } test("formatNumber", async () => { const cases: { value: number; unit?: string; expected: { [lang: string]: string...
hexEncode
identifier_name
i18n.test.ts
return result; } test("formatNumber", async () => { const cases: { value: number; unit?: string; expected: { [lang: string]: string }; }[] = [ { value: 150000000, expected: { de: "150\xa0Mio.", en: "150M", es: "150\xa0M", fr: "150\xa0M", // \xa0 is a ...
{ hex = str.charCodeAt(i).toString(16); result += "\\u00" + hex; }
conditional_block
i18n.test.ts
return result; } test("formatNumber", async () => { const cases: { value: number; unit?: string; expected: { [lang: string]: string }; }[] = [ { value: 150000000, expected: { de: "150\xa0Mio.", en: "150M", es: "150\xa0M", fr: "150\xa0M", // \xa0 is a non...
ru: "20 т", }, }, { value: 0.05, unit: "kWh", expected: { de: "0,05 kWh", en: "0.05 kWh", es: "0,05 kWh", fr: "0,05 kWh", hi: "0.05 kWh", it: "0,05 kWh", ja: "0.05 kWh", ko: "0.05kWh", ru: "0,05 кВт⋅ч", ...
ja: "20 t", ko: "20t",
random_line_split
i18n.test.ts
test("formatNumber", async () => { const cases: { value: number; unit?: string; expected: { [lang: string]: string }; }[] = [ { value: 150000000, expected: { de: "150\xa0Mio.", en: "150M", es: "150\xa0M", fr: "150\xa0M", // \xa0 is a non-breaking space ...
{ let hex; let result = ""; for (let i = 0; i < str.length; i++) { hex = str.charCodeAt(i).toString(16); result += "\\u00" + hex; } return result; }
identifier_body
http.py
{4})' __Y2 = r'(?P<year>\d{2})' __T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})' RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T)) RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T)) ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y)) ...
return [etag_str] etags = [e.encode('ascii').decode('unicode_escape') for e in etags] return etags def quote_etag(etag): """ Wraps a string in double quotes escaping contents as necessary. """ return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"') def same_origin
etags = ETAG_MATCH.findall(etag_str) if not etags: # etag_str has wrong format, treat it as an opaque string then
random_line_split
http.py
4})' __Y2 = r'(?P<year>\d{2})' __T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})' RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T)) RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T)) ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y)) R...
value = int(s, 36) # ... then do a final check that the value will fit into an int to avoid # returning a long (#15067). The long type was removed in Python 3. if six.PY2 and value > sys.maxint: raise ValueError("Base36 input too large") return value def int_to_base36(i): """ Conv...
raise ValueError("Base36 input too large")
conditional_block
http.py
encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring. """ return force_text(quote(force_str(url), force_str(safe))) urlquote = allow_lazy(urlquote, six.text_type) def urlquote_plus(url, safe=''): "...
""" Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host and uses a safe scheme). Always returns ``False`` on an empty url. """ if url is not None: url = url.strip() if not url: return False if six.PY2: try: url = fo...
identifier_body
http.py
4})' __Y2 = r'(?P<year>\d{2})' __T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})' RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T)) RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T)) ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y)) R...
(query, doseq=0): """ A version of Python's urllib.urlencode() function that can operate on unicode strings. The parameters are first cast to UTF-8 encoded strings and then encoded as per normal. """ if isinstance(query, MultiValueDict): query = query.lists() elif hasattr(query, 'ite...
urlencode
identifier_name
resolver.test.js
import { fileURLToPath } from "url"; import enhanced from "enhanced-resolve"; import sass from "sass";
* external packages, we want to test it separately to ensure its API does not * change unexpectedly. */ describe("getWebpackResolver", () => { const resolve = (request, ...options) => getWebpackResolver(enhanced.create, sass, ...options)(__filename, request); it("should resolve .scss from node_modules", asy...
import { getWebpackResolver } from "../src/utils"; /** * Because `getWebpackResolver` is a public function that can be imported by
random_line_split
resolver.test.js
import { fileURLToPath } from "url"; import enhanced from "enhanced-resolve"; import sass from "sass"; import { getWebpackResolver } from "../src/utils"; /** * Because `getWebpackResolver` is a public function that can be imported by * external packages, we want to test it separately to ensure its API does not * ...
});
{ // a `file:` URI with two `/`s indicates the next segment is a hostname, // which Node restricts to `localhost` on Unix platforms. Because it is // nevertheless commonly used, the resolver converts it to a relative path. // Node does allow specifying remote hosts in the Windows environment, so // ...
conditional_block
fixtures.ts
import { BigIntOrderedMap, Content, GraphNode, unixToDa } from '@urbit/api'; import bigInt, { BigInteger } from 'big-integer'; export const makeComment = ( author: string, time: number, parentIndex: string, contents: Content[] ): [BigInteger, GraphNode] => { const da = unixToDa(time); const index = `${pare...
post: { index, author, 'time-sent': time, signatures: [], contents: [], hash: null }, children } ]; };
random_line_split
views.py
from django.views.generic import ListView, DetailView from .forms import OrganisationSearchForm from .models import Organisation class OrganisationSearchView(ListView): template_name = 'justizgelder/search.html' paginate_by = 25 def get_queryset(self): self.form = OrganisationSearchForm(self.req...
return context class OrganisationDetail(DetailView): template_name = 'justizgelder/organisation_detail.html' model = Organisation def get_context_data(self, **kwargs): context = super(OrganisationDetail, self).get_context_data(**kwargs) return context
context['base_template'] = 'justizgelder/embed_base.html'
conditional_block
views.py
from django.views.generic import ListView, DetailView from .forms import OrganisationSearchForm from .models import Organisation class OrganisationSearchView(ListView): template_name = 'justizgelder/search.html' paginate_by = 25 def get_queryset(self): self.form = OrganisationSearchForm(self.req...
model = Organisation def get_context_data(self, **kwargs): context = super(OrganisationDetail, self).get_context_data(**kwargs) return context
template_name = 'justizgelder/organisation_detail.html'
random_line_split
views.py
from django.views.generic import ListView, DetailView from .forms import OrganisationSearchForm from .models import Organisation class
(ListView): template_name = 'justizgelder/search.html' paginate_by = 25 def get_queryset(self): self.form = OrganisationSearchForm(self.request.GET) result, self.aggregates = self.form.search() return result def get_context_data(self, **kwargs): context = super(Organisa...
OrganisationSearchView
identifier_name
views.py
from django.views.generic import ListView, DetailView from .forms import OrganisationSearchForm from .models import Organisation class OrganisationSearchView(ListView): template_name = 'justizgelder/search.html' paginate_by = 25 def get_queryset(self): self.form = OrganisationSearchForm(self.req...
class OrganisationDetail(DetailView): template_name = 'justizgelder/organisation_detail.html' model = Organisation def get_context_data(self, **kwargs): context = super(OrganisationDetail, self).get_context_data(**kwargs) return context
context = super(OrganisationSearchView, self).get_context_data(**kwargs) context['aggregates'] = self.aggregates context['query'] = self.request.GET.get('q') context['form'] = self.form context['base_template'] = 'justizgelder/search_base.html' if self.req...
identifier_body
upload.rs
(())), x => x, } } fn start_send(self: Pin<&mut Self>, msg: T) -> Result<(), Self::Error> { match self.project().inner.start_send(msg) { Err(e) if e.is_disconnected() => Ok(()), x => x, } } fn poll_flus...
} = state.take(); let ctx = RepositoryRequestContext::instantiate(state, repository.clone(), LfsMethod::Upload).await?;
random_line_split
upload.rs
97; P 99), } // Small buffers for Filestore & Dewey const BUFFER_SIZE: usize = 5; mod closeable_sender { use pin_project::pin_project; use futures::{ channel::mpsc::{SendError, Sender}, sink::Sink, task::{Context, Poll}, }; use std::pin::Pin; #[pin_project] pub struct...
<S>( ctx: &RepositoryRequestContext, oid: Sha256, size: u64, body: S, scuba: &mut Option<&mut ScubaMiddlewareState>, ) -> Result<(), Error> where S: Stream<Item = Result<Bytes, ()>> + Unpin + Send + 'static, { let (internal_send, internal_recv) = channel::<Result<Bytes, ()>>(BUFFER_SIZE); ...
upload_from_client
identifier_name
currency.js
Optional path to a file containing currency conversion data. Prebid.org hosts a file that is used as the default, * if not specified. * @param {object} [config.rates] * This optional argument allows you to specify the rates with a JSON object, subverting the need for a external * config.conversionRateFile pa...
{ if (fromCurrency in currencyRates.conversions) { // using direct conversion rate from fromCurrency to toCurrency rates = currencyRates.conversions[fromCurrency]; if (!(toCurrency in rates)) { // bid should fail, currency is not supported throw new Error('Specified adServerCurrenc...
conditional_block
currency.js
represents the target currency. (e.g. 'EUR'). If this value is present, * the currency conversion feature is activated. * @param {number} [config.granularityMultiplier = 1] * A decimal value representing how mcuh to scale the price granularity calculations. * @param {object} config.bidderCurrencyDefault * A...
// bid should fail, currency is not supported throw new Error('Specified adServerCurrency in config \'' + toCurrency + '\' not found in the currency rates file'); } conversionRate
{ var conversionRate = null; var rates; let cacheKey = `${fromCurrency}->${toCurrency}`; if (cacheKey in conversionCache) { conversionRate = conversionCache[cacheKey]; utils.logMessage('Using conversionCache value ' + conversionRate + ' for ' + cacheKey); } else if (currencySupportEnabled === false) {...
identifier_body
currency.js
that represents the target currency. (e.g. 'EUR'). If this value is present, * the currency conversion feature is activated. * @param {number} [config.granularityMultiplier = 1] * A decimal value representing how mcuh to scale the price granularity calculations. * @param {object} config.bidderCurrencyDefault ...
}, error: errorSettingsRates } ); } } function resetCurrency() { utils.logInfo('Uninstalling addBidResponse decorator for currency module', arguments); getHook('addBidResponse').getHooks({hook: addBidResponseHook}).remove(); delete getGlobal().convertCurrency; adServerCurrency = '...
errorSettingsRates('Failed to parse currencyRates response: ' + response); }
random_line_split
currency.js
represents the target currency. (e.g. 'EUR'). If this value is present, * the currency conversion feature is activated. * @param {number} [config.granularityMultiplier = 1] * A decimal value representing how mcuh to scale the price granularity calculations. * @param {object} config.bidderCurrencyDefault * A...
() { while (bidResponseQueue.length > 0) { (bidResponseQueue.shift())(); } } function wrapFunction(fn, context, params) { return function() { let bid = params[1]; if (bid !== undefined && 'currency' in bid && 'cpm' in bid) { let fromCurrency = bid.currency; try { let conversion = ...
processBidResponseQueue
identifier_name
replay-server.ts
import * as ava from 'ava'; import * as crypto from 'crypto'; import * as fsExtra from 'fs-extra'; import * as http from 'http'; import * as path from 'path'; import * as request from 'request'; const projectRoot = path.join(__dirname, '..', '..'); const replayRoot = path.join(projectRoot, '..', 'replays'); const gith...
ash.update(key); hash.update('\u241F'); // UNIT SEPARATOR hash.update(val); hash.update('\u241E'); // RECORD SEPARATOR } return hash.digest('hex'); } type queryVars = { [key: string]: any // tslint:disable-line:no-any };
continue; } h
conditional_block
replay-server.ts
import * as ava from 'ava'; import * as crypto from 'crypto'; import * as fsExtra from 'fs-extra'; import * as http from 'http'; import * as path from 'path'; import * as request from 'request'; const projectRoot = path.join(__dirname, '..', '..'); const replayRoot = path.join(projectRoot, '..', 'replays'); const gith...
queryVars): string { // SHA1 is good enough for a fingerprint. const hash = crypto.createHash('sha1'); // Don't rely on JSON serialization being deterministic; properties can be // serializated in any order (in V8 it follows property creation order). for (const key of Object.keys(vars).sort()) { const va...
printQueryVars(vars:
identifier_name
replay-server.ts
import * as ava from 'ava'; import * as crypto from 'crypto'; import * as fsExtra from 'fs-extra'; import * as http from 'http'; import * as path from 'path'; import * as request from 'request'; const projectRoot = path.join(__dirname, '..', '..'); const replayRoot = path.join(projectRoot, '..', 'replays'); const gith...
} await fsExtra.emptyDir(replayDir); } function router(req: http.IncomingMessage, res: http.ServerResponse) { if (req.method === 'POST' && req.url === '/') { gqlHandler(req, res); } else { jsonHandler(req, res); } } async function sendReplayFile(res: http.ServerResponse, replay...
{ const record = process.env.RECORD === 'true'; // Kind of weirdly, t.title will include the name of the current function // plus " for " as a prefix. Get the original name instead. const testTitle = overrideTitle ? overrideTitle : t.title.replace(/^[\w\s]+ hook for /, ''); // We don't want spaces in ...
identifier_body
replay-server.ts
import * as ava from 'ava'; import * as crypto from 'crypto'; import * as fsExtra from 'fs-extra'; import * as http from 'http'; import * as path from 'path'; import * as request from 'request'; const projectRoot = path.join(__dirname, '..', '..'); const replayRoot = path.join(projectRoot, '..', 'replays'); const gith...
function fingerprintQueryVars(vars: queryVars): string { // SHA1 is good enough for a fingerprint. const hash = crypto.createHash('sha1'); // Don't rely on JSON serialization being deterministic; properties can be // serializated in any order (in V8 it follows property creation order). for (const key of Objec...
*/
random_line_split
service.py
# -*- coding: utf-8 -*- import sys import json import binascii import xbmc from lib.yd_private_libs import util, servicecontrol, jsonqueue sys.path.insert(0, util.MODULE_PATH) import YDStreamExtractor # noqa E402 import threading # noqa E402 class Service(xbmc.Monitor): def __init__(self): self.download...
self.processCommand(method.split('.', 1)[-1], self.controller.processCommandData(data)) # Remove the "Other." prefix def processCommand(self, command, args): if command == 'DOWNLOAD_STOP': YDStreamExtractor._cancelDownload() def getNextQueuedDownload(self): try: ...
return
conditional_block
service.py
# -*- coding: utf-8 -*- import sys import json import binascii import xbmc from lib.yd_private_libs import util, servicecontrol, jsonqueue sys.path.insert(0, util.MODULE_PATH) import YDStreamExtractor # noqa E402 import threading # noqa E402 class Service(xbmc.Monitor): def __init__(self): self.download...
info['data'],), kwargs={'path': info['path'], 'duration': info['duration'], 'bg': True}) t.start() while t.isAlive() and not xbmc.abortRequested: xbmc.sleep(100) info = self.getNextQueuedDownload() util.LOG('DOWNLOAD SERVICE: FINISHED') Ser...
util.LOG('DOWNLOAD SERVICE: START') info = self.getNextQueuedDownload() while info and not xbmc.abortRequested: t = threading.Thread(target=YDStreamExtractor._handleDownload, args=(
random_line_split
service.py
# -*- coding: utf-8 -*- import sys import json import binascii import xbmc from lib.yd_private_libs import util, servicecontrol, jsonqueue sys.path.insert(0, util.MODULE_PATH) import YDStreamExtractor # noqa E402 import threading # noqa E402 class Service(xbmc.Monitor): def __init__(self): self.download...
(self, command, args): if command == 'DOWNLOAD_STOP': YDStreamExtractor._cancelDownload() def getNextQueuedDownload(self): try: dataHEX = jsonqueue.XBMCJsonRAFifoQueue(util.QUEUE_FILE).pop() if not dataHEX: return None dataJSON = binas...
processCommand
identifier_name
service.py
# -*- coding: utf-8 -*- import sys import json import binascii import xbmc from lib.yd_private_libs import util, servicecontrol, jsonqueue sys.path.insert(0, util.MODULE_PATH) import YDStreamExtractor # noqa E402 import threading # noqa E402 class Service(xbmc.Monitor): def __init__(self):
def onNotification(self, sender, method, data): if not sender == 'script.module.youtube.dl': return self.processCommand(method.split('.', 1)[-1], self.controller.processCommandData(data)) # Remove the "Other." prefix def processCommand(self, command, args): if command == ...
self.downloadCount = 0 self.controller = servicecontrol.ServiceControl() self.start()
identifier_body
buttons.po.ts
import { BaseComponent } from './base.component'; export class ButtonsPo extends BaseComponent { pageUrl = '#/components/buttons'; pageTitle = 'Buttons'; ghLinkToComponent = 'https://github.com/valor-software/ngx-bootstrap/tree/development/src/buttons'; buttonNames = [ 'Left', 'Middle', 'Right' ...
isButtonEnabled(baseSelector: string, buttonName: string, enabled = true) { cy.get(`${baseSelector}`).contains(buttonName).should(enabled ? 'not.to.have.attr' : 'to.have.attr', 'disabled'); } isButtonClassActive(baseSelector: string, buttonName: string, result: string, btnSelector: string) { cy.get(`...
{ cy.get(`${baseSelector} ${btnSelector}`).contains(buttonName).should('to.be.visible'); }
identifier_body
buttons.po.ts
import { BaseComponent } from './base.component'; export class ButtonsPo extends BaseComponent { pageUrl = '#/components/buttons'; pageTitle = 'Buttons'; ghLinkToComponent = 'https://github.com/valor-software/ngx-bootstrap/tree/development/src/buttons'; buttonNames = [ 'Left', 'Middle', 'Right' ...
(baseSelector: string, buttonName: string, enabled = true) { cy.get(`${baseSelector}`).contains(buttonName).should(enabled ? 'not.to.have.attr' : 'to.have.attr', 'disabled'); } isButtonClassActive(baseSelector: string, buttonName: string, result: string, btnSelector: string) { cy.get(`${baseSelector} ${b...
isButtonEnabled
identifier_name
buttons.po.ts
import { BaseComponent } from './base.component'; export class ButtonsPo extends BaseComponent { pageUrl = '#/components/buttons'; pageTitle = 'Buttons'; ghLinkToComponent = 'https://github.com/valor-software/ngx-bootstrap/tree/development/src/buttons'; buttonNames = [ 'Left', 'Middle', 'Right' ...
}; isButtonVisible(baseSelector: string, buttonName: string, btnSelector: string) { cy.get(`${baseSelector} ${btnSelector}`).contains(buttonName).should('to.be.visible'); } isButtonEnabled(baseSelector: string, buttonName: string, enabled = true) { cy.get(`${baseSelector}`).contains(buttonName).shou...
radioBtnWithGroup: 'tab[heading="Overview"] demo-buttons-radio-with-group', radioBtnWithForms: 'tab[heading="Overview"] demo-buttons-radio-reactiveforms', disabled: 'tab[heading="Overview"] demo-buttons-disabled'
random_line_split
some.spec.ts
beforeEach(() => { pipe = new SomePipe(); }); it('should not change anything if not array', () => { expect(pipe.transform('foo', isNumber)).toEqual('foo'); expect(pipe.transform(null, isNumber)).toEqual(null); expect(pipe.transform(undefined, isNumber)).toEqual(undefined); expect(pipe.transf...
import { SomePipe } from './some'; import { isNumber, isUndefined } from '../helpers/helpers'; describe('SomePipe', () => { let pipe: SomePipe;
random_line_split
Bar.js
define("Bar", [ "Stats" ], function (Stats) { function Bar (screenWidth, screenHeight, position)
Bar.prototype.getPoint = function (position) { var parts = position.split("-"), x = 0, y = 0; if (parts.length !== 2) { return { x: 0, y: 0}; } if (parts[0] === "top") { y = 20; } else { y = 0; } if (parts[1] === "left") { x = 20; } else { ...
{ this.screenWidth = screenWidth; this.screenHeight = screenHeight; this.position = position || "top-left"; this.width = 200; this.height = 20; }
identifier_body
Bar.js
define("Bar", [ "Stats" ], function (Stats) { function Bar (screenWidth, screenHeight, position) { this.screenWidth = screenWidth; this.screenHeight = screenHeight; this.position = position || "top-left"; this.width = 200; this.height = 20; } Bar.prototype.getPoint = function (positio...
}; Bar.prototype.draw = function (ctx) { var pos = this.getPoint(this.position), grad = ctx.createLinearGradient(pos.x, pos.y,this.width,this.height), offset = 10; // Defensive check for health var if (Stats.health < 0) { Stats.health = 0; } ctx.save(); grad.add...
random_line_split
Bar.js
define("Bar", [ "Stats" ], function (Stats) { function
(screenWidth, screenHeight, position) { this.screenWidth = screenWidth; this.screenHeight = screenHeight; this.position = position || "top-left"; this.width = 200; this.height = 20; } Bar.prototype.getPoint = function (position) { var parts = position.split("-"), x = 0, ...
Bar
identifier_name
Bar.js
define("Bar", [ "Stats" ], function (Stats) { function Bar (screenWidth, screenHeight, position) { this.screenWidth = screenWidth; this.screenHeight = screenHeight; this.position = position || "top-left"; this.width = 200; this.height = 20; } Bar.prototype.getPoint = function (positio...
ctx.restore(); }; return Bar; });
{ if (Math.round(Stats.health * 10) < i) { color = 'red'; } else { color = 'green'; } ctx.fillStyle = color; offset = 20 * i; ctx.fillRect(pos.x + offset, pos.y, 15, 30); }
conditional_block
tr_es_ES.ts
<?xml version="1.0" ?><!DOCTYPE TS><TS language="es_ES" version="2.0"> <context> <name>MainPage</name> <message> <source>Synchronize settings</source> <translation>Ajustes de sincronización</translation> </message> <message> <source>Configuration</source> <translation>Con...
<message> <source>Only share when connected to this access point</source> <translation>Solo compartir cuando se conecte a este punto de acceso</translation> </message> <message> <source>Tweak media sharing settings</source> <translation>Modificar los ajustes para compartir me...
<translation>Nombre en la red</translation> </message>
random_line_split
example-uncommented.rs
#![feature(custom_attribute,plugin)] #![plugin(tag_safe)] #![allow(dead_code)] /// RAII primitive spinlock struct Spinlock; /// Handle to said spinlock struct HeldSpinlock(&'static Spinlock); /// RAII IRQ hold struct IRQLock; /// Spinlock that also disables IRQs struct
(Spinlock); static S_NON_IRQ_SPINLOCK: Spinlock = Spinlock; static S_IRQ_SPINLOCK: IrqSpinlock = IrqSpinlock(Spinlock); #[deny(not_tagged_safe)] // Make the lint an error #[req_safe(irq)] // Require this method be IRQ safe fn irq_handler() { let _lock = acquire_non_irq_spinlock(&S_NON_IRQ_SPINLOCK); //...
IrqSpinlock
identifier_name