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
sliceobject.rs
use libc::c_int; use pyport::Py_ssize_t; use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { static mut _Py_EllipsisObject: PyObject; } #[inline(always)] pub unsafe fn Py_Ellipsis() -> *mut PyObject { &mut _Py_EllipsisObject } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { p...
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub fn PySlice_New(start: *mut PyObject, stop: *mut PyObject, step: *mut PyObject) -> *mut PyObject; pub fn PySlice_GetIndices(r: *mut PyObject, length: Py_ssize_t, start: *mut Py_ssize_t, stop: *mut ...
{ (Py_TYPE(op) == &mut PySlice_Type) as c_int }
identifier_body
sliceobject.rs
use libc::c_int; use pyport::Py_ssize_t;
static mut _Py_EllipsisObject: PyObject; } #[inline(always)] pub unsafe fn Py_Ellipsis() -> *mut PyObject { &mut _Py_EllipsisObject } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub static mut PySlice_Type: PyTypeObject; pub static mut PyEllipsis_Type: PyTypeObject; } #[inline(always)] p...
use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
random_line_split
svgcontext.ts
| number, minY?: number, width?: number, height?: number): void { if (typeof viewBox_or_minX === 'string') { this.svg.setAttribute('viewBox', viewBox_or_minX); } else { const viewBoxString = viewBox_or_minX + ' ' + minY + ' ' + width + ' ' + height; this.svg.setAttribute('viewBox', viewBoxStr...
{ return { x: 0, y: 0, width: 0, height: 0 } as SVGRect; }
conditional_block
svgcontext.ts
// ### Drawing helper methods: applyAttributes(element: SVGElement, attributes: Attributes): SVGElement { const attrNamesToIgnore = attrNamesToIgnoreMap[element.nodeName]; Object.keys(attributes).forEach((propertyName) => { if (attrNamesToIgnore && attrNamesToIgnore[propertyName]) { return; ...
this.svg.removeChild(txt); return bbox; }
random_line_split
svgcontext.ts
number): this { this.path += 'C' + x1 + ' ' + y1 + ',' + x2 + ' ' + y2 + ',' + x + ' ' + y; this.pen.x = x; this.pen.y = y; return this; } quadraticCurveTo(x1: number, y1: number, x: number, y: number): this { this.path += 'Q' + x1 + ' ' + y1 + ',' + x + ' ' + y; this.pen.x = x; this.p...
fillStyle
identifier_name
svgcontext.ts
avigator.userAgent) || /Trident/i.test(navigator.userAgent); } } // ### Styling & State Methods: setFont(family: string, size: number, weight: string): this { // In SVG italic is handled by font-style. // We search the weight argument and apply bold and italic // to font-weight and font-...
/** * @param blur A non-negative float specifying the level of shadow blur, where 0 * represents no blur and larger numbers represent increasingly more blur. * @returns this */ setShadowBlur(blur: number): this { this.shadow_attributes.width = blur; return this; } /** * @pa...
{ this.shadow_attributes.color = color; return this; }
identifier_body
from_repr.rs
use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::{Data, DeriveInput, PathArguments, Type, TypeParen}; use crate::helpers::{non_enum_error, HasStrumVariantProperties}; pub fn from_repr_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.g...
}; Ok(quote! { impl #impl_generics #name #ty_generics #where_clause { #vis #const_if_possible fn from_repr(discriminant: #discriminant_type) -> Option<#name #ty_generics> { #(#constant_defs)* match discriminant { #(#arms),* ...
#[rustversion::since(1.46)] fn filter_by_rust_version(s: TokenStream) -> TokenStream { s } filter_by_rust_version(quote! { const })
random_line_split
from_repr.rs
use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::{Data, DeriveInput, PathArguments, Type, TypeParen}; use crate::helpers::{non_enum_error, HasStrumVariantProperties}; pub fn
(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.generics; let (impl_generics, ty_generics, where_clause) = gen.split_for_impl(); let vis = &ast.vis; let attrs = &ast.attrs; let mut discriminant_type: Type = syn::parse("usize".parse().unwrap()).unwrap(); ...
from_repr_inner
identifier_name
from_repr.rs
use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::{Data, DeriveInput, PathArguments, Type, TypeParen}; use crate::helpers::{non_enum_error, HasStrumVariantProperties}; pub fn from_repr_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.g...
let typ_paren = match syn::parse2::<Type>(tokens.clone()) { Ok(Type::Paren(TypeParen { elem, .. })) => *elem, _ => continue, }; let inner_path = match &typ_paren { Type::Path(t) => t, _ => continue, }; if let Some(seg) = inner_path...
{ continue; }
conditional_block
from_repr.rs
use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::{Data, DeriveInput, PathArguments, Type, TypeParen}; use crate::helpers::{non_enum_error, HasStrumVariantProperties}; pub fn from_repr_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.g...
#[rustversion::since(1.46)] fn filter_by_rust_version(s: TokenStream) -> TokenStream { s } filter_by_rust_version(quote! { const }) }; Ok(quote! { impl #impl_generics #name #ty_generics #where_clause { #vis #const_if_possible fn from_repr(discri...
{ quote! {} }
identifier_body
context.ts
import { Observable, observable, watch } from "../core"; import { createOpType, createContainerOp, OpType, ContextOp, Op } from "./operations"; import { NodeFlags } from "./node_flags"; /** * Context descriptor. */ export interface ContextDescriptor<T = any> { /** * Retrieves context value. */ get(): T; ...
(c: ContextState | null): ContextState | null { return n = c; } /** * contextValue creates a context descriptor. * * @example * * const { set: StoreContext, get: getStore } = contextValue<Store>(); * const Component = component((c) => ( * () => getStore().value * )); * render( * ...
setContext
identifier_name
context.ts
import { Observable, observable, watch } from "../core"; import { createOpType, createContainerOp, OpType, ContextOp, Op } from "./operations"; import { NodeFlags } from "./node_flags"; /** * Context descriptor. */ export interface ContextDescriptor<T = any> { /** * Retrieves context value. */ get(): T; ...
} let next = n; while (next !== null) { if (next.d === d) { return watch(next.v); } next = next.n; } /* istanbul ignore else */ if (process.env.NODE_ENV !== "production") { throw Error("Unable to find context value"); } }, set...
{ throw Error("Invalid context invocation"); }
conditional_block
context.ts
import { Observable, observable, watch } from "../core"; import { createOpType, createContainerOp, OpType, ContextOp, Op } from "./operations"; import { NodeFlags } from "./node_flags"; /** * Context descriptor. */ export interface ContextDescriptor<T = any> { /** * Retrieves context value. */ get(): T; ...
/** * Disable checking for invalid `context()` invocations in DEBUG mode. */ export function disableContext() { contextEnabled = false; } /** * Reset current context. */ export function resetContext() { n = null; } /** * pushContext creates a new context state and pushes it to the context stack. * * @par...
{ contextEnabled = true; }
identifier_body
context.ts
import { Observable, observable, watch } from "../core"; import { createOpType, createContainerOp, OpType, ContextOp, Op } from "./operations"; import { NodeFlags } from "./node_flags"; /** * Context descriptor. */ export interface ContextDescriptor<T = any> { /** * Retrieves context value. */ get(): T; ...
/** * Disable checking for invalid `context()` invocations in DEBUG mode. */ export function disableContext() { contextEnabled = false; } /** * Reset current context. */ export function resetContext() { n = null; } /** * pushContext creates a new context state and pushes it to the context stack. * * @param...
random_line_split
conftest.py
import os import pytest from datetime import time from sport_systems import stats BASE_DIR = os.path.dirname(__file__) @pytest.fixture def response_1(): path = os.path.join(BASE_DIR, 'response-1.xml') with open(path, 'rb') as fin: data = fin.read() return data @pytest.fixture def
(): return [ stats.Result(time=time(1, 10, 15), name='foo'), stats.Result(time=time(1, 10, 20), name='foo'), stats.Result(time=time(1, 20), name='foo'), stats.Result(time=time(1, 30, 10), name='foo'), stats.Result(time=time(1, 30, 15), name='foo'), stats.Result(time=t...
results_1
identifier_name
conftest.py
import os import pytest from datetime import time from sport_systems import stats BASE_DIR = os.path.dirname(__file__) @pytest.fixture def response_1():
@pytest.fixture def results_1(): return [ stats.Result(time=time(1, 10, 15), name='foo'), stats.Result(time=time(1, 10, 20), name='foo'), stats.Result(time=time(1, 20), name='foo'), stats.Result(time=time(1, 30, 10), name='foo'), stats.Result(time=time(1, 30, 15), name='fo...
path = os.path.join(BASE_DIR, 'response-1.xml') with open(path, 'rb') as fin: data = fin.read() return data
identifier_body
templating.py
"""Templates module for Zinnia""" import os from django.template.defaultfilters import slugify def append_position(path, position, separator=''):
def loop_template_list(loop_positions, instance, instance_type, default_template, registry): """ Build a list of templates from a position within a loop and a registry of templates. """ templates = [] local_loop_position = loop_positions[1] global_loop_position = lo...
""" Concatenate a path and a position, between the filename and the extension. """ filename, extension = os.path.splitext(path) return ''.join([filename, separator, str(position), extension])
identifier_body
templating.py
"""Templates module for Zinnia""" import os from django.template.defaultfilters import slugify def append_position(path, position, separator=''): """ Concatenate a path and a position, between the filename and the extension. """ filename, extension = os.path.splitext(path) return ''.join([fil...
templates.append( append_position(default_template, global_loop_position, '-')) templates.append( append_position(default_template, local_loop_position, '_')) templates.append(default_template) return templates
try: templates.append(registry[key][global_loop_position]) except KeyError: pass
conditional_block
templating.py
"""Templates module for Zinnia""" import os from django.template.defaultfilters import slugify def append_position(path, position, separator=''): """ Concatenate a path and a position, between the filename and the extension. """ filename, extension = os.path.splitext(path) return ''.join([fil...
""" templates = [] local_loop_position = loop_positions[1] global_loop_position = loop_positions[0] instance_string = slugify(str(instance)) for key in ['%s-%s' % (instance_type, instance_string), instance_string, instance_type, 'default']: ...
and a registry of templates.
random_line_split
templating.py
"""Templates module for Zinnia""" import os from django.template.defaultfilters import slugify def append_position(path, position, separator=''): """ Concatenate a path and a position, between the filename and the extension. """ filename, extension = os.path.splitext(path) return ''.join([fil...
(loop_positions, instance, instance_type, default_template, registry): """ Build a list of templates from a position within a loop and a registry of templates. """ templates = [] local_loop_position = loop_positions[1] global_loop_position = loop_positions[0] insta...
loop_template_list
identifier_name
ddemo.py
"""Fake output as if code was typed in an interactive interpreter This is used to generate docs """ import ast import sys from pyterm import Term # copy from doit.action class Writer(object): """write to many streams""" def __init__(self, *writers): """@param writers - file stream like objects""" ...
(self, text): """write 'text' to all streams""" for stream in self.writers: stream.write(text) def flush(self): """flush all streams""" for stream in self.writers: stream.flush() def isatty(self): return self._isatty def fileno(self): ...
write
identifier_name
ddemo.py
"""Fake output as if code was typed in an interactive interpreter This is used to generate docs """ import ast import sys from pyterm import Term # copy from doit.action class Writer(object): """write to many streams""" def __init__(self, *writers): """@param writers - file stream like objects""" ...
def fileno(self): return 0 #return whatever # fake our sys.stdout to be always considered a tty new_out = Writer() new_out.add_writer(sys.stdout, isatty=True) sys.stdout = new_out source = open('tutorial.py').read() term = Term() block = [] for line in source.splitlines(): if block and (not line...
return self._isatty
identifier_body
ddemo.py
"""Fake output as if code was typed in an interactive interpreter This is used to generate docs """ import ast import sys from pyterm import Term # copy from doit.action class Writer(object): """write to many streams""" def __init__(self, *writers): """@param writers - file stream like objects""" ...
for writer in writers: self.add_writer(writer) def add_writer(self, stream, isatty=None): """adds a stream to the list of writers @param isatty: (bool) if specified overwrites real isatty from stream """ self.writers.append(stream) isatty = stream.isatty(...
self._isatty = True
random_line_split
ddemo.py
"""Fake output as if code was typed in an interactive interpreter This is used to generate docs """ import ast import sys from pyterm import Term # copy from doit.action class Writer(object): """write to many streams""" def __init__(self, *writers): """@param writers - file stream like objects""" ...
def add_writer(self, stream, isatty=None): """adds a stream to the list of writers @param isatty: (bool) if specified overwrites real isatty from stream """ self.writers.append(stream) isatty = stream.isatty() if (isatty is None) else isatty self._isatty = self._isa...
self.add_writer(writer)
conditional_block
negative.js
var fixed = Traverse.map(obj, function (x) { if (x < 0) this.update(x + 128); }); assert.deepEqual(fixed, [ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ], 'Negative values += 128' ); assert.deepEqual(obj, [ 5, 6, -3, [ 7, 8, -2, 1 ], { f: 10, g: -13 } ], ...
var Traverse = require('.'); var assert = require('assert'); exports['negative update test'] = function () { var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];
random_line_split
build_model.py
import sys import os import json from optparse import OptionParser from tornado.template import Template from build_template import * from build_config import * def get_allow_empty_fields(fields_config, unhandled_fields): allow_empty_fields = unhandled_fields for field in fields_config:
return allow_empty_fields def get_like_fields(fields_config): like_fields = [] for field in fields_config: if field["fieldMode"] == "primaryKey": continue if 'more' not in field: continue more = field['more'] if 'search' in more and more['search'] ==...
if field["fieldMode"] == "primaryKey": continue if 'required' in field and field['required'] == "0": allow_empty_fields.append(field['fieldName'])
conditional_block
build_model.py
import sys import os import json from optparse import OptionParser from tornado.template import Template from build_template import * from build_config import * def get_allow_empty_fields(fields_config, unhandled_fields): allow_empty_fields = unhandled_fields for field in fields_config: if field["fiel...
if __name__ == '__main__': config = load_config() build_model_by_config(config)
fn = build_model(config, 'AbBaseModel') return fn
identifier_body
build_model.py
import sys import os import json from optparse import OptionParser from tornado.template import Template from build_template import * from build_config import * def get_allow_empty_fields(fields_config, unhandled_fields): allow_empty_fields = unhandled_fields for field in fields_config: if field["fiel...
(config): fn = build_model(config, 'AbBaseModel') return fn if __name__ == '__main__': config = load_config() build_model_by_config(config)
build_model_by_config
identifier_name
build_model.py
import sys import os import json from optparse import OptionParser from tornado.template import Template from build_template import * from build_config import * def get_allow_empty_fields(fields_config, unhandled_fields): allow_empty_fields = unhandled_fields for field in fields_config: if field["field...
d = init_dict() d['model_name'] = config['module_name'] d['module_name'] = config['module_name'] d['base_model_name'] = base_model_name d['table_name'] = config['table_name'] d['primary_key'] = model['info']['PrimaryKey'] d['fields_info'] = list(filter(lambda x: x['fieldName'] != '', fields...
unhandled_fields = model['info']['UnhandledFields']
random_line_split
conf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # HobsonPy documentation build configuration file, created by # sphinx-quickstart on Sat Sep 16 18:59:19 2017. # # 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 # a...
master_doc = 'index' # General information about the project. project = 'HobsonPy' copyright = '2017, Al Sweigart' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. ve...
# The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document.
random_line_split
career.js
import { combineReducers } from 'redux'; import { ADDED_ACCEPTOR_CAREER, DELETED_ACCEPTOR_CAREER, INIT_ACCEPTOR_CAREER_HISTORY, FETCH_FAILED, FETCHING } from '../../constants'; const error = (state = null, action) => { switch (action.type) { case FETCH_FAILED: return action.error; default: ...
const data = (state = [], action) => { switch (action.type) { case INIT_ACCEPTOR_CAREER_HISTORY: return action.careerHistory; case ADDED_ACCEPTOR_CAREER: return [...state, action.career]; case DELETED_ACCEPTOR_CAREER: return state.filter(({ name, year }) => name !== action.career...
random_line_split
lib.rs
. // // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Terminal f...
#[cfg(not(windows))] /// Return a Terminal wrapping stderr, or None if a terminal couldn't be /// opened. pub fn stderr() -> Option<Box<StderrTerminal>> { TerminfoTerminal::new(io::stderr()).map(|t| { Box::new(t) as Box<StderrTerminal> }) } #[cfg(windows)] /// Return a Terminal wrapping stderr, or No...
{ TerminfoTerminal::new(io::stdout()).map(|t| { Box::new(t) as Box<StdoutTerminal> }).or_else(|| WinConsole::new(io::stdout()).ok().map(|t| { Box::new(t) as Box<StdoutTerminal> })) }
identifier_body
lib.rs
. // // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Terminal f...
{ /// Bold (or possibly bright) mode Bold, /// Dim mode, also called faint or half-bright. Often not supported Dim, /// Italics mode. Often not supported Italic(bool), /// Underline mode Underline(bool), /// Blink mode Blink, /// Standout mode. Often implemented as Reverse, ...
Attr
identifier_name
lib.rs
.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Terminal formatting library. //! //! This crate provides the `...
/// Moves the cursor to the left edge of the current line. /// /// Returns `Ok(true)` if the text was deleted, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn carriage_return(&mut self) -> io::Result<bool>;
random_line_split
htmlPageContent.py
dd>Добавлен проект закона о бюджете на 2015 г.</dd>" "</dl>" ).ref+"</p>\n") yearLaws=collections.defaultdict(list) yearExtracted=collections.defaultdict(bool) for law in env.laws: yearLaws[law.year].append(law) if law.documents: yearExtracted[law.year]=True w("<p>Документы для годов: ") wn=no...
conditional_block
htmlPageContent.py
def makeContent(env=None,linksToDocumentCopies=False): if env is None: import main env=main.Environment(main.loadData()) def content(makeFns): w,nonFirstWrite,wtd,wtdrowspan,e,a,af,ae=makeFns('w,nonFirstWrite,wtd,wtdrowspan,e,a,af,ae') refs=Refs() w("<h1>Ведомственная структура расходов бюджета Санкт-Пе...
ref=self.__class__.Ref(len(self.refs)+1,html) self.refs.append(ref) return ref
identifier_body
htmlPageContent.py
: class Ref: def __init__(self,number,html): self.number=number self.html=html @property def id(self): return "ref-"+str(self.number) @property def ref(self): return "<sup><a href='#"+self.id+"'>["+str(self.number)+"]</a></sup>" @property def body(self): return "<div id='"+self.id+"'>"+sel...
Refs
identifier_name
htmlPageContent.py
а Санкт-Петербурга</h1>\n") abbrXls="<abbr title='Excel Binary File Format, бинарный формат файлов Excel'>xls</abbr>" abbrPdf="<abbr title='Portable Document Format'>pdf</abbr>" abbrCsv="<abbr title='comma-separated values, значения, разделённые запятыми'>csv</abbr>" abbrUtf8="<abbr title='Unicode Transformati...
refCsv=refs.makeRef("В кодировке "+abbrUtf8+". Числа с десятичной запятой, потому что в таком формате их читают русские версии электронных таблиц.") w("<table>\n") w("<thead>\n") w("<tr><th rowspan='2'>год</th><th rowspan='2'>закон</th><th rowspan='2'>исходные документы"+refs.makeRef( "Наличие ссылок на архи...
)
random_line_split
external_sort_text_agg.js
// Ensure text search metadata is not lost in an external sort var t = db.external_sort_text_agg; t.drop(); t.ensureIndex({text: "text"}); for (i = 0; i < 100; i++) { t.insert({_id: i, text: Array(210000).join("asdf ")}); // string over 1MB to hit the 100MB threshold for external sort } var score = t.find({$te...
assert.eq(res.next().score, score);
{allowDiskUse: true}); // we must use .next() rather than a $limit because a $limit will optimize away the external sort printjson(res.next());
random_line_split
external_sort_text_agg.js
// Ensure text search metadata is not lost in an external sort var t = db.external_sort_text_agg; t.drop(); t.ensureIndex({text: "text"}); for (i = 0; i < 100; i++)
var score = t.find({$text: {$search: "asdf"}}, {score: {$meta: 'textScore'}}).next().score; var res = t.aggregate( [ {$match: {$text: {$search: "asdf"}}}, {$sort: {"_id": 1}}, {$project: {string: "$text", score: {$meta: "textScore"}}} ], {allowDiskUse: true}); // we must use .next() rath...
{ t.insert({_id: i, text: Array(210000).join("asdf ")}); // string over 1MB to hit the 100MB threshold for external sort }
conditional_block
p017.rs
use solutions::Solution; pub fn solve() -> Solution { let mut sum = 0; for n in 1..1001 { sum += wordify(n).len(); } Solution::new(&format!("{}", sum)) } /// Turns the given number (in the range [1,1000]) into a string with no spaces or dashes fn wordify(n: usize) -> String { let numbers =...
if n % 100 < 20 { s += numbers[n % 100]; n /= 100; } else { // Otherwise, the construction of numbers is regular s += numbers[n % 10]; n /= 10; s = tens[n % 10].to_string() + &s; n /= 10; } if n != 0 { // Add "and" between hundreds and what...
// Need to account for special number names below 20
random_line_split
p017.rs
use solutions::Solution; pub fn solve() -> Solution { let mut sum = 0; for n in 1..1001 { sum += wordify(n).len(); } Solution::new(&format!("{}", sum)) } /// Turns the given number (in the range [1,1000]) into a string with no spaces or dashes fn wordify(n: usize) -> String { let numbers =...
let mut n = n; let mut s = String::new(); // Need to account for special number names below 20 if n % 100 < 20 { s += numbers[n % 100]; n /= 100; } else { // Otherwise, the construction of numbers is regular s += numbers[n % 10]; n /= 10; s = tens[n...
{ return "onethousand".to_string(); }
conditional_block
p017.rs
use solutions::Solution; pub fn solve() -> Solution { let mut sum = 0; for n in 1..1001 { sum += wordify(n).len(); } Solution::new(&format!("{}", sum)) } /// Turns the given number (in the range [1,1000]) into a string with no spaces or dashes fn
(n: usize) -> String { let numbers = vec!["", "one", "two", "three", "four", "five", "six", "seven", "eight", ...
wordify
identifier_name
p017.rs
use solutions::Solution; pub fn solve() -> Solution
/// Turns the given number (in the range [1,1000]) into a string with no spaces or dashes fn wordify(n: usize) -> String { let numbers = vec!["", "one", "two", "three", "four", "five", ...
{ let mut sum = 0; for n in 1..1001 { sum += wordify(n).len(); } Solution::new(&format!("{}", sum)) }
identifier_body
index.js
'use strict'; // MODULES // var isNumber = require( 'validate.io-number-primitive' ), isArrayLike = require( 'validate.io-array-like' ), isTypedArrayLike = require( 'validate.io-typed-array-like' ), isMatrixLike = require( 'validate.io-matrix-like' ), ctors = require( 'compute-array-constructors' ), matrix = req...
var opts = {}, ctor, err, out, dt, d; if ( arguments.length > 1 ) { err = validate( opts, options ); if ( err ) { throw err; } } opts.mu = typeof opts.mu !== 'undefined' ? opts.mu : 0; opts.b = typeof opts.b !== 'undefined' ? opts.b : 1; if ( isNumber( x ) ) { return pdf1( x, opts.mu, opts....
/* jshint newcap:false */
random_line_split
index.js
'use strict'; // MODULES // var isNumber = require( 'validate.io-number-primitive' ), isArrayLike = require( 'validate.io-array-like' ), isTypedArrayLike = require( 'validate.io-typed-array-like' ), isMatrixLike = require( 'validate.io-matrix-like' ), ctors = require( 'compute-array-constructors' ), matrix = req...
( x, options ) { /* jshint newcap:false */ var opts = {}, ctor, err, out, dt, d; if ( arguments.length > 1 ) { err = validate( opts, options ); if ( err ) { throw err; } } opts.mu = typeof opts.mu !== 'undefined' ? opts.mu : 0; opts.b = typeof opts.b !== 'undefined' ? opts.b : 1; if ( isNumb...
pdf
identifier_name
index.js
'use strict'; // MODULES // var isNumber = require( 'validate.io-number-primitive' ), isArrayLike = require( 'validate.io-array-like' ), isTypedArrayLike = require( 'validate.io-typed-array-like' ), isMatrixLike = require( 'validate.io-matrix-like' ), ctors = require( 'compute-array-constructors' ), matrix = req...
} if ( isMatrixLike( x ) ) { if ( opts.copy !== false ) { dt = opts.dtype || 'float64'; ctor = ctors( dt ); if ( ctor === null ) { throw new Error( 'pdf()::invalid option. Data type option does not have a corresponding array constructor. Option: `' + dt + '`.' ); } // Create an output matrix: ...
{ /* jshint newcap:false */ var opts = {}, ctor, err, out, dt, d; if ( arguments.length > 1 ) { err = validate( opts, options ); if ( err ) { throw err; } } opts.mu = typeof opts.mu !== 'undefined' ? opts.mu : 0; opts.b = typeof opts.b !== 'undefined' ? opts.b : 1; if ( isNumber( x ) ) { r...
identifier_body
editSpecification_job_parameters.js
<!-- 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 (the "License"); you may not use ...
} function s${SEQNUM}_deleteFieldMapping(i) { // Set the operation eval("editjob.s${SEQNUM}_fieldmapping_op_"+i+".value=\"Delete\""); // Submit if (editjob.s${SEQNUM}_fieldmapping_count.value==i) postFormSetAnchor("s${SEQNUM}_fieldmapping"); else postFormSetAnchor("s${SEQNUM}_fieldmapping_"+i) // U...
postFormSetAnchor("s${SEQNUM}_fieldmapping");
random_line_split
editSpecification_job_parameters.js
<!-- 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 (the "License"); you may not use ...
("$Encoder.bodyEscape($ResourceBundle.getString('SolrIngester.NoFieldNameSpecified'))"); editjob.s${SEQNUM}_fieldmapping_source.focus(); return; } editjob.s${SEQNUM}_fieldmapping_op.value="Add"; postFormSetAnchor("s${SEQNUM}_fieldmapping"); } function s${SEQNUM}_deleteFieldMapping(i) { // Set the opera...
alert
identifier_name
editSpecification_job_parameters.js
<!-- 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 (the "License"); you may not use ...
editjob.s${SEQNUM}_fieldmapping_op.value="Add"; postFormSetAnchor("s${SEQNUM}_fieldmapping"); } function s${SEQNUM}_deleteFieldMapping(i) { // Set the operation eval("editjob.s${SEQNUM}_fieldmapping_op_"+i+".value=\"Delete\""); // Submit if (editjob.s${SEQNUM}_fieldmapping_count.value==i) postFormSetA...
{SEQNUM}_fieldmapping_source.focus(); return; }
identifier_body
editSpecification_job_parameters.js
<!-- 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 (the "License"); you may not use ...
_fieldmapping_source.value == "") { alert("$Encoder.bodyEscape($ResourceBundle.getString('SolrIngester.NoFieldNameSpecified'))"); editjob.s${SEQNUM}_fieldmapping_source.focus(); return; } editjob.s${SEQNUM}_fieldmapping_op.value="Add"; postFormSetAnchor("s${SEQNUM}_fieldmapping"); } function s${SEQ...
{SEQNUM}
conditional_block
lib.rs
#[feature(macro_rules)]; #[crate_id = "diagrus#0.1"]; #[crate_type = "lib"]; #[crate_type = "dylib"]; #[comment = "Utilities to make using JSON easier"]; #[license = "MIT"]; extern mod extra; use std::fmt; pub use self::fromjson::FromJson; pub use self::jsonutil::JsonLike; pub mod macros; pub mod jsonutil;
pub enum ErrorTy { Conversion, Value } /// These error codes describe the actual error specifically. #[deriving(Clone, Encodable, Decodable, Eq, ToStr)] pub enum ErrorCode { NotString, NotNumber, NotInteger, NotBoolean, NotList, NotObject, NotEither, NoSuchKey, IdxOutOfBound...
pub mod fromjson; /// This enum indicates if the error is due to a conversion failure, /// or from mishandling the JSON value #[deriving(Clone, Encodable, Decodable, Eq, ToStr)]
random_line_split
lib.rs
#[feature(macro_rules)]; #[crate_id = "diagrus#0.1"]; #[crate_type = "lib"]; #[crate_type = "dylib"]; #[comment = "Utilities to make using JSON easier"]; #[license = "MIT"]; extern mod extra; use std::fmt; pub use self::fromjson::FromJson; pub use self::jsonutil::JsonLike; pub mod macros; pub mod jsonutil; pub mod...
} impl ToStr for Error { fn to_str(&self) -> ~str { format!("{}", *self) } } /// Convenience function for errors fn error<T>(ty: ErrorTy, code: ErrorCode) -> Result<T, Error> { Err(Error::new(ty, code)) }
{ let msg = match e.code { NotString => ~"Not a JSON string", NotNumber => ~"Not a JSON number", NotInteger => ~"JSON number is not an integer", NotBoolean => ~"Not a JSON boolean", NotList => ~"Not a JSON list", NotObject => ~"Not a JSON O...
identifier_body
lib.rs
#[feature(macro_rules)]; #[crate_id = "diagrus#0.1"]; #[crate_type = "lib"]; #[crate_type = "dylib"]; #[comment = "Utilities to make using JSON easier"]; #[license = "MIT"]; extern mod extra; use std::fmt; pub use self::fromjson::FromJson; pub use self::jsonutil::JsonLike; pub mod macros; pub mod jsonutil; pub mod...
{ /// Error category category: ErrorTy, /// Code indicating the specific error. code: ErrorCode } impl Error { pub fn new(ty: ErrorTy, code: ErrorCode) -> Error { Error { category: ty, code: code } } } impl fmt::Default for Error { fn fmt(e: &Error, f: &mut fmt::Formatter) { ...
Error
identifier_name
test_namedict.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "...
self.ndict['foo'] = 100 self.failUnlessRaises(ValueError, bad) def testRelDepth(self): self.failUnless(self.rndict.max_depth == 2) def testRelLookup1(self): k = dns.name.from_text('foo.bar', None) self.failUnless(self.rndict[k] == 1) def testRelLookup2(self): ...
self.failUnless(v == 100) def testLookup8(self): def bad():
random_line_split
test_namedict.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "...
def testLookup6(self): def bad(): (k, v) = self.ndict.get_deepest_match(dns.name.empty) self.failUnlessRaises(KeyError, bad) def testLookup7(self): self.ndict[dns.name.empty] = 100 n = dns.name.from_text('a.b.c.') (k, v) = self.ndict.get_deepest_match(n) ...
def bad(): n = dns.name.from_text('a.b.c.') (k, v) = self.ndict.get_deepest_match(n) self.failUnlessRaises(KeyError, bad)
identifier_body
test_namedict.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "...
(self): self.ndict[dns.name.empty] = 100 n = dns.name.from_text('a.b.c.') (k, v) = self.ndict.get_deepest_match(n) self.failUnless(v == 100) def testLookup8(self): def bad(): self.ndict['foo'] = 100 self.failUnlessRaises(ValueError, bad) def testRelD...
testLookup7
identifier_name
test_namedict.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "...
unittest.main()
conditional_block
problem-036.py
problem = """ The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) """ def is_palindromic(s): return ...
print sum(double_base_palindromes)
random_line_split
problem-036.py
problem = """ The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) """ def is_palindromic(s): return ...
double_base_palindromes = set() for num in range(1000): p1 = int(str(num) + str(num)[-2::-1]) p2 = int(str(num) + str(num)[::-1]) if is_palindromic(decimal2binary(p1)): double_base_palindromes.add(p1) if is_palindromic(decimal2binary(p2)): double_base_palindromes.add(p2) print sum(do...
x = '' while num > 0: x = str(num % 2) + x num /= 2 return x
identifier_body
problem-036.py
problem = """ The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) """ def
(s): return s[:len(s)/2] == s[:(len(s)-1)/2:-1] def decimal2binary(num): x = '' while num > 0: x = str(num % 2) + x num /= 2 return x double_base_palindromes = set() for num in range(1000): p1 = int(str(num) + str(num)[-2::-1]) p2 = int(str(num) + str(num)[::-1]) if is_pal...
is_palindromic
identifier_name
problem-036.py
problem = """ The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) """ def is_palindromic(s): return ...
return x double_base_palindromes = set() for num in range(1000): p1 = int(str(num) + str(num)[-2::-1]) p2 = int(str(num) + str(num)[::-1]) if is_palindromic(decimal2binary(p1)): double_base_palindromes.add(p1) if is_palindromic(decimal2binary(p2)): double_base_palindromes.add(p2) ...
x = str(num % 2) + x num /= 2
conditional_block
app.js
'use strict'; angular
'ngAnimate', 'animatedBirdsDirective', 'scrollAnimDirective', 'swfTemplateDirective' ]) .config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' }) .when('/about', { templat...
.module('personalWebsiteApp', [ 'ngResource', 'ngRoute',
random_line_split
allow.rs
use method::Method; header! { #[doc="`Allow` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.4.1)"] #[doc=""] #[doc="The `Allow` header field lists the set of methods advertised as"] #[doc="supported by the target resource. The purpose of this field is"] #[doc="strictly t...
bench_header!(bench, Allow, { vec![b"OPTIONS,GET,PUT,POST,DELETE,HEAD,TRACE,CONNECT,PATCH,fOObAr".to_vec()] });
random_line_split
test_shred.rs
use crate::common::util::*; #[test] fn
() { let scene = TestScenario::new(util_name!()); let at = &scene.fixtures; let file_a = "test_shred_remove_a"; let file_b = "test_shred_remove_b"; // Create file_a and file_b. at.touch(file_a); at.touch(file_b); // Shred file_a. scene.ucmd().arg("-u").arg(file_a).run(); // f...
test_shred_remove
identifier_name
test_shred.rs
use crate::common::util::*; #[test] fn test_shred_remove() { let scene = TestScenario::new(util_name!()); let at = &scene.fixtures; let file_a = "test_shred_remove_a"; let file_b = "test_shred_remove_b"; // Create file_a and file_b. at.touch(file_a); at.touch(file_b); // Shred file_a...
let file = "test_shred_force"; // Create file_a. at.touch(file); assert!(at.file_exists(file)); // Make file_a readonly. at.set_readonly(file); // Try shred -u. scene.ucmd().arg("-u").arg(file).run(); // file_a was not deleted because it is readonly. assert!(at.file_exists(fi...
fn test_shred_force() { let scene = TestScenario::new(util_name!()); let at = &scene.fixtures;
random_line_split
test_shred.rs
use crate::common::util::*; #[test] fn test_shred_remove()
#[cfg(not(target_os = "freebsd"))] #[test] fn test_shred_force() { let scene = TestScenario::new(util_name!()); let at = &scene.fixtures; let file = "test_shred_force"; // Create file_a. at.touch(file); assert!(at.file_exists(file)); // Make file_a readonly. at.set_readonly(file); ...
{ let scene = TestScenario::new(util_name!()); let at = &scene.fixtures; let file_a = "test_shred_remove_a"; let file_b = "test_shred_remove_b"; // Create file_a and file_b. at.touch(file_a); at.touch(file_b); // Shred file_a. scene.ucmd().arg("-u").arg(file_a).run(); // file...
identifier_body
utils.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 from rapidsms.utils.modules import try_import from .forms import LocationForm from .models import Location def get_model(name): """ """ for type in Location.subclasses(): if type._meta.module_name == name: return type raise Sta...
(model): """ Return the Form which should be used to add/edit ``model`` in the WebUI, by importing the class named ``"%sForm" % model.__name__`` from the sibling ``forms`` module. For example:: app1.models.Alpha -> myapp.forms.SchoolForm app2.models.beta.Beta -> app2.forms.beta.Beta...
form_for_model
identifier_name
utils.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 from rapidsms.utils.modules import try_import from .forms import LocationForm from .models import Location def get_model(name): """ """ for type in Location.subclasses():
raise StandardError("There is no Location subclass named '%s'" % name) def form_for_model(model): """ Return the Form which should be used to add/edit ``model`` in the WebUI, by importing the class named ``"%sForm" % model.__name__`` from the sibling ``forms`` module. For example:: app1...
if type._meta.module_name == name: return type
conditional_block
utils.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 from rapidsms.utils.modules import try_import from .forms import LocationForm from .models import Location def get_model(name): """ """ for type in Location.subclasses(): if type._meta.module_name == name: return type raise Sta...
form = getattr(module, form_name, None) if form is not None: return form meta_dict = LocationForm.Meta.__dict__ meta_dict["model"] = model return type( form_name, (LocationForm,), { "Meta": type("Meta", (), meta_dict) } )
""" Return the Form which should be used to add/edit ``model`` in the WebUI, by importing the class named ``"%sForm" % model.__name__`` from the sibling ``forms`` module. For example:: app1.models.Alpha -> myapp.forms.SchoolForm app2.models.beta.Beta -> app2.forms.beta.BetaForm If ...
identifier_body
utils.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 from rapidsms.utils.modules import try_import from .forms import LocationForm from .models import Location def get_model(name): """ """ for type in Location.subclasses(): if type._meta.module_name == name: return type raise Sta...
form = getattr(module, form_name, None) if form is not None: return form meta_dict = LocationForm.Meta.__dict__ meta_dict["model"] = model return type( form_name, (LocationForm,), { "Meta": type("Meta", (), meta_dict) } )
module = try_import(module_name) if module is not None:
random_line_split
plugit_tags.py
from django import template from django.template.base import Node, Template, TemplateSyntaxError from django.conf import settings register = template.Library() class PlugItIncludeNode(Node): def __init__(self, action): self.action = action def render(self, context): action = self.action.reso...
return text.replace('<a ', '<a target="_blank" ')
identifier_body
plugit_tags.py
from django import template from django.template.base import Node, Template, TemplateSyntaxError from django.conf import settings register = template.Library() class PlugItIncludeNode(Node): def __init__(self, action): self.action = action def
(self, context): action = self.action.resolve(context) # Load plugIt object if settings.PIAPI_STANDALONE: # Import objects form the view from plugit_proxy.views import plugIt, baseURI else: # Import object using the function in the view fr...
render
identifier_name
plugit_tags.py
from django import template from django.template.base import Node, Template, TemplateSyntaxError from django.conf import settings register = template.Library() class PlugItIncludeNode(Node): def __init__(self, action): self.action = action def render(self, context): action = self.action.reso...
action = parser.compile_filter(bits[1]) return PlugItIncludeNode(action) @register.assignment_tag def plugitGetUser(pk): if settings.PIAPI_STANDALONE: from plugit_proxy.views import generate_user user = generate_user(pk=str(pk)) else: from users.models import TechUser ...
raise TemplateSyntaxError("'plugitInclude' tag takes one argument: the tempalte's action to use")
conditional_block
plugit_tags.py
from django import template from django.template.base import Node, Template, TemplateSyntaxError from django.conf import settings register = template.Library()
class PlugItIncludeNode(Node): def __init__(self, action): self.action = action def render(self, context): action = self.action.resolve(context) # Load plugIt object if settings.PIAPI_STANDALONE: # Import objects form the view from plugit_proxy.views im...
random_line_split
search_source.js
of where filters come from for when they are saved back to * the savedObject store in the Kibana index. To do this, we create trees of searchSource objects * that can have associated query parameters (index, query, filter, etc) which can also inherit from * other searchSource objects. * * At query time, all of th...
*****/ /** * List of the editable state properties that turn into a * chainable API * * @type {Array} */ SearchSource.prototype._methods = [ 'type', 'query', 'filter', 'sort', 'highlight', 'highlightAll', 'aggs', 'from', 'size', 'source' ]; SearchSourc...
/***** * PUBLIC API
random_line_split
search_source.js
where filters come from for when they are saved back to * the savedObject store in the Kibana index. To do this, we create trees of searchSource objects * that can have associated query parameters (index, query, filter, etc) which can also inherit from * other searchSource objects. * * At query time, all of the s...
// user a shallow flatten to detect if val is an array, and pull the values out if it is state.filters = _([ state.filters || [], verifiedFilters ]) .flatten() // Yo Dawg! I heard you needed to filter out your filters .reject(function (filter) { return !filter || _.get...
{ if (!_.isArray(val)) val = [val]; verifiedFilters = val.filter(function (el) { if ('meta' in el && 'index' in state) { const field = state.index.fields.byName[el.meta.key]; if (!field) return false; } return true; }); ...
conditional_block
search_source.js
of where filters come from for when they are saved back to * the savedObject store in the Kibana index. To do this, we create trees of searchSource objects * that can have associated query parameters (index, query, filter, etc) which can also inherit from * other searchSource objects. * * At query time, all of th...
*****/ /** * List of the editable state properties that turn into a * chainable API * * @type {Array} */ SearchSource.prototype._methods = [ 'type', 'query', 'filter', 'sort', 'highlight', 'highlightAll', 'aggs', 'from', 'size', 'source' ]; SearchSourc...
{ const SourceAbstract = Private(AbstractDataSourceProvider); const SearchRequest = Private(SearchRequestProvider); const SegmentedRequest = Private(SegmentedRequestProvider); const searchStrategy = Private(SearchStrategyProvider); const normalizeSortRequest = Private(NormalizeSortRequestProvider); const f...
identifier_body
search_source.js
, etc) which can also inherit from * other searchSource objects. * * At query time, all of the searchSource objects that have subscribers are "flattened", at which * point the query params from the searchSource are collected while traversing up the inheritance * chain. At each link in the chain a decision about ho...
addToBody
identifier_name
parityClient.js
address": "00a329c0648769a73afac7f9381e08fb43dbea72", "name": "Development Account", "meta": "{\"description\":\"Never use this account outside of development chain!\",\"passwordHint\":\"Password is empty string\"}" } }; const safePush = function (set, value) { if (set.indexOf(value) === -1) { set.push...
mainCommand
identifier_name
parityClient.js
bd1bd288f9d1ed14edf61aa68fc518093f97c791cf719", "kdf": "pbkdf2", "kdfparams": {"c": 10240, "dklen": 32, "prf": "hmac-sha256", "salt": "73b74e437a1144eb9a775e196f450a23ab415ce2c17083c225ddbb725f279b98"}, "mac": "f5882ae121e4597bd133136bf15dcbcc1bb2417a25ad205041a50c59def812a8" }, "address": "00...
v = `${v.major}.${v.minor}.${v.patch}`; test = semver.Range(this.versSupported).test(semver(v)); if (typeof test !== 'boolean') { test = undefined; } } finally { // eslint-disable-next-line no-unsafe-finally return test; } } determineNetworkType(config) { if ...
let test; try { let v = semver(parsedVersion);
random_line_split
parityClient.js
1bd288f9d1ed14edf61aa68fc518093f97c791cf719", "kdf": "pbkdf2", "kdfparams": {"c": 10240, "dklen": 32, "prf": "hmac-sha256", "salt": "73b74e437a1144eb9a775e196f450a23ab415ce2c17083c225ddbb725f279b98"}, "mac": "f5882ae121e4597bd133136bf15dcbcc1bb2417a25ad205041a50c59def812a8" }, "address": "00a3...
if (config.syncMode === 'light') { cmd.push("--light"); } else if (config.syncMode === 'fast') { cmd.push("--pruning=fast"); } else if (config.syncMode === 'full') { cmd.push("--pruning=archive"); } // In dev mode we store all users passwords in the devPassword file, so Parity c...
{ cmd.push(`--base-path=${config.datadir}`); }
conditional_block
parityClient.js
1bd288f9d1ed14edf61aa68fc518093f97c791cf719", "kdf": "pbkdf2", "kdfparams": {"c": 10240, "dklen": 32, "prf": "hmac-sha256", "salt": "73b74e437a1144eb9a775e196f450a23ab415ce2c17083c225ddbb725f279b98"}, "mac": "f5882ae121e4597bd133136bf15dcbcc1bb2417a25ad205041a50c59def812a8" }, "address": "00a3...
listAccountsCommand() { return this.bin + " " + this.commonOptions().join(' ') + " account list "; } parseListAccountsCommandResultToAddress(data = "") { return data.replace(/^\n|\n$/g, "").split('\n')[0]; } parseListAccountsCommandResultToAddressList(data = "") { const list = data.split('\n')...
{ return data.replace(/^\n|\n$/g, ""); }
identifier_body
BasicFormType.ts
import {TransformManager} from "../../coreBundle/transformer/TransformManager"; import {FormGroup, FormControl} from "@angular/forms"; import {TransformableInterface} from "../../coreBundle/transformer/common"; import {FunctionTransformer} from "../../coreBundle/transformer/FunctionTransformer"; import * as _ from "lod...
let tm = new TransformManager(); let fromFormGroupTransformer = new ChainTransformer([ new FunctionTransformer((form:FormGroup)=> { return form.getRawValue(); }), new ToTypeTransformer<T>(this.TCreator) ]); return tm.createData<T>(this._formGroup, fromFormGroupTransformer, ...
{ throw new Error('Form is not valid'); }
conditional_block
BasicFormType.ts
import {TransformManager} from "../../coreBundle/transformer/TransformManager"; import {FormGroup, FormControl} from "@angular/forms"; import {TransformableInterface} from "../../coreBundle/transformer/common"; import {FunctionTransformer} from "../../coreBundle/transformer/FunctionTransformer"; import * as _ from "lod...
buildForm(data:any, options?:any): FormGroup{ let controls:any = {}; let validators = getValidatorDecoratorConfiguration(this.TCreator, this.name); let validatorsAsync = getValidatorAsyncDecoratorConfiguration(this.TCreator, this.name); let fields:string[] = _.uniq(Object.keys(data).concat(this.f...
{ }
identifier_body
BasicFormType.ts
import {TransformManager} from "../../coreBundle/transformer/TransformManager"; import {FormGroup, FormControl} from "@angular/forms"; import {TransformableInterface} from "../../coreBundle/transformer/common"; import {FunctionTransformer} from "../../coreBundle/transformer/FunctionTransformer"; import * as _ from "lod...
(private TCreator: { new (): T; }, public fields:string[]=[]) { } buildForm(data:any, options?:any): FormGroup{ let controls:any = {}; let validators = getValidatorDecoratorConfiguration(this.TCreator, this.name); let validatorsAsync = getValidatorAsyncDecoratorConfiguration(this.TCreator, this.name)...
constructor
identifier_name
BasicFormType.ts
import {TransformManager} from "../../coreBundle/transformer/TransformManager"; import {FormGroup, FormControl} from "@angular/forms"; import {TransformableInterface} from "../../coreBundle/transformer/common"; import {FunctionTransformer} from "../../coreBundle/transformer/FunctionTransformer"; import * as _ from "lod...
constructor(private TCreator: { new (): T; }, public fields:string[]=[]) { } buildForm(data:any, options?:any): FormGroup{ let controls:any = {}; let validators = getValidatorDecoratorConfiguration(this.TCreator, this.name); let validatorsAsync = getValidatorAsyncDecoratorConfiguration(this.TCreato...
random_line_split
test_lmdb_utils.py
''' Created on Jan 06, 2016 @author: kashefy ''' from nose.tools import assert_greater, assert_equal, assert_is_instance, assert_true import nideep.iow.lmdb_utils as lu class TestLMDBConsts: def test_map_sz(self):
def test_num_idx_digits(self): assert_greater(lu.NUM_IDX_DIGITS, 0) assert_is_instance(lu.NUM_IDX_DIGITS, int) class TestIdxFormat: def test_idx_format(self): assert_greater(len(lu.IDX_FMT), 0) assert_is_instance(lu.IDX_FMT, str) assert_true(lu.IDX_FMT.startswith('{...
assert_greater(lu.MAP_SZ, 0) assert_is_instance(lu.MAP_SZ, int)
identifier_body
test_lmdb_utils.py
''' Created on Jan 06, 2016 @author: kashefy ''' from nose.tools import assert_greater, assert_equal, assert_is_instance, assert_true import nideep.iow.lmdb_utils as lu class TestLMDBConsts: def test_map_sz(self): assert_greater(lu.MAP_SZ, 0) assert_is_instance(lu.MAP_SZ, int) def test_num_...
assert_equal(lu.IDX_FMT.format(i), s[:-2] + '%d' % i)
random_line_split
test_lmdb_utils.py
''' Created on Jan 06, 2016 @author: kashefy ''' from nose.tools import assert_greater, assert_equal, assert_is_instance, assert_true import nideep.iow.lmdb_utils as lu class TestLMDBConsts: def test_map_sz(self): assert_greater(lu.MAP_SZ, 0) assert_is_instance(lu.MAP_SZ, int) def test_num_...
assert_equal(lu.IDX_FMT.format(i), s[:-2] + '%d' % i)
conditional_block
test_lmdb_utils.py
''' Created on Jan 06, 2016 @author: kashefy ''' from nose.tools import assert_greater, assert_equal, assert_is_instance, assert_true import nideep.iow.lmdb_utils as lu class TestLMDBConsts: def
(self): assert_greater(lu.MAP_SZ, 0) assert_is_instance(lu.MAP_SZ, int) def test_num_idx_digits(self): assert_greater(lu.NUM_IDX_DIGITS, 0) assert_is_instance(lu.NUM_IDX_DIGITS, int) class TestIdxFormat: def test_idx_format(self): assert_greater(len(lu.IDX_FMT), 0) ...
test_map_sz
identifier_name
test_inline_markup.py
#! /usr/bin/env python # $Id: test_inline_markup.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for inline markup in PEPs (readers/pep.py). """ from __init__ import DocutilsTestSupport def suite():
totest = {} totest['standalone_references'] = [ ["""\ See PEP 287 (pep-0287.txt), and RFC 2822 (which obsoletes RFC822 and RFC-733). """, """\ <document source="test data"> <paragraph> See \n\ <reference refuri="http://www.python.org/dev/peps/pep-0287"> PEP 287 ( <re...
s = DocutilsTestSupport.PEPParserTestSuite() s.generateTests(totest) return s
identifier_body
test_inline_markup.py
#! /usr/bin/env python # $Id: test_inline_markup.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for inline markup in PEPs (readers/pep.py). """ from __init__ import DocutilsTestSupport def suite(): s =...
import unittest unittest.main(defaultTest='suite')
conditional_block
test_inline_markup.py
#! /usr/bin/env python # $Id: test_inline_markup.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for inline markup in PEPs (readers/pep.py). """ from __init__ import DocutilsTestSupport def
(): s = DocutilsTestSupport.PEPParserTestSuite() s.generateTests(totest) return s totest = {} totest['standalone_references'] = [ ["""\ See PEP 287 (pep-0287.txt), and RFC 2822 (which obsoletes RFC822 and RFC-733). """, """\ <document source="test data"> <paragraph> See \n\ <reference...
suite
identifier_name
test_inline_markup.py
#! /usr/bin/env python # $Id: test_inline_markup.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for inline markup in PEPs (readers/pep.py). """ from __init__ import DocutilsTestSupport def suite(): s =...
"""], ["""\ References split across lines: PEP 287 RFC 2822 """, """\ <document source="test data"> <paragraph> References split across lines: <paragraph> <reference refuri="http://www.python.org/dev/peps/pep-0287"> PEP 287 <paragraph> <reference refuri="htt...
RFC822 and \n\ <reference refuri="http://www.faqs.org/rfcs/rfc733.html"> RFC-733 ).
random_line_split
Footer.tsx
import * as React from "react"; import * as PropTypes from "prop-types"; import RevealEffect from "react-uwp/RevealEffect"; import FooterLinks from "./FooterLinks"; export interface DataProps { renderContentWidth?: number | string; footerHeight?: number; } export interface FooterProps extends DataProps, React.HT...
margin: "0 auto", padding: "10px 0", display: "flex", flexDirection: "row", flexWrap: "wrap", justifyContent: "space-between", ...style }), links: { display: "inline-block", margin: 20, verticalAlign: "top" }, openSource: { margin: 20, ...
{ const { context: { theme }, props: { footerHeight, renderContentWidth, style } } = footer; const { prefixStyle } = theme; return { root: prefixStyle({ ...theme.acrylicTexture20.style, zIndex: theme.zIndex.header, fontSize: 14, color: theme.baseHigh, minHeight: footer...
identifier_body
Footer.tsx
import * as React from "react"; import * as PropTypes from "prop-types"; import RevealEffect from "react-uwp/RevealEffect"; import FooterLinks from "./FooterLinks"; export interface DataProps { renderContentWidth?: number | string; footerHeight?: number; } export interface FooterProps extends DataProps, React.HT...
} /> </div> <a href="https://github.com/myxvisual/react-uwp/blob/master/LICENSE" target="_blank" {...classes.openSource} > Free & Open Source (MIT) </a> </div> <RevealEffect effectEnable="border...
[{ children: "Github", href: "https://github.com/myxvisual/react-uwp" }]
identifier_name
Footer.tsx
import * as React from "react"; import * as PropTypes from "prop-types"; import RevealEffect from "react-uwp/RevealEffect"; import FooterLinks from "./FooterLinks"; export interface DataProps { renderContentWidth?: number | string; footerHeight?: number; } export interface FooterProps extends DataProps, React.HT...
}, { children: "Fluent Design System", href: "http://fluent.microsoft.com/" }, { children: "Fabric", href: "https://dev.office.com/fabric" }]} /> <FooterLinks style={styles.lin...
href: "https://developer.microsoft.com/en-us/windows" }, { children: "MSDN Forums", href: "https://msdn.microsoft.com/en-us/default.aspx"
random_line_split
Dashboard.tsx
import * as React from 'react'; import { experimentalStyled as styled } from '@material-ui/core/styles'; import CssBaseline from '@material-ui/core/CssBaseline'; import MuiDrawer from '@material-ui/core/Drawer'; import Box from '@material-ui/core/Box'; import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@material...
duration: theme.transitions.duration.enteringScreen, }), }), })); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })( ({ theme, open }) => ({ '& .MuiDrawer-paper': { position: 'relative', whiteSpace: 'nowrap', width: drawerWidth, transition: the...
transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp,
random_line_split
Dashboard.tsx
import * as React from 'react'; import { experimentalStyled as styled } from '@material-ui/core/styles'; import CssBaseline from '@material-ui/core/CssBaseline'; import MuiDrawer from '@material-ui/core/Drawer'; import Box from '@material-ui/core/Box'; import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@material...
(props: any) { return ( <Typography variant="body2" color="text.secondary" align="center" {...props}> {'Copyright © '} <Link color="inherit" href="https://material-ui.com/"> Your Website </Link>{' '} {new Date().getFullYear()} {'.'} </Typography> ); } const drawerWidth...
Copyright
identifier_name