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
gauge.py
# -*- coding: utf-8 - # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software ...
def metrics(self): return [MV(self.name, self.value)]
pass
identifier_body
gauge.py
# -*- coding: utf-8 - # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software ...
from bucky.metrics.metric import Metric, MetricValue as MV class Gauge(Metric): def __init__(self, name): self.name = name self.value = 0.0 def update(self, value): self.value = value def clear(self): pass def metrics(self): return [MV(self.name, self.value)]
random_line_split
gauge.py
# -*- coding: utf-8 - # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software ...
(self, value): self.value = value def clear(self): pass def metrics(self): return [MV(self.name, self.value)]
update
identifier_name
slice-2.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 x = Foo; x[]; //~ ERROR cannot take a slice of a value with type `Foo` x[Foo..]; //~ ERROR cannot take a slice of a value with type `Foo` x[..Foo]; //~ ERROR cannot take a slice of a value with type `Foo` x[Foo..Foo]; //~ ERROR cannot take a slice of a value with type `Foo` x[mut]; //~ ERR...
identifier_body
slice-2.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
// option. This file may not be copied, modified, or distributed // except according to those terms. // Test that slicing syntax gives errors if we have not implemented the trait. struct Foo; fn main() { let x = Foo; x[]; //~ ERROR cannot take a slice of a value with type `Foo` x[Foo..]; //~ ERROR cannot...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
slice-2.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 x = Foo; x[]; //~ ERROR cannot take a slice of a value with type `Foo` x[Foo..]; //~ ERROR cannot take a slice of a value with type `Foo` x[..Foo]; //~ ERROR cannot take a slice of a value with type `Foo` x[Foo..Foo]; //~ ERROR cannot take a slice of a value with type `Foo` x[mut]; //~ ...
main
identifier_name
TableDialog.js
//>>built define( "dojox/editor/plugins/nls/kk/TableDialog", //begin v1.x content ({ insertTableTitle: "Кесте кірістіру", modifyTableTitle: "Кестені өзгерту", rows: "Жолдар:", columns: "Бағандар:", align: "Туралау:", cellPadding: "Ұяшық өрісі:", cellSpacing: "Ұяшық аралығы:", tableWidth: "Кесте ені:", backgrou...
);
}) //end v1.x content
random_line_split
iterable.py
djangae.forms.fields import ListFormField from django.utils.text import capfirst class _FakeModel(object): """ An object of this class can pass itself off as a model instance when used as an arguments to Field.pre_save method (item_fields of iterable fields are not actually fields of any model). ...
if isinstance(item_field_type, models.ForeignKey): raise ImproperlyConfigured("Lists of ForeignKeys aren't supported, use RelatedSetField instead") self.item_field_type = item_field_type # We'll be pretending that item_field is a field of a model # with just one "value" f...
item_field_type = item_field_type()
conditional_block
iterable.py
djangae.forms.fields import ListFormField from django.utils.text import capfirst class _FakeModel(object): """ An object of this class can pass itself off as a model instance when used as an arguments to Field.pre_save method (item_fields of iterable fields are not actually fields of any model). ...
if hasattr(item_field_type, 'attname'): item_field_type = item_field_type.__class__ if callable(item_field_type): item_field_type = item_field_type() if isinstance(item_field_type, models.ForeignKey): raise ImproperlyConfigured("Lists of ForeignKeys aren't ...
random_line_split
iterable.py
djangae.forms.fields import ListFormField from django.utils.text import capfirst class _FakeModel(object): """ An object of this class can pass itself off as a model instance when used as an arguments to Field.pre_save method (item_fields of iterable fields are not actually fields of any model). ...
(self, value): if value is None: return self._iterable_type([]) # Because a set cannot be defined in JSON, we must allow a list to be passed as the value # of a SetField, as otherwise SetField data can't be loaded from fixtures if not hasattr(value, "__iter__"): # Allows lis...
to_python
identifier_name
iterable.py
djangae.forms.fields import ListFormField from django.utils.text import capfirst class _FakeModel(object): """ An object of this class can pass itself off as a model instance when used as an arguments to Field.pre_save method (item_fields of iterable fields are not actually fields of any model). ...
def db_type(self, connection): return 'set' def get_db_prep_save(self, *args, **kwargs): ret = super(SetField, self).get_db_prep_save(*args, **kwargs) if ret: ret = list(ret) return ret
return set
identifier_body
conf.py
# -*- coding: utf-8 -*- # # zambiaureport documentation build configuration file, created by # sphinx-quickstart. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values ...
html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The n...
# The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes.
random_line_split
__init__.py
#!/usr/bin/env python """Provide command line interface to easygv.""" # Imports import logzero from logzero import logger as log import os from pathlib import Path import appdirs from munch import Munch import click import graphviz as gv from easygv.cli import config as _config from easygv import easygv # Meta...
if formats == 'all': formats = draw_formats[1:] else: formats = [formats] graph_input = easygv.load_graph_input(path=definition) attrs = easygv.process_attrs(attr_config) g = easygv.build_graph(graph_input=graph_input, attrs=attrs) gvg = gv.Source(g.string(), engine=layout) ...
name = 'easygv'
conditional_block
__init__.py
#!/usr/bin/env python """Provide command line interface to easygv.""" # Imports import logzero from logzero import logger as log import os from pathlib import Path import appdirs from munch import Munch import click import graphviz as gv from easygv.cli import config as _config from easygv import easygv # Meta...
(ctx, generate_config, kind, prefix): """Manage configuration values and files.""" factory_resets = FACTORY_RESETS default_files = {"attrs": factory_resets / 'attrs.yaml'} if generate_config: if kind == 'all': for p in default_files['all']: _config.replace_config(nam...
config
identifier_name
__init__.py
#!/usr/bin/env python """Provide command line interface to easygv.""" # Imports import logzero from logzero import logger as log import os from pathlib import Path import appdirs from munch import Munch import click import graphviz as gv from easygv.cli import config as _config from easygv import easygv # Meta...
@main.command() @click.option('-g', '--generate-config', is_flag=True, help="Copy one or more of the 'factory default' config files to the users " "config directory ({user_config_dir}). Back ups will be made of any existing config files.".format(user_config_dir=USER_APP_DIR)...
"""Command interface to easygv. Define nodes and edges in an excel file and graph-style attributes in a yaml file with inheritence. For command specific help text, call the specific command followed by the --help option. """ ctx.obj = Munch() # NOTE: Not sure I need to store this or just set ...
identifier_body
__init__.py
#!/usr/bin/env python """Provide command line interface to easygv.""" # Imports import logzero from logzero import logger as log import os from pathlib import Path import appdirs from munch import Munch import click import graphviz as gv from easygv.cli import config as _config from easygv import easygv # Meta...
graph, node-, and edge-types """ log.info("Preparing your graph.") directory = Path(directory) definition = Path(definition) attr_config = Path(attr_config) if name is None: name = 'easygv' if formats == 'all': formats = draw_formats[1:] else: ...
ATTR_CONFIG = YAML file containing the attribute information for your
random_line_split
macros.rs
/// Define a trait as usual, and a macro that can be used to instantiate /// implementations of it. /// /// There *must* be section markers in the trait definition: /// @section type for associated types /// @section self for methods /// @section nodelegate for arbitrary tail that is not forwarded. macro_rules! trait_t...
}) => { impl<$($param)*> $name for $self_wrap where $self_type: $name { $( $( type $assoc_name = $self_type::$assoc_name; )* )* $( type $assoc_name_ext = $self_type::$assoc_name_ext; )* $( ...
// Arbitrary tail that is ignored when forwarding. $( @section nodelegate $($tail:tt)* )*
random_line_split
index.d.ts
export interface AxiosTransformer { (data: any, headers?: any): any; } export interface AxiosAdapter { (config: AxiosRequestConfig): AxiosPromise<any>; } export interface AxiosBasicCredentials { username: string; password: string; } export interface AxiosProxyConfig { host: string; port: number; } expor...
} declare const Axios: AxiosStatic; export default Axios;
CancelToken: CancelTokenStatic; isCancel(value: any): boolean; all<T>(values: (T | Promise<T>)[]): Promise<T[]>; spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
random_line_split
render_mode_inheritance.js
'use strict'; import React from 'react'; import { external_url_map } from "../components/globals"; /** * Method to display either mode of inheritance with adjective, * or just mode of inheritance if no adjective * @param {object} object - A GDM or Interpretation object */ export function renderSelectedModeInherita...
(modeInheritance, modeInheritanceAdjective) { if (modeInheritance) { let start = modeInheritance.indexOf('('); let end = modeInheritance.indexOf(')'); let hpoNumber; let adjective = modeInheritanceAdjective && modeInheritanceAdjective.length ? ' (' + modeInheritanceAdjective.match(/^...
renderModeInheritanceLink
identifier_name
render_mode_inheritance.js
'use strict'; import React from 'react'; import { external_url_map } from "../components/globals"; /** * Method to display either mode of inheritance with adjective, * or just mode of inheritance if no adjective * @param {object} object - A GDM or Interpretation object */ export function renderSelectedModeInherita...
}
{ if (modeInheritance) { let start = modeInheritance.indexOf('('); let end = modeInheritance.indexOf(')'); let hpoNumber; let adjective = modeInheritanceAdjective && modeInheritanceAdjective.length ? ' (' + modeInheritanceAdjective.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1] + ')' : ...
identifier_body
render_mode_inheritance.js
'use strict'; import React from 'react'; import { external_url_map } from "../components/globals"; /** * Method to display either mode of inheritance with adjective, * or just mode of inheritance if no adjective * @param {object} object - A GDM or Interpretation object */ export function renderSelectedModeInherita...
let end = modeInheritance.indexOf(')'); let hpoNumber; let adjective = modeInheritanceAdjective && modeInheritanceAdjective.length ? ' (' + modeInheritanceAdjective.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1] + ')' : ''; if (start && end) { hpoNumber = modeInheritance.substri...
random_line_split
render_mode_inheritance.js
'use strict'; import React from 'react'; import { external_url_map } from "../components/globals"; /** * Method to display either mode of inheritance with adjective, * or just mode of inheritance if no adjective * @param {object} object - A GDM or Interpretation object */ export function renderSelectedModeInherita...
else { return ( <span>{modeInheritance + adjective}</span> ); } } }
{ let hpoLink = external_url_map['HPO'] + hpoNumber; return ( <span><a href={hpoLink} target="_blank">{modeInheritance.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1]}</a>{adjective}</span> ); }
conditional_block
overlay-context.ts
import { Injectable } from '@angular/core'; import { FluentAssign, FluentAssignMethod } from './../framework/fluent-assign'; import { extend, arrayUnion } from './../framework/utils'; import { DialogRef } from './dialog-ref'; import { WideVCRef, OverlayConfig } from './tokens'; export const DEFAULT_VALUES = { inEle...
else if (!Array.isArray(<Array<number>>this.keyboard)) { this.keyboard = DEFAULT_VALUES.keyboard; } } } /** * A core context builder for a modal window instance, used to define the context upon * a modal choose it's behaviour. */ @Injectable() export class OverlayContextBuilder<T extends OverlayContext...
{ this.keyboard = [<number>this.keyboard]; }
conditional_block
overlay-context.ts
import { Injectable } from '@angular/core'; import { FluentAssign, FluentAssignMethod } from './../framework/fluent-assign'; import { extend, arrayUnion } from './../framework/utils'; import { DialogRef } from './dialog-ref'; import { WideVCRef, OverlayConfig } from './tokens'; export const DEFAULT_VALUES = { inEle...
(defaultValues: T | T[] = undefined, initialSetters: string[] = undefined, baseType: new () => T = undefined) { super( extend<any>(DEFAULT_VALUES, defaultValues || {}), arrayUnion<string>(DEFAULT_SETTERS, initialSetters || []), baseType || <any>OverlayContext // https:/...
constructor
identifier_name
overlay-context.ts
import { Injectable } from '@angular/core'; import { FluentAssign, FluentAssignMethod } from './../framework/fluent-assign'; import { extend, arrayUnion } from './../framework/utils'; import { DialogRef } from './dialog-ref'; import { WideVCRef, OverlayConfig } from './tokens'; export const DEFAULT_VALUES = { inEle...
} export interface ModalControllingContextBuilder<T> { open(viewContainer?: WideVCRef): Promise<DialogRef<T>>; } /** * A helper to create an `OverlayConfig` on the fly. * Since `OverlayConfig` requires context it means a builder is needed, this process had some boilerplate. * When a quick, on the fly overlay co...
{ return extend(base || {}, { context: this.toJSON() }); }
identifier_body
overlay-context.ts
import { Injectable } from '@angular/core'; import { FluentAssign, FluentAssignMethod } from './../framework/fluent-assign'; import { extend, arrayUnion } from './../framework/utils'; import { DialogRef } from './dialog-ref'; import { WideVCRef, OverlayConfig } from './tokens'; export const DEFAULT_VALUES = { inEle...
super( extend<any>(DEFAULT_VALUES, defaultValues || {}), arrayUnion<string>(DEFAULT_SETTERS, initialSetters || []), baseType || <any>OverlayContext // https://github.com/Microsoft/TypeScript/issues/7234 ); } /** * Returns an new OverlayConfig with a context property representing the da...
constructor(defaultValues: T | T[] = undefined, initialSetters: string[] = undefined, baseType: new () => T = undefined) {
random_line_split
ewf_path_spec.py
#!/usr/bin/python # -*- coding: utf-8 -*- """Tests for the EWF image path specification implementation.""" import unittest from dfvfs.path import ewf_path_spec from tests.path import test_lib class EwfPathSpecTest(test_lib.PathSpecTestCase): """Tests for the EWF image path specification implementation.""" def...
if __name__ == '__main__': unittest.main()
"""Tests the path specification comparable property.""" path_spec = ewf_path_spec.EwfPathSpec(parent=self._path_spec) self.assertNotEqual(path_spec, None) expected_comparable = u'\n'.join([ u'type: TEST', u'type: EWF', u'']) self.assertEqual(path_spec.comparable, expected_comp...
identifier_body
ewf_path_spec.py
#!/usr/bin/python # -*- coding: utf-8 -*- """Tests for the EWF image path specification implementation.""" import unittest from dfvfs.path import ewf_path_spec from tests.path import test_lib class EwfPathSpecTest(test_lib.PathSpecTestCase): """Tests for the EWF image path specification implementation.""" def...
(self): """Tests the path specification initialization.""" path_spec = ewf_path_spec.EwfPathSpec(parent=self._path_spec) self.assertNotEqual(path_spec, None) with self.assertRaises(ValueError): _ = ewf_path_spec.EwfPathSpec(parent=None) with self.assertRaises(ValueError): _ = ewf_path...
testInitialize
identifier_name
ewf_path_spec.py
#!/usr/bin/python # -*- coding: utf-8 -*- """Tests for the EWF image path specification implementation.""" import unittest from dfvfs.path import ewf_path_spec from tests.path import test_lib class EwfPathSpecTest(test_lib.PathSpecTestCase): """Tests for the EWF image path specification implementation.""" def...
unittest.main()
conditional_block
ewf_path_spec.py
#!/usr/bin/python
import unittest from dfvfs.path import ewf_path_spec from tests.path import test_lib class EwfPathSpecTest(test_lib.PathSpecTestCase): """Tests for the EWF image path specification implementation.""" def testInitialize(self): """Tests the path specification initialization.""" path_spec = ewf_path_spec...
# -*- coding: utf-8 -*- """Tests for the EWF image path specification implementation."""
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 ...
(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult> { let (expr, endian) = parse_tts(cx, tts); let little = match endian { None => false, Some(Ident{ident, span}) => match token::get_ident(ident).get() { "little" => true, ...
expand_syntax_ext
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 ...
use syntax::parse::token::InternedString; use rustc::plugin::Registry; use std::gc::Gc; #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("fourcc", expand_syntax_ext); } pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box...
use syntax::ext::base; use syntax::ext::base::{ExtCtxt, MacExpr}; use syntax::ext::build::AstBuilder; use syntax::parse::token;
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 ...
// FIXME (10872): This is required to prevent an LLVM assert on Windows #[test] fn dummy_test() { }
{ let meta = cx.meta_name_value(sp, InternedString::new("target_endian"), ast::LitStr(InternedString::new("little"), ast::CookedStr)); contains(cx.cfg().as_slice(), meta) }
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 ...
}, _ => { cx.span_err(expr.span, "non-literal in fourcc!"); return base::DummyResult::expr(sp) } }; let mut val = 0u32; for codepoint in s.get().chars().take(4) { let byte = if codepoint as u32 > 0xFF { cx.span_err(expr.span, "fourcc! lit...
{ cx.span_err(expr.span, "unsupported literal in fourcc!"); return base::DummyResult::expr(sp) }
conditional_block
map.py
""" Dump Mapper This script acts as a map/function over the pages in a set of MediaWiki database dump files. This script allows the algorithm for processing a set of pages to be spread across the available processor cores of a system for faster analysis. This script can also be imported as a module to expose the ...
(path): """ Verifies that a file exists at a given path and that the file has a known extension type. :Parameters: path : `str` the path to a dump file """ path = os.path.expanduser(path) if not os.path.isfile(path): raise FileTypeError("Can't find file %s" % path) match = EXT_RE.search(path) if...
dumpFile
identifier_name
map.py
""" Dump Mapper This script acts as a map/function over the pages in a set of MediaWiki database dump files. This script allows the algorithm for processing a set of pages to be spread across the available processor cores of a system for faster analysis. This script can also be imported as a module to expose the ...
self.output.put(out) except Exception as e: self.logger.error( "Failed to process page %s:%s - %s" % ( page.getId(), page.getTitle(), e ) ) except Empty: self.logger.info("Nothing left to do. Shutting down thread.") finally: se...
try: if self.noop: self.processPage(dump, page) else: for out in self.processPage(dump, page):
random_line_split
map.py
""" Dump Mapper This script acts as a map/function over the pages in a set of MediaWiki database dump files. This script allows the algorithm for processing a set of pages to be spread across the available processor cores of a system for faster analysis. This script can also be imported as a module to expose the ...
#output while processes are running while running.value > 0: try: yield output.get(timeout=.25) except Empty: pass #finish yielding output buffer try: while True: yield output.get(block=False) except Empty: pass EXTENSIONS = { 'xml': "cat", 'bz2': "bzcat", '7z': "7zr e -so", '...
running.value += 1 Processor( input, processPage, output, dec, logging.getLogger("Process %s" % i), False ).start()
conditional_block
map.py
""" Dump Mapper This script acts as a map/function over the pages in a set of MediaWiki database dump files. This script allows the algorithm for processing a set of pages to be spread across the available processor cores of a system for faster analysis. This script can also be imported as a module to expose the ...
outputBuffer : int the maximum number of output values to buffer. """ input = dumpFiles(dumps) output = Queue(maxsize=outputBuffer) running = Value('i', 0) threads = max(1, min(int(threads), input.qsize())) def dec(): running.value -= 1 for i in range(0, threads): running.value += 1 Processor( ...
""" Maps a function across all of the pages in a set of dump files and returns an (order not guaranteed) iterator over the output. Increasing the `outputBuffer` size will allow more mapplications to happen before the output is read, but will consume memory to do so. Big output buffers are benefitial when the ...
identifier_body
class-cast-to-trait.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 ...
} fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } pub fn main() { let nyan: @mut noisy = @mut cat(0u, 2, ~"nyan") as @mut noisy; nyan.speak(); }
{ error!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } }
identifier_body
class-cast-to-trait.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 ...
{ priv meows: uint, how_hungry: int, name: ~str, } impl noisy for cat { fn speak(&mut self) { self.meow(); } } impl cat { pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { error!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { error!("Not hungry...
cat
identifier_name
class-cast-to-trait.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 ...
nyan.speak(); }
pub fn main() { let nyan: @mut noisy = @mut cat(0u, 2, ~"nyan") as @mut noisy;
random_line_split
class-cast-to-trait.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 ...
} } impl cat { fn meow(&mut self) { error!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } } } fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } pub...
{ error!("Not hungry!"); return false; }
conditional_block
test_get_rest_mags.py
import unittest import ezgal.zf_grid import numpy as np import math # I put the test data for the zf_grid tests in # tests.zf_grid instead of in tests because # there is a lot of data but it is all # specific for this test. import tests.zf_grid class test_get_rest_mags(tests.zf_grid.test_zf_grid): def test_get_r...
def test_get_rest_mags_lower_bound(self): # if we go lower than our lowest grided z then # we should get a nan vals = self.zf_grid.get_rest_mags([-1]) self.assertTrue(math.isnan(vals[0])) def test_get_rest_mags_upper_bound(self): # if we go lower than our lowest gri...
self.assertTrue(np.allclose( self.zf_grid.get_rest_mags(tests.zf_grid.test_zs), [0.275, 0.75, 1.25, 1.75, 2.25, 2.778], 1e-4))
identifier_body
test_get_rest_mags.py
import unittest import ezgal.zf_grid import numpy as np import math # I put the test data for the zf_grid tests in # tests.zf_grid instead of in tests because # there is a lot of data but it is all # specific for this test. import tests.zf_grid class test_get_rest_mags(tests.zf_grid.test_zf_grid): def test_get_r...
def test_get_rest_mags_upper_bound(self): # if we go lower than our lowest grided z then # we should get a nan vals = self.zf_grid.get_rest_mags([4]) self.assertTrue(math.isnan(vals[0])) if __name__ == '__main__': unittest.main()
random_line_split
test_get_rest_mags.py
import unittest import ezgal.zf_grid import numpy as np import math # I put the test data for the zf_grid tests in # tests.zf_grid instead of in tests because # there is a lot of data but it is all # specific for this test. import tests.zf_grid class test_get_rest_mags(tests.zf_grid.test_zf_grid): def test_get_r...
(self): # if we go lower than our lowest grided z then # we should get a nan vals = self.zf_grid.get_rest_mags([4]) self.assertTrue(math.isnan(vals[0])) if __name__ == '__main__': unittest.main()
test_get_rest_mags_upper_bound
identifier_name
test_get_rest_mags.py
import unittest import ezgal.zf_grid import numpy as np import math # I put the test data for the zf_grid tests in # tests.zf_grid instead of in tests because # there is a lot of data but it is all # specific for this test. import tests.zf_grid class test_get_rest_mags(tests.zf_grid.test_zf_grid): def test_get_r...
unittest.main()
conditional_block
Transformer.ts
import BaseObject from "ts-core/lib/BaseObject"; import Text from "ts-core/lib/Utils/Text"; import * as _ from "underscore"; export interface TransformerInterface { new():Transformer; item(data); collection(data); } export default class Transformer extends BaseObject { public availableIncludes = []; ...
return transformer.item(data); } public static transformRequest(data) { var transformer = new this; return transformer.transformRequest(data); } }
var transformer = new this;
random_line_split
Transformer.ts
import BaseObject from "ts-core/lib/BaseObject"; import Text from "ts-core/lib/Utils/Text"; import * as _ from "underscore"; export interface TransformerInterface { new():Transformer; item(data); collection(data); } export default class Transformer extends BaseObject { public availableIncludes = []; ...
(data) { return data; } public transform(item) { return item; } public collection(data) { if (!data) { return null; } return _.map(data, item => this.item(item)); } public item(data) { if (!data) { return null; ...
transformRequest
identifier_name
Transformer.ts
import BaseObject from "ts-core/lib/BaseObject"; import Text from "ts-core/lib/Utils/Text"; import * as _ from "underscore"; export interface TransformerInterface { new():Transformer; item(data); collection(data); } export default class Transformer extends BaseObject { public availableIncludes = []; ...
public static item(data) { var transformer = new this; return transformer.item(data); } public static transformRequest(data) { var transformer = new this; return transformer.transformRequest(data); } }
{ var transformer = new this; return transformer.collection(data); }
identifier_body
Transformer.ts
import BaseObject from "ts-core/lib/BaseObject"; import Text from "ts-core/lib/Utils/Text"; import * as _ from "underscore"; export interface TransformerInterface { new():Transformer; item(data); collection(data); } export default class Transformer extends BaseObject { public availableIncludes = []; ...
return _.map(data, item => this.item(item)); } public item(data) { if (!data) { return null; } var result = this.transform(data); _.each(this.availableIncludes, (include:any) => { var includeMethod = 'include' + Text.ucFirst(include); ...
{ return null; }
conditional_block
vm.rs
use std::collections::HashMap; use serde_json; use serde_json::value::Value; use common::{Context, Result, Error}; use common::structs::VM; use database; use handler; use backend; use remote; use net; /* * Validates the user-specified parameters for VM creation, and sets up the VM's network interfaces */ fn valida...
/* * Handle a 'statusvm' command */ pub fn status(ctx: &Context, name: &str) -> Result<String> { let mut vm = try!(database::vm::get(ctx, name)); match backend::vm::script_status(ctx, &mut vm) { Ok(p) => { let mut pp: HashMap<String, Value> = HashMap::new(); for (k, v) in p ...
{ let mut vm = try!(database::vm::get(ctx, name)); match backend::vm::script_stop(ctx, &mut vm) { Ok(_) => Ok(String::new()), Err(e) => Err(e) } }
identifier_body
vm.rs
use std::collections::HashMap; use serde_json; use serde_json::value::Value; use common::{Context, Result, Error}; use common::structs::VM; use database; use handler; use backend; use remote; use net; /* * Validates the user-specified parameters for VM creation, and sets up the VM's network interfaces */ fn valida...
(ctx: &Context, name: &str) -> Result<String> { let mut vm = try!(database::vm::get(ctx, name)); match backend::vm::script_start(ctx, &mut vm) { Ok(_) => {}, Err(e) => return Err(e) }; Ok(String::new()) } /* * Handle a 'stopvm' command */ pub fn stop(ctx: &Context, name: &str) -> Re...
start
identifier_name
vm.rs
use std::collections::HashMap; use serde_json; use serde_json::value::Value; use common::{Context, Result, Error}; use common::structs::VM; use database; use handler; use backend; use remote; use net; /* * Validates the user-specified parameters for VM creation, and sets up the VM's network interfaces */ fn valida...
} // TODO: Check backend, make sure it exists if vm.image.len() > 0 { if let Err(_) = database::image::get(ctx, vm.image.as_str()) { return Err(Error::new("Image not found")); } } let mut index = 0; for iface in &mut vm.interfaces { if iface.mac.len() == 0 ...
return Err(Error::new("The 'name' must be less than 11 characters long")); } if vm.backend.len() == 0 { return Err(Error::new("A 'backend' is required"));
random_line_split
cssLabAbout.js
/* ~ Copyright (c) 2014 George Norman. ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ -------------------------------------------------------------- ~ Renders <css-lab-about> tags - sharable among all projects. ~ ----------------------------...
* &lt;css-lab-about style="margin-top:12px;"/&gt; * </pre> * * @module cssLabAboutTag */ var cssLabAboutTag = (function(tzDomHelper, tzCustomTagHelper) { "use strict"; // http://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript var template = ['This page contains example co...
* The &lt;css-lab-about&gt; tag renders a common introduction, displayed across all of the * CSS Lab projects and pages. There can be only one Introduction section per page. *<p> * Example: * <pre style="background:#eee; padding:6px;">
random_line_split
testing.rs
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use crate::{ raw::{config::*, security}, testing::s2n_tls::Harness, }; use bytes::Bytes; use core::task::Poll; use std::collections::VecDeque; pub mod s2n_tls; type Error = Box<dyn std::error::Error>;...
(&mut self) -> &'static [u8] { self.cert } fn key(&mut self) -> &'static [u8] { self.key } } pub fn build_config(cipher_prefs: &security::Policy) -> Result<crate::raw::config::Config, Error> { let mut builder = Builder::new(); let mut keypair = CertKeyPair::default(); // Build ...
cert
identifier_name
testing.rs
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use crate::{ raw::{config::*, security}, testing::s2n_tls::Harness, }; use bytes::Bytes; use core::task::Poll; use std::collections::VecDeque; pub mod s2n_tls; type Error = Box<dyn std::error::Error>;...
(_, Poll::Ready(server_res)) => { server_res?; Poll::Pending } _ => Poll::Pending, } } } #[derive(Debug, Default)] pub struct MemoryContext { rx: VecDeque<Bytes>, tx: VecDeque<Bytes>, } impl MemoryContext { pub fn transfer(&m...
{ assert!( self.max_iterations > 0, "handshake has iterated too many times: {:#?}", self, ); let client_res = self.client.0.poll(&mut self.client.1); let server_res = self.server.0.poll(&mut self.server.1); self.client.1.transfer(&mut self.serv...
identifier_body
testing.rs
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use crate::{ raw::{config::*, security}, testing::s2n_tls::Harness, }; use bytes::Bytes; use core::task::Poll; use std::collections::VecDeque; pub mod s2n_tls; type Error = Box<dyn std::error::Error>;...
let mut server = crate::raw::connection::Connection::new_server(); server .set_config(config.clone()) .expect("Failed to bind config to server connection"); server .set_client_auth_type(s2n_tls_sys::s2n_cert_auth_type::NONE) .expect("Unable to set server client auth type"); ...
pub fn s2n_tls_pair(config: crate::raw::config::Config) { // create and configure a server connection
random_line_split
htmlappletelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLAppletElementBinding; use dom::bindings::codegen::Bindings::HTMLAppletEl...
(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLAppletElement { HTMLAppletElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub...
new_inherited
identifier_name
htmlappletelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLAppletElementBinding; use dom::bindings::codegen::Bindings::HTMLAppletEl...
impl HTMLAppletElement { fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLAppletElement { HTMLAppletElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } ...
#[dom_struct] pub struct HTMLAppletElement { htmlelement: HTMLElement }
random_line_split
htmlappletelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLAppletElementBinding; use dom::bindings::codegen::Bindings::HTMLAppletEl...
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("name") => AttrValue::from_atomic(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } }
{ Some(self.upcast::<HTMLElement>() as &VirtualMethods) }
identifier_body
test_init.py
"""Tests for the ATAG integration.""" import aiohttp from homeassistant.components.atag import DOMAIN from homeassistant.config_entries import ENTRY_STATE_SETUP_RETRY from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.components.atag import init_integration from tests.test_util...
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test the ATAG configuration entry unloading.""" entry = await init_integration(hass, aioclient_mock) assert hass.data[DOMAIN] await hass.config_entries.async_unload(entry.entry_id) await hass.async_block_till_done() ass...
test_unload_config_entry
identifier_name
test_init.py
"""Tests for the ATAG integration.""" import aiohttp from homeassistant.components.atag import DOMAIN from homeassistant.config_entries import ENTRY_STATE_SETUP_RETRY from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.components.atag import init_integration from tests.test_util...
async def test_unload_config_entry( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test the ATAG configuration entry unloading.""" entry = await init_integration(hass, aioclient_mock) assert hass.data[DOMAIN] await hass.config_entries.async_unload(entry.entry_id) await...
"""Test configuration entry not ready when library returns False.""" with patch("pyatag.AtagOne.update", return_value=False): entry = await init_integration(hass, aioclient_mock) assert entry.state == ENTRY_STATE_SETUP_RETRY
identifier_body
test_init.py
"""Tests for the ATAG integration.""" import aiohttp from homeassistant.components.atag import DOMAIN from homeassistant.config_entries import ENTRY_STATE_SETUP_RETRY from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.components.atag import init_integration from tests.test_util...
async def test_config_entry_empty_reply( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test configuration entry not ready when library returns False.""" with patch("pyatag.AtagOne.update", return_value=False): entry = await init_integration(hass, aioclient_mock) as...
random_line_split
profile2.py
and preferences functions ######################################################### ## Profile functions def getDefaultProfilePath(): if platform.system() == "Windows": basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) #If we have a frozen python install, we need to step...
return pre + time.strftime('%a').encode('utf-8', 'replace')
conditional_block
profile2.py
to next object on the platform. clear_z is the minimal z height we need to make sure we do not hit any objects. G92 E0 G91 ;relative positioning G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure G1 Z+0.5 E-5...
(name): try: setting = getProfileSetting(name).replace(',', '.') return float(eval(setting, {}, {})) except (ValueError, SyntaxError, TypeError): return 0.0 def putProfileSetting(name, value): #Check if we have a configuration file loaded, else load the default. if not globals().has_key('globalProfileParser'...
getProfileSettingFloat
identifier_name
profile2.py
('alterations'): if key in tempOverride: p.append(key + "=" + tempOverride[key]) tempDone.append(key) else: alt.append(key + "=" + globalProfileParser.get('alterations', key)) for key in tempOverride: if key not in tempDone: p.append(key + "=" + tempOverride[key]) ret = '\b'.join(p) + '\f' + '\...
if not globals().has_key('globalProfileParser'): loadGlobalProfile(getDefaultProfilePath()) if not globalProfileParser.has_option('alterations', filename): if filename in alterationDefault: default = alterationDefault[filename] else: print("Missing default alteration for: '" + filename + "'") alterati...
identifier_body
profile2.py
PreferenceParser.has_section('preference'): globalPreferenceParser.add_section('preference') globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8")) globalPreferenceParser.write(open(getPreferencePath(), 'w')) def isPreference(name): if name in preferencesDefaultSettings: return True ret...
if len(line) != 2: continue if line[0].upper() == 'NAME': item['name'] = line[1].strip()
random_line_split
jquery.tablesorter.pager.js
(function($) { $.extend({ tablesorterPager: new function() { function updatePageDisplay(c) { var s = $(c.cssPageDisplay,c.container).val((c.page+1) + c.seperator + c.totalPages); } function setPageSize(table,size) { var c = table.config; c.size = size; c.totalPages = Math.ceil(c.totalRows ...
config.page = parseInt($(this).text()) - 1; moveToPage(table); }); } $(pages[config.page]).addClass('active'); } this.appender = function(table,rows) { var c = table.config; c.rowsCopy = rows...
{ /* * Creates numbered pagination links * and appends to config.cssPaginationDisplay */ var config = table.config; var pager = config.container; var paginationNode = $(pager).find(config.cssPaginationDis...
identifier_body
jquery.tablesorter.pager.js
(function($) { $.extend({ tablesorterPager: new function() { function updatePageDisplay(c) { var s = $(c.cssPageDisplay,c.container).val((c.page+1) + c.seperator + c.totalPages); } function setPageSize(table,size) { var c = table.config; c.size = size; c.totalPages = Math.ceil(c.totalRows ...
var pages = paginationNode.children('span.page'); if (config.totalPages > 1) { pages.bind('click', function() { config.page = parseInt($(this).text()) - 1; moveToPage(table); }); } ...
{ for (var x=0; x < config.totalPages; x+=1) { $('<span class="page">' + (x+1) + '</span>').appendTo(paginationNode); } }
conditional_block
jquery.tablesorter.pager.js
(function($) { $.extend({ tablesorterPager: new function() { function updatePageDisplay(c) { var s = $(c.cssPageDisplay,c.container).val((c.page+1) + c.seperator + c.totalPages); } function setPageSize(table,size) { var c = table.config; c.size = size; c.totalPages = Math.ceil(c.totalRows ...
(table) { var c = table.config; if (c.page > 0) { c.page -= 1; moveToPage(table); } } function moveToPage(table) { var c = table.config; if(c.page < 0 || c.page > (c.totalPages-1)) { c.page = 0; } renderTable(table...
moveToPrevPage
identifier_name
jquery.tablesorter.pager.js
(function($) { $.extend({ tablesorterPager: new function() { function updatePageDisplay(c) { var s = $(c.cssPageDisplay,c.container).val((c.page+1) + c.seperator + c.totalPages); } function setPageSize(table,size) { var c = table.config; c.size = size; c.totalPages = Math.ceil(c.totalRows ...
var c = table.config; c.page = 0; moveToPage(table); } function moveToLastPage(table) { var c = table.config; c.page = (c.totalPages-1); moveToPage(table); } function moveToNextPage(table) { var c = table.config; if (c.page < (c.totalPages-1)) { ...
} } function moveToFirstPage(table) {
random_line_split
update-image.mock.ts
export const request = { "headers": { "Content-Type": "application/json", }, "body": { "name": "ubuntu-18.04-minimal", "distribution": "Ubuntu", "description": "update-works" } }; export const response = { "body": { "image": { "id": 7938391, "name": "new-image-name", ...
], "status": "available", "error_message": "" }, }, "headers": { "content-type": "application/json; charset=utf-8", "status": 200, "ratelimit-limit": 1200, "ratelimit-remaining": 1137, "ratelimit-reset": 1415984218 }, };
"min_disk_size": 20, "size_gigabytes": 2.34, "description": "", "tags": [
random_line_split
Pattern.py
from __future__ import absolute_import, division, print_function, unicode_literals import copy import re import six from echomesh.expression import ConstantExpression from echomesh.expression import Expression from echomesh.expression.LiteralExpression import LiteralExpression from echomesh.pattern.Registry import ma...
(self): return self._value if self.is_constant else self._evaluate() def _evaluate(self): return [] def _precompute(self): pass def __str__(self): return 'pattern "%s" in element "%s"' % ( self.name, self.element.class_name()) def copy_settings(cl, **kwds): ...
evaluate
identifier_name
Pattern.py
from __future__ import absolute_import, division, print_function, unicode_literals import copy import re import six from echomesh.expression import ConstantExpression from echomesh.expression import Expression from echomesh.expression.LiteralExpression import LiteralExpression from echomesh.pattern.Registry import ma...
class Filter(Pattern): """A Filter is a Pattern that contains exactly one Pattern.""" PATTERN_COUNT = 1 def _evaluate(self): color_lists = self.patterns() assert len(color_lists) == 1 return self._evaluate_one(color_lists[0])
random_line_split
Pattern.py
from __future__ import absolute_import, division, print_function, unicode_literals import copy import re import six from echomesh.expression import ConstantExpression from echomesh.expression import Expression from echomesh.expression.LiteralExpression import LiteralExpression from echomesh.pattern.Registry import ma...
value = desc.get(k, v.get('default')) if value is None and 'default' not in v: missing.append(k) else: if literal: expression = LiteralExpression(value) elif const: expression = ConstantExpressio...
self.constants.add(k)
conditional_block
Pattern.py
from __future__ import absolute_import, division, print_function, unicode_literals import copy import re import six from echomesh.expression import ConstantExpression from echomesh.expression import Expression from echomesh.expression.LiteralExpression import LiteralExpression from echomesh.pattern.Registry import ma...
def patterns(self): return [p.evaluate() for p in self._patterns] def evaluate(self): return self._value if self.is_constant else self._evaluate() def _evaluate(self): return [] def _precompute(self): pass def __str__(self): return 'pattern "%s" in eleme...
return dict((name, self.get(name)) for name in names)
identifier_body
DetailsNavigation.tsx
/* Copyright (C) 2017 Cloudbase Solutions SRL This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribute...
extends React.Component<Props> { renderItems() { return ( this.props.items.map(item => ( <Item selected={item.value === this.props.selectedValue} key={item.value || item.label} to={this.props.customHref ? this.props.customHref(item) : `/${this.props.itemType || ''}s/${...
DetailsNavigation
identifier_name
DetailsNavigation.tsx
/* Copyright (C) 2017 Cloudbase Solutions SRL
published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero Gener...
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as
random_line_split
DetailsNavigation.tsx
/* Copyright (C) 2017 Cloudbase Solutions SRL This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribute...
} export default DetailsNavigation
{ return ( <Wrapper> {this.renderItems()} </Wrapper> ) }
identifier_body
index.js
const electron = require('electron'); const ipcRenderer = electron.ipcRenderer; window.onload = function() { ipcRenderer.send('game-preview-loaded'); } ipcRenderer.on('game-preview-start', function(event, data) { var app = new Application({ // resize: true, fullscreen: true, antyAliasing: true, ...
//load scene (json) // this.loader.load('json', scene file path, 'scene.json'); }, //instantiate scene objects loaded: function(){ //instantiate all object for(var i = 0; i < data.sceneFile.length; i++) { if(data.sceneFile[i].tag == 'mainCamera') { this.mainCamer...
{ var meta = data.assets[i]; if(meta.type == 'script') { require(meta.path); // connect script with uuid } else { this.loader.load(meta.type, meta.path, meta.name, meta.uuid); } }
conditional_block
index.js
const electron = require('electron'); const ipcRenderer = electron.ipcRenderer; window.onload = function() { ipcRenderer.send('game-preview-loaded'); } ipcRenderer.on('game-preview-start', function(event, data) { var app = new Application({ // resize: true, fullscreen: true, antyAliasing: true, ...
} }); })
random_line_split
tests.rs
#[test] fn rustc_bootstrap_parsing() { let is_bootstrap = |env, krate| { std::env::set_var("RUSTC_BOOTSTRAP", env); matches!(UnstableFeatures::from_environment(krate), UnstableFeatures::Cheat) }; assert!(is_bootstrap("1", None)); assert!(is_bootstrap("1", Some("x"))); // RUSTC_BOOTST...
use super::UnstableFeatures;
random_line_split
tests.rs
use super::UnstableFeatures; #[test] fn
() { let is_bootstrap = |env, krate| { std::env::set_var("RUSTC_BOOTSTRAP", env); matches!(UnstableFeatures::from_environment(krate), UnstableFeatures::Cheat) }; assert!(is_bootstrap("1", None)); assert!(is_bootstrap("1", Some("x"))); // RUSTC_BOOTSTRAP allows specifying a specific c...
rustc_bootstrap_parsing
identifier_name
tests.rs
use super::UnstableFeatures; #[test] fn rustc_bootstrap_parsing()
{ let is_bootstrap = |env, krate| { std::env::set_var("RUSTC_BOOTSTRAP", env); matches!(UnstableFeatures::from_environment(krate), UnstableFeatures::Cheat) }; assert!(is_bootstrap("1", None)); assert!(is_bootstrap("1", Some("x"))); // RUSTC_BOOTSTRAP allows specifying a specific crat...
identifier_body
identity.js
var reddit = require('../index.js'); reddit.prototype.me = function(callback) { var self = this; this._apiRequest("me", {"version": 1}, function(err, response, body) { self._rawJSON(err, body, callback); }); };
callback = prefs; prefs = []; } var self = this; this._apiRequest("prefs", {"path": "/api/v1/me", "qs": {"fields": prefs.join(',')}}, function(err, response, body) { self._rawJSON(err, body, callback); }); }; reddit.prototype.trophies = function(callback) { var self = this; this._apiRequest("trophies", {...
reddit.prototype.getPrefs = function(prefs, callback) { if(typeof prefs == 'function') {
random_line_split
identity.js
var reddit = require('../index.js'); reddit.prototype.me = function(callback) { var self = this; this._apiRequest("me", {"version": 1}, function(err, response, body) { self._rawJSON(err, body, callback); }); }; reddit.prototype.getPrefs = function(prefs, callback) { if(typeof prefs == 'function')
var self = this; this._apiRequest("prefs", {"path": "/api/v1/me", "qs": {"fields": prefs.join(',')}}, function(err, response, body) { self._rawJSON(err, body, callback); }); }; reddit.prototype.trophies = function(callback) { var self = this; this._apiRequest("trophies", {"path": "/api/v1/me"}, function(err,...
{ callback = prefs; prefs = []; }
conditional_block
utils.rs
#![allow(dead_code)] extern crate ffigen; pub const HEAD: &'static str = "//! ffigen generate. #![allow(dead_code)] #![allow(non_snake_case)] #![allow(unused_attributes)] #![allow(non_camel_case_types)] #![allow(non_upper_case_globals)] use libc::*;"; pub const TAIL: &'static str = r#"#[link(name="test")] extern "C...
.arg(&format!("-I{}", ffigen::find_clang_include_path().to_string_lossy())) $( .header(&format!("{}/tests/headers/{}", env!("PWD"), $h)) )* .link($l) .format($f) .gen() }; ( $l:expr, $h:expr ) => { gen!($l, [$h], true) }; ...
( $l:expr, [ $( $h:expr ),* ], $f:expr ) => { GenOptions::default()
random_line_split
models.py
# -*- coding: utf-8 -*- """ {{ project_name }}.libs.common.models ~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains all models that can be used across apps :copyright: (c) 2015 """ from django.db import models from django.utils.translation import ugettext_lazy as _ from .utils.text import slugify clas...
slug. If the slug dosen't exist, return None. :param slug: the slug value to search for """ try: return cls.objects.get(slug=slug) except cls.DoesNotExist: return None def base_slug_value(self): """ As a subclass of :class:`{{ projec...
""" A base class for any model that wants to implement an auto generated slug field. """ # how many times we'll retry creating a slug before giving up MAX_RETRIES = 100 slug = models.SlugField(_('slug'), max_length=255, unique=True) class Meta: abstract = True @classmethod ...
identifier_body
models.py
# -*- coding: utf-8 -*- """ {{ project_name }}.libs.common.models ~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains all models that can be used across apps :copyright: (c) 2015 """ from django.db import models from django.utils.translation import ugettext_lazy as _ from .utils.text import slugify clas...
return super(SlugModel, self).save(*args, **kwargs)
self.slug = self.generate_slug()
conditional_block
models.py
# -*- coding: utf-8 -*- """ {{ project_name }}.libs.common.models ~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains all models that can be used across apps
from .utils.text import slugify class SlugModel(models.Model): """ A base class for any model that wants to implement an auto generated slug field. """ # how many times we'll retry creating a slug before giving up MAX_RETRIES = 100 slug = models.SlugField(_('slug'), max_length=255, unique=...
:copyright: (c) 2015 """ from django.db import models from django.utils.translation import ugettext_lazy as _
random_line_split
models.py
# -*- coding: utf-8 -*- """ {{ project_name }}.libs.common.models ~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains all models that can be used across apps :copyright: (c) 2015 """ from django.db import models from django.utils.translation import ugettext_lazy as _ from .utils.text import slugify clas...
(self, value=None): """ Create a slug based on the value of :method:`{{ project_name }}.libs.common.models.SlugModel.base_slug_value`, ensure that the slug is unique by comparing it to existing slugs. """ if value is None: value = self.base_slug_value() ...
generate_slug
identifier_name
package.js
Package.describe({ name: 'waeltken:leaflet', version: '0.0.1', // Brief, one-line summary of the package. summary: 'Simple package for leaflet v1.0.0-beta.1', // URL to the Git repository containing the source code for this package. git: '', // By default, Meteor will default to using README.md for docume...
'dist/images/marker-icon-2x.png', 'dist/images/marker-icon.png', 'dist/images/marker-shadow.png' ], 'client', {isAsset: true}); });
'dist/images/layers-2x.png', 'dist/images/layers.png',
random_line_split
mod.rs
extern crate libc; pub mod job_control; pub mod signals; use libc::{c_int, pid_t, sighandler_t}; use std::io; use std::os::unix::io::RawFd; pub(crate) const PATH_SEPARATOR: &str = ":"; pub(crate) const O_CLOEXEC: usize = libc::O_CLOEXEC as usize; pub(crate) const SIGHUP: i32 = libc::SIGHUP; pub(crate) const SIGINT:...
pub(crate) fn killpg(pgid: u32, signal: i32) -> io::Result<()> { cvt(unsafe { libc::kill(-(pgid as pid_t), signal as c_int) }).and(Ok(())) } pub(crate) fn pipe2(flags: usize) -> io::Result<(RawFd, RawFd)> { let mut fds = [0; 2]; #[cfg(not(target_os = "macos"))] cvt(unsafe { libc::pipe2(fds.as_mut_pt...
{ cvt(unsafe { libc::kill(pid as pid_t, signal as c_int) }).and(Ok(())) }
identifier_body
mod.rs
extern crate libc; pub mod job_control; pub mod signals; use libc::{c_int, pid_t, sighandler_t}; use std::io; use std::os::unix::io::RawFd; pub(crate) const PATH_SEPARATOR: &str = ":"; pub(crate) const O_CLOEXEC: usize = libc::O_CLOEXEC as usize; pub(crate) const SIGHUP: i32 = libc::SIGHUP; pub(crate) const SIGINT:...
pub(crate) fn getpid() -> io::Result<u32> { cvt(unsafe { libc::getpid() }).map(|pid| pid as u32) } pub(crate) fn kill(pid: u32, signal: i32) -> io::Result<()> { cvt(unsafe { libc::kill(pid as pid_t, signal as c_int) }).and(Ok(())) } pub(crate) fn killpg(pgid: u32, signal: i32) -> io::Result<()> { cvt(unsafe {...
pub unsafe fn fork() -> io::Result<u32> { cvt(libc::fork()).map(|pid| pid as u32) }
random_line_split
mod.rs
extern crate libc; pub mod job_control; pub mod signals; use libc::{c_int, pid_t, sighandler_t}; use std::io; use std::os::unix::io::RawFd; pub(crate) const PATH_SEPARATOR: &str = ":"; pub(crate) const O_CLOEXEC: usize = libc::O_CLOEXEC as usize; pub(crate) const SIGHUP: i32 = libc::SIGHUP; pub(crate) const SIGINT:...
() -> bool { unsafe { libc::geteuid() == 0 } } pub unsafe fn fork() -> io::Result<u32> { cvt(libc::fork()).map(|pid| pid as u32) } pub(crate) fn getpid() -> io::Result<u32> { cvt(unsafe { libc::getpid() }).map(|pid| pid as u32) } pub(crate) fn kill(pid: u32, signal: i32) -> io::Result<()> { cvt(unsafe { libc::ki...
is_root
identifier_name
mod.rs
extern crate libc; pub mod job_control; pub mod signals; use libc::{c_int, pid_t, sighandler_t}; use std::io; use std::os::unix::io::RawFd; pub(crate) const PATH_SEPARATOR: &str = ":"; pub(crate) const O_CLOEXEC: usize = libc::O_CLOEXEC as usize; pub(crate) const SIGHUP: i32 = libc::SIGHUP; pub(crate) const SIGINT:...
else { Ok(()) } } pub(crate) fn reset_signal(signal: i32) -> io::Result<()> { if unsafe { libc::signal(signal as c_int, libc::SIG_DFL) } == libc::SIG_ERR { Err(io::Error::last_os_error()) } else { Ok(()) } } pub(crate) fn tcsetpgrp(fd: RawFd, pgrp: u32) -> io::Result<()> { ...
{ Err(io::Error::last_os_error()) }
conditional_block
amplifyjs-tests.ts
/// <reference types="jquery" /> import amplify = require("amplify"); // Copied examples directly from AmplifyJs site // Subscribe and publish with no data amplify.subscribe("nodataexample", function () { alert("nodataexample topic published!"); }); // Subscribe and publish with data amplify.publish("nodataex...
myStoredValue2 = amplify.store("storeExample2"), myStoredValues = amplify.store(); myStoredValue.foo; // bar myStoredValue2; // baz myStoredValues.storeExample1.foo; // bar myStoredValues.storeExample2; // baz // Store data explicitly with session storage amplify.store.sessionStorage("explicitExample", { foo2...
amplify.store("storeExample2", "baz"); // retrieve the data later via the key var myStoredValue = amplify.store("storeExample1"),
random_line_split
amplifyjs-tests.ts
/// <reference types="jquery" /> import amplify = require("amplify"); // Copied examples directly from AmplifyJs site // Subscribe and publish with no data amplify.subscribe("nodataexample", function () { alert("nodataexample topic published!"); }); // Subscribe and publish with data amplify.publish("nodatae...
} }); amplify.request({ resourceId: "decoderSingleExample", success: function (data) { data.foo; // bar }, error: function (message, level) { alert("always handle errors with alerts."); } }); // Handling Status // Status in Success and Error Callbacks // amplify.request comes ...
{ error(data.message, "fatal"); }
conditional_block
conf.py
# you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES ...
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag refer...
# If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True
random_line_split
index.tsx
import "babel-polyfill"; import "isomorphic-fetch"; import * as injectTapEventPlugin from "react-tap-event-plugin"; injectTapEventPlugin(); import "@accounts/react-material-ui"; import thunk from "redux-thunk"; import { bootstrap } from "@redux-bootstrap/bootstrap"; import { createLogger } from "redux-logger...
let preloadedState: any = null; if (typeof __PRELOADED_STATE__ === 'undefined') { // use state from server side preloadedState = loadState(); } else { // use state from localstorage or server side preloadedState = loadState() || __PRELOADED_STATE__; } let result = bootstrap({ contai...
{ middleware.push(createLogger({level: "log"})); //middleware.push(immutableStateInvariant()); }
conditional_block