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
const-block-non-item-statement-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 ...
() {}
main
identifier_name
const-block-non-item-statement-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 ...
{}
identifier_body
const-block-non-item-statement-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.
// <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. const A: usize = { 1; 2 }; //~^ ERROR statements in constants are unstable const B: usize = { { } 2 }; //~^ ERROR statements in constants are unstable m...
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
lib.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! FFI bindings to d3d9. #![cfg(windows)] extern crate winapi; use winapi::*; #[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm"))]
extern "system" { pub fn D3DPERF_BeginEvent(col: D3DCOLOR, wszName: LPCWSTR) -> INT; pub fn D3DPERF_EndEvent() -> INT; pub fn D3DPERF_GetStatus() -> DWORD; pub fn D3DPERF_QueryRepeatFrame() -> BOOL; pub fn D3DPERF_SetMarker(col: D3DCOLOR, wszName: LPCWSTR) -> (); pub fn D3DPERF_SetOptions(dwOpti...
random_line_split
tool_catalog.py
import inspect from biicode.client.shell.biistream import Color class ToolCatalog(dict): def __init__(self, main_class, tools):
def _get_doc_short(self, doc): return doc.split('\n', 1)[0] def print_help(self, out, argv): out.writeln('\nSYNOPSIS:', Color.YELLOW) out.writeln(' $ bii COMMAND [options]') out.writeln('For help about a command:', Color.YELLOW) out.writeln(' $ bii COMMAND --help...
dict.__init__(self) self.main_class = main_class # dict from tool group name to set of classes for c in tools: self[c.group] = c self.show_advanced = False
identifier_body
tool_catalog.py
import inspect from biicode.client.shell.biistream import Color class ToolCatalog(dict): def __init__(self, main_class, tools): dict.__init__(self) self.main_class = main_class # dict from tool group name to set of classes for c in tools: self[c.group] = c self....
out.write('To change verbosity, use options ', Color.YELLOW) out.writeln('--quiet --verbose\n') if not argv or 'all' in argv: out.writeln('--------- Global Commands ----------', Color.YELLOW) for m in inspect.getmembers(self.main_class, predicate=inspect.ismethod): ...
random_line_split
tool_catalog.py
import inspect from biicode.client.shell.biistream import Color class ToolCatalog(dict): def __init__(self, main_class, tools): dict.__init__(self) self.main_class = main_class # dict from tool group name to set of classes for c in tools: self[c.group] = c self....
(self, out, argv): out.writeln('\nSYNOPSIS:', Color.YELLOW) out.writeln(' $ bii COMMAND [options]') out.writeln('For help about a command:', Color.YELLOW) out.writeln(' $ bii COMMAND --help') out.write('To change verbosity, use options ', Color.YELLOW) out.writeln('...
print_help
identifier_name
tool_catalog.py
import inspect from biicode.client.shell.biistream import Color class ToolCatalog(dict): def __init__(self, main_class, tools): dict.__init__(self) self.main_class = main_class # dict from tool group name to set of classes for c in tools: self[c.group] = c self....
if group not in argv and 'all' not in argv: continue out.writeln('---------%s--------' % class_.__doc__, Color.YELLOW) for m in inspect.getmembers(class_, predicate=inspect.ismethod): method_name = m[0] method = m[1] ...
conditional_block
cli.py
# coding: utf-8 # Copyright 2014-2015 Álvaro Justen <https://github.com/turicas/rows/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at yo...
input_encoding, output_encoding, input_locale, output_locale, keys, sources, destination): keys = [key.strip() for key in keys.split(',')] input_locale = input_locale.split('.') output_locale = output_locale.split('.') with rows.locale_context(input_locale): tables = [import_from_uri(s...
oin(
identifier_name
cli.py
# coding: utf-8 # Copyright 2014-2015 Álvaro Justen <https://github.com/turicas/rows/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at yo...
@click.group() def cli(): pass @cli.command(help='Convert table on `source` URI to `destination`') @click.option('--input-encoding', default='utf-8') @click.option('--output-encoding', default='utf-8') @click.option('--input-locale', default='en_US.UTF-8') @click.option('--output-locale', default='en_US.UTF-8') @...
from rows.utils import import_from_uri, export_to_uri
random_line_split
cli.py
# coding: utf-8 # Copyright 2014-2015 Álvaro Justen <https://github.com/turicas/rows/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at yo...
with rows.locale_context(output_locale): export_to_uri(destination, result) if __name__ == '__main__': cli()
esult = result + table
conditional_block
cli.py
# coding: utf-8 # Copyright 2014-2015 Álvaro Justen <https://github.com/turicas/rows/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at yo...
if __name__ == '__main__': cli()
nput_locale = input_locale.split('.') output_locale = output_locale.split('.') with rows.locale_context(input_locale): tables = [import_from_uri(source) for source in sources] result = tables[0] for table in tables[1:]: result = result + table with rows.locale_context(output_local...
identifier_body
interval.js
//{namespace name=backend/config/view/main} /** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Pu...
* @author shopware AG */ Ext.define('Shopware.apps.Base.view.element.Interval', { extend:'Ext.form.field.ComboBox', alias:[ 'widget.base-element-interval' ], queryMode: 'local', forceSelection: false, editable: true, store: [ [0, '{s name=element/interval/empty_value}None...
* @package Base * @subpackage Component * @version $Id$
random_line_split
logging-right-crate.rs
// Copyright 2013-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-MI...
extern crate logging_right_crate; pub fn main() { // this function panicks if logging is turned on logging_right_crate::foo::<int>(); }
random_line_split
logging-right-crate.rs
// Copyright 2013-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-MI...
() { // this function panicks if logging is turned on logging_right_crate::foo::<int>(); }
main
identifier_name
logging-right-crate.rs
// Copyright 2013-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-MI...
{ // this function panicks if logging is turned on logging_right_crate::foo::<int>(); }
identifier_body
file_preview.js
* * Canvas 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, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the imp...
/* * Copyright (C) 2013 - present Instructure, Inc. * * This file is part of Canvas.
random_line_split
file_preview.js
/* * Copyright (C) 2013 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas 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, version 3 of the License. * * Canvas is distribut...
})
{ $('#media_preview').css({ margin: '0', padding: '0', position: 'absolute', top: '50%', left: '50%', '-webkit-transform': 'translate(-50%, -50%)', transform: 'translate(-50%, -50%)' }) }
conditional_block
mod.rs
pub use self::cache::*; pub use self::combiners::*; pub use self::generators::*; pub use self::modifiers::*; pub use self::selectors::*; pub use self::transformers::*; mod cache; mod combiners; mod generators; mod modifiers; mod selectors; mod transformers; /// Base trait for noise functions. /// /// A noise function...
(&self, point: T) -> f64 { M::get(*self, point) } } /// Trait for functions that require a seed before generating their values pub trait Seedable { /// Set the seed for the function implementing the `Seedable` trait fn set_seed(self, seed: u32) -> Self; /// Getter to retrieve the seed from the...
get
identifier_name
mod.rs
pub use self::cache::*; pub use self::combiners::*; pub use self::generators::*; pub use self::modifiers::*; pub use self::selectors::*; pub use self::transformers::*; mod cache; mod combiners; mod generators; mod modifiers; mod selectors; mod transformers; /// Base trait for noise functions. /// /// A noise function...
#[inline] fn get(&self, point: T) -> f64 { M::get(*self, point) } } /// Trait for functions that require a seed before generating their values pub trait Seedable { /// Set the seed for the function implementing the `Seedable` trait fn set_seed(self, seed: u32) -> Self; /// Getter to re...
fn get(&self, point: T) -> f64; } impl<'a, T, M: NoiseFn<T>> NoiseFn<T> for &'a M {
random_line_split
mod.rs
pub use self::cache::*; pub use self::combiners::*; pub use self::generators::*; pub use self::modifiers::*; pub use self::selectors::*; pub use self::transformers::*; mod cache; mod combiners; mod generators; mod modifiers; mod selectors; mod transformers; /// Base trait for noise functions. /// /// A noise function...
} /// Trait for functions that require a seed before generating their values pub trait Seedable { /// Set the seed for the function implementing the `Seedable` trait fn set_seed(self, seed: u32) -> Self; /// Getter to retrieve the seed from the function fn seed(&self) -> u32; }
{ M::get(*self, point) }
identifier_body
example.js
import {Map, View} from 'ol'; import TileLayer from 'ol/layer/Tile'; import {TileJSON as TileJSONSource, OSM as OSMSource, TileArcGISRest as TileArcGISRestSource} from 'ol/source.js'; import {ComparisonTools as ComparisonToolsControl} from '../../src/control.js'; import {HistogramMatching as HistogramMatchingControl} ...
else if(selectedLayer == "arcgis") { newLayer = new TileLayer({ source: new TileArcGISRestSource({ url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer", crossOrigin: 'anonymous' }) }); } olMap.getLayers().setAt(1, newLayer); ccontrol.setRightLaye...
{ newLayer = new TileLayer({ source: new OSMSource() }); }
conditional_block
example.js
import {Map, View} from 'ol'; import TileLayer from 'ol/layer/Tile'; import {TileJSON as TileJSONSource, OSM as OSMSource, TileArcGISRest as TileArcGISRestSource} from 'ol/source.js'; import {ComparisonTools as ComparisonToolsControl} from '../../src/control.js'; import {HistogramMatching as HistogramMatchingControl} ...
var hcontrol = new HistogramMatchingControl({ layer1: layer1, layer2: layer2 }); olMap.addControl(ccontrol); olMap.addControl(hcontrol); ccontrol.setDisplayMode('doubleMap'); window.changeLeftLayer = function() { var selectedLayer = document.getElementById("leftLayerSelect").value; var newLayer; if(select...
random_line_split
linkage-visibility.rs
// Copyright 2013 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 ...
// We're testing linkage visibility; the compiler warns us, but we want to // do the runtime check that these functions aren't exported. #![allow(private_no_mangle_fns)] use std::dynamic_lib::DynamicLibrary; #[no_mangle] pub fn foo() { bar(); } pub fn foo2<T>() { fn bar2() { bar(); } bar2(); } ...
random_line_split
linkage-visibility.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn test() { let lib = DynamicLibrary::open(None).unwrap(); unsafe { assert!(lib.symbol::<isize>("foo").is_ok()); assert!(lib.symbol::<isize>("baz").is_err()); assert!(lib.symbol::<isize>("bar").is_err()); } }
{ }
identifier_body
linkage-visibility.rs
// Copyright 2013 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 ...
() { } #[allow(dead_code)] #[no_mangle] fn baz() { } pub fn test() { let lib = DynamicLibrary::open(None).unwrap(); unsafe { assert!(lib.symbol::<isize>("foo").is_ok()); assert!(lib.symbol::<isize>("baz").is_err()); assert!(lib.symbol::<isize>("bar").is_err()); } }
bar
identifier_name
weak_lang_items.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 ...
tcx.sess.err(&format!("language item required, but not found: `{}`", stringify!($name))); } } )* } impl<'a, 'tcx> Context<'a, 'tcx> { fn register(&mut self, name: &str, span: Span) { $(if name == stringify!($name) { i...
} else if lang_items::$item == lang_items::OomLangItem { tcx.sess.err(&format!("`#[alloc_error_handler]` function required, \ but not found")); } else {
random_line_split
floatfns.rs
defined later simple_float_op!("cos", cos, "Return the cosine of ARG."); simple_float_op!("sin", sin, "Return the sine of ARG."); simple_float_op!("tan", tan, "Return the tangent of ARG."); simple_float_op!("exp", exp, "Return the exponential base e of ARG."); simple_float_op!("sqrt", sqrt, "Return the square root of...
/// Return the exponential ARG1 ** ARG2. #[lisp_fn] pub fn expt(arg1: LispObject, arg2: LispObject) -> LispObject { if let (Some(x), Some(y)) = (arg1.as_fixnum(), arg2.as_fixnum()) { if y >= 0 && y <= u32::max_value() as EmacsInt { return LispObject::from_fixnum(x.pow(y as u32)); } ...
{ let exponent = exponent.as_fixnum_or_error(); let significand = sgnfcand.any_to_float_or_error(); let result = libm::ldexp(significand, exponent as libc::c_int); LispObject::from_float(result) }
identifier_body
floatfns.rs
defined later simple_float_op!("cos", cos, "Return the cosine of ARG."); simple_float_op!("sin", sin, "Return the sine of ARG."); simple_float_op!("tan", tan, "Return the tangent of ARG."); simple_float_op!("exp", exp, "Return the exponential base e of ARG."); simple_float_op!("sqrt", sqrt, "Return the square root of...
pub fn fceiling(arg: LispObject) -> LispObject { let d = arg.as_float_or_error(); LispObject::from_float(d.ceil()) } /// Return the largest integer no greater than ARG, as a float. /// (Round toward -inf.) #[lisp_fn] pub fn ffloor(arg: LispObject) -> LispObject { let d = arg.as_float_or_error(); LispOb...
/// Return the smallest integer no less than ARG, as a float. /// (Round toward +inf.) #[lisp_fn]
random_line_split
floatfns.rs
defined later simple_float_op!("cos", cos, "Return the cosine of ARG."); simple_float_op!("sin", sin, "Return the sine of ARG."); simple_float_op!("tan", tan, "Return the tangent of ARG."); simple_float_op!("exp", exp, "Return the exponential base e of ARG."); simple_float_op!("sqrt", sqrt, "Return the square root of...
else if args.len() == 1 { -next } else { next } } } ArithOp::Mult => accum *= next, ArithOp::Div => if args.len() > 1 && argnum == 0 { accum = next; } ...
{ accum - next }
conditional_block
floatfns.rs
d.log10() } else if base == 2.0 { d.log2() } else { d.log(base) } }; LispObject::from_float(res) } /* These functions take only floats now. */ /// Return the smallest integer no less than ARG, as a float. /// (Round toward +inf.) #[lisp_fn] pub fn fceiling(arg:...
truncate2
identifier_name
coverage.js
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. 'use strict';
var should = require('should'); var http = require('http'); var util = require('util'); var assert = require('assert'); var _ = require('underscore') var msRest = require('ms-rest'); var msRestAzure = require('ms-rest-azure'); var reportClient = require('../Expected/AcceptanceTests/AzureReport/AutoRestReportServiceF...
random_line_split
coverage.js
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. 'use strict'; var should = require('should'); var http = require('http'); var util = require('util'); var assert = require('assert'); var _ = require('underscor...
lse { console.log('No coverage for scenario: ' + item + '\n'); } }); var result = Math.floor((passed / total) * 100); console.log('Passed: ' + passed + ', Total: ' + total + ', coverage: ' + result + '% .'); result.should.equal(100); done(); }); })...
passed++; } e
conditional_block
oxgui.py
import numpy as np from pygmin import gui import oxdnagmin_ as GMIN import pygmin.gui.run as gr from pygmin.utils.rbtools import CoordsAdapter from pygmin import takestep from pygmin.utils import rotations from pygmin.potentials import GMINPotential from pygmin.transition_states import NEB, InterpolatedPath from pygmin...
(RBSystem): def setup_aatopology(self): GMIN.initialize() pot = GMINPotential(GMIN) coords = pot.getCoords() nrigid = coords.size / 6 print "I have %d water molecules in the system"%nrigid print "The initial energy is", pot.getEnergy(coords) wat...
OXDNASystem
identifier_name
oxgui.py
import numpy as np from pygmin import gui import oxdnagmin_ as GMIN import pygmin.gui.run as gr from pygmin.utils.rbtools import CoordsAdapter from pygmin import takestep from pygmin.utils import rotations from pygmin.potentials import GMINPotential from pygmin.transition_states import NEB, InterpolatedPath from pygmin...
import sys from OpenGL.GLUT import glutInit from PyQt4.QtGui import QApplication import pickle glutInit() app = QApplication(sys.argv) from pygmin.gui.neb_explorer import NEBExplorer system = OXDNASystem() wnd = NEBExplorer(None, system, app) wnd.show() path = pick...
conditional_block
oxgui.py
import numpy as np from pygmin import gui import oxdnagmin_ as GMIN import pygmin.gui.run as gr from pygmin.utils.rbtools import CoordsAdapter from pygmin import takestep from pygmin.utils import rotations from pygmin.potentials import GMINPotential from pygmin.transition_states import NEB, InterpolatedPath from pygmin...
self.draw_bonds.append((2*i, 2*i+1)) self.draw_bonds.append((2*i, 2*i+2)) return system def get_potential(self): return self.potential # def get_mindist(self): # mindist = RBSystem.get_mindist(self) # mindist.transform if __name__ ==...
GMIN.initialize() pot = GMINPotential(GMIN) coords = pot.getCoords() nrigid = coords.size / 6 print "I have %d water molecules in the system"%nrigid print "The initial energy is", pot.getEnergy(coords) water = create_base() system = RBTopology()...
identifier_body
oxgui.py
import numpy as np from pygmin import gui import oxdnagmin_ as GMIN import pygmin.gui.run as gr from pygmin.utils.rbtools import CoordsAdapter from pygmin import takestep from pygmin.utils import rotations from pygmin.potentials import GMINPotential from pygmin.transition_states import NEB, InterpolatedPath from pygmin...
sys.exit(app.exec_()) #gr.run_gui(OXDNASystem, db="oxdna.sqlite")
wnd = NEBExplorer(None, system, app) wnd.show() path = pickle.load(open("interpolate.pickle")) wnd.new_neb(path[0], path[-1], path=path, run=False)
random_line_split
Search.js
import React from 'react' import {Observable} from 'rx' import {TextField} from 'material-ui' import ThemeManager from 'material-ui/lib/styles/theme-manager'; import MyRawTheme from '../components/Theme.js'; import ThemeDecorator from 'material-ui/lib/styles/theme-decorator'; import {compose} from 'recompose' import...
</View> </View> )) export default Search
children={`${result.title} - ${result.artist}`} /> )}
random_line_split
forms.py
# Author: Martin Oehler <oehler@knopper.net> 2013 # License: GPL V2 from django.forms import ModelForm from django.forms import Form from django.forms import ModelChoiceField from django.forms.widgets import RadioSelect from django.forms.widgets import CheckboxSelectMultiple from django.forms.widgets import TextInput...
class pxelinuxcfgForm(ModelForm): class Meta: model = pxelinuxcfg widgets = { 'configuration': Textarea(attrs={'cols': 80, 'rows': 40}), }
random_line_split
forms.py
# Author: Martin Oehler <oehler@knopper.net> 2013 # License: GPL V2 from django.forms import ModelForm from django.forms import Form from django.forms import ModelChoiceField from django.forms.widgets import RadioSelect from django.forms.widgets import CheckboxSelectMultiple from django.forms.widgets import TextInput...
(ModelForm): class Meta: model = clientGroup class pxelinuxcfgForm(ModelForm): class Meta: model = pxelinuxcfg widgets = { 'configuration': Textarea(attrs={'cols': 80, 'rows': 40}), }
clientGroupForm
identifier_name
forms.py
# Author: Martin Oehler <oehler@knopper.net> 2013 # License: GPL V2 from django.forms import ModelForm from django.forms import Form from django.forms import ModelChoiceField from django.forms.widgets import RadioSelect from django.forms.widgets import CheckboxSelectMultiple from django.forms.widgets import TextInput...
class pxelinuxcfgForm(ModelForm): class Meta: model = pxelinuxcfg widgets = { 'configuration': Textarea(attrs={'cols': 80, 'rows': 40}), }
model = clientGroup
identifier_body
getlangnames.py
# # getlangnames.py # # Copyright (C) 2007 Red Hat, Inc. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later...
import sys sys.path.append("..") import localeinfo import gettext localeInfo = localeinfo.get("en_US.UTF-8") names = {} for k in localeInfo.keys(): found = False for l in localeinfo.expandLangs(k): try: f = open("../po/%s.gmo" %(l,)) except (OSError, IOError): continue ...
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
random_line_split
getlangnames.py
# # getlangnames.py # # Copyright (C) 2007 Red Hat, Inc. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later...
if not found: names[localeInfo[k][0]] = localeInfo[k][0] nameList = names.keys() nameList.sort() for k in nameList: print("%s\t%s" % (k, names[k]))
try: f = open("../po/%s.gmo" %(l,)) except (OSError, IOError): continue cat = gettext.GNUTranslations(f) cat.set_output_charset("utf-8") names[localeInfo[k][0]] = cat.lgettext(localeInfo[k][0]) found = True break
conditional_block
Gruntfile.js
] } }, // The actual grunt server settings connect: { options: { port: 9000, // Change this to '0.0.0.0' to access the server from outside. hostname: 'localhost', livereload: 35729 }, livereload: { options: { open: true, m...
{ return grunt.task.run(['build', 'connect:dist:keepalive']); }
conditional_block
Gruntfile.js
'] }, styles: { files: ['<%= yeoman.app %>/styles/{,*/}*.css'], tasks: ['newer:copy:styles', 'autoprefixer'] }, gruntfile: { files: ['Gruntfile.js'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, ...
src: '{,*/}*.css' }, }, // Run some tasks in parallel to speed up the build process
random_line_split
main.rs
extern crate crypto; use crypto::ripemd160; use crypto::digest::Digest; fn ripemd_str(string: &str) -> String { let mut ripemd = ripemd160::Ripemd160::new(); ripemd.input_str(string); ripemd.result_str() } fn main() { println!("{}", ripemd_str("Rosetta Code")); } #[cfg(test)] mod tests { use sup...
} }
"b0e20b6e3116640286ed3a87a5713079b21f5189");
random_line_split
main.rs
extern crate crypto; use crypto::ripemd160; use crypto::digest::Digest; fn ripemd_str(string: &str) -> String { let mut ripemd = ripemd160::Ripemd160::new(); ripemd.input_str(string); ripemd.result_str() } fn main()
#[cfg(test)] mod tests { use super::ripemd_str; #[test] fn ripemd160() { assert_eq!(ripemd_str("Rosetta Code"), "b3be159860842cebaa7174c8fff0aa9e50a5199f"); assert_eq!(ripemd_str(""), "9c1185a5c5e9fc54612808977ee8f548b2258d31"); assert_eq!(ripemd_str("ABCDEFGHIJ...
{ println!("{}", ripemd_str("Rosetta Code")); }
identifier_body
main.rs
extern crate crypto; use crypto::ripemd160; use crypto::digest::Digest; fn ripemd_str(string: &str) -> String { let mut ripemd = ripemd160::Ripemd160::new(); ripemd.input_str(string); ripemd.result_str() } fn main() { println!("{}", ripemd_str("Rosetta Code")); } #[cfg(test)] mod tests { use sup...
() { assert_eq!(ripemd_str("Rosetta Code"), "b3be159860842cebaa7174c8fff0aa9e50a5199f"); assert_eq!(ripemd_str(""), "9c1185a5c5e9fc54612808977ee8f548b2258d31"); assert_eq!(ripemd_str("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), "b0e20b6...
ripemd160
identifier_name
wsgi.py
""" WSGI config for django_rest_test project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLI...
# Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
# file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
random_line_split
experimentHandler.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Demo of class data.ExperimentHandler """ from psychopy import data, logging from numpy import random logging.console.setLevel(logging.DEBUG) exp = data.ExperimentHandler(name='testExp', version='0.1', extraInfo={'participant':'jwp', 'o...
# then run 3 repeats of a staircase outerLoop = data.TrialHandler(trialList=[], nReps=3, name='stairBlock', method='random') exp.addLoop(outerLoop) for thisRep in outerLoop: # the outer loop doesn't save any data staircase = data.StairHandler(startVal=10, name='staircase', nTrials=5) exp.add...
training.addData('training.rt', random.random() * 0.5 + 0.5) if random.random() > 0.5: training.addData('training.key', 'left') else: training.addData('training.key', 'right') exp.nextEntry()
conditional_block
experimentHandler.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Demo of class data.ExperimentHandler """ from psychopy import data, logging from numpy import random logging.console.setLevel(logging.DEBUG) exp = data.ExperimentHandler(name='testExp', version='0.1', extraInfo={'participant':'jwp', 'o...
seed=100) # this will set the global seed - for the whole exp exp.addLoop(training) # run those trials for trial in training: training.addData('training.rt', random.random() * 0.5 + 0.5) if random.random() > 0.5: training.addData('training.key', 'left') else: training.addDa...
random_line_split
test_optimizers_by_linear_model.py
import unittest import numpy as np import six import chainer from chainer import cuda import chainer.functions as F from chainer import optimizers from chainer import testing from chainer.testing import attr from chainer.testing import condition if cuda.available: cuda.init() class LinearModel(object): UNI...
class TestMomentumSGD(OptimizerTestBase, unittest.TestCase): def create(self): return optimizers.MomentumSGD(0.1) class TestRMSprop(OptimizerTestBase, unittest.TestCase): def create(self): return optimizers.RMSprop(0.1) class TestRMSpropGraves(OptimizerTestBase, unittest.TestCase): de...
def create(self): return optimizers.Adam(0.1)
identifier_body
test_optimizers_by_linear_model.py
import unittest import numpy as np import six import chainer from chainer import cuda import chainer.functions as F from chainer import optimizers from chainer import testing from chainer.testing import attr from chainer.testing import condition if cuda.available: cuda.init() class LinearModel(object): UNI...
(self): return optimizers.SGD(0.1) testing.run_module(__name__, __file__)
create
identifier_name
test_optimizers_by_linear_model.py
import unittest import numpy as np import six import chainer from chainer import cuda import chainer.functions as F from chainer import optimizers from chainer import testing from chainer.testing import attr from chainer.testing import condition if cuda.available: cuda.init() class LinearModel(object): UNI...
optimizer.zero_grads() y = model.l(x) loss = F.softmax_cross_entropy(y, t) loss.backward() optimizer.update() x_test, t_test = _make_dataset(self.BATCH_SIZE, self.UNIT_NUM, gpu) y_test = model.l(x_test) return F.accuracy(y_test, t_test...
return x, t for epoch in six.moves.range(self.EPOCH): x, t = _make_dataset(self.BATCH_SIZE, self.UNIT_NUM, gpu)
random_line_split
test_optimizers_by_linear_model.py
import unittest import numpy as np import six import chainer from chainer import cuda import chainer.functions as F from chainer import optimizers from chainer import testing from chainer.testing import attr from chainer.testing import condition if cuda.available: cuda.init() class LinearModel(object): UNI...
x = chainer.Variable(x_data) t = chainer.Variable(t_data) return x, t for epoch in six.moves.range(self.EPOCH): x, t = _make_dataset(self.BATCH_SIZE, self.UNIT_NUM, gpu) optimizer.zero_grads() y = model.l(x) loss = F.softmax_c...
x_data = cuda.to_gpu(x_data) t_data = cuda.to_gpu(t_data)
conditional_block
rellenarFormularioFP.py
#!/usr/bin/python3 # Instalar : # * python3-pdfrw import os from pdfrw import PdfWriter, PdfReader, IndirectPdfDict, PdfName, PdfDict,PdfObject INVOICE_TEMPLATE_PATH = 'templates/9_FP_GM_I_GS_AUTOBIS.pdf' # DOCUMENTO BASE INVOICE_OUTPUT_PATH = 'invoice.pdf' #DESTINO ANNOT_KEY = '/Annots' ANNOT_FIELD_KEY = '/T' ANN...
width =(round(float(rct[2]) - float(rct[0]),2)) xobj = PdfDict( BBox = [0, 0, width, hight], FormType = 1, Resources = PdfDict(ProcSet = [PdfName.PDF, PdfName.Text]), Subtype ...
template_pdf = PdfReader(input_pdf_path) # Para que se vean los campos rellenados template_pdf.Root.AcroForm.update(PdfDict(NeedAppearances=PdfObject('true'))) for page in template_pdf.pages: annotations = page[ANNOT_KEY] for annotation in annotations: if annotation[SUBTYPE_KEY] =...
identifier_body
rellenarFormularioFP.py
#!/usr/bin/python3 # Instalar : # * python3-pdfrw import os from pdfrw import PdfWriter, PdfReader, IndirectPdfDict, PdfName, PdfDict,PdfObject INVOICE_TEMPLATE_PATH = 'templates/9_FP_GM_I_GS_AUTOBIS.pdf' # DOCUMENTO BASE INVOICE_OUTPUT_PATH = 'invoice.pdf' #DESTINO ANNOT_KEY = '/Annots' ANNOT_FIELD_KEY = '/T' ANN...
(input_pdf_path, output_pdf_path, data_dict): template_pdf = PdfReader(input_pdf_path) # Para que se vean los campos rellenados template_pdf.Root.AcroForm.update(PdfDict(NeedAppearances=PdfObject('true'))) for page in template_pdf.pages: annotations = page[ANNOT_KEY] for annotation in an...
write_fillable_pdf
identifier_name
rellenarFormularioFP.py
#!/usr/bin/python3 # Instalar : # * python3-pdfrw import os from pdfrw import PdfWriter, PdfReader, IndirectPdfDict, PdfName, PdfDict,PdfObject INVOICE_TEMPLATE_PATH = 'templates/9_FP_GM_I_GS_AUTOBIS.pdf' # DOCUMENTO BASE INVOICE_OUTPUT_PATH = 'invoice.pdf' #DESTINO ANNOT_KEY = '/Annots' ANNOT_FIELD_KEY = '/T' ANN...
width =(round(float(rct[2]) - float(rct[0]),2)) xobj = PdfDict( BBox = [0, 0, width, hight], FormType = 1, Resources = PdfDict(ProcSet = [PdfName.PDF, PdfName.Text]), Subtype ...
hight = round(float(rct[3]) - float(rct[1]),2)
random_line_split
rellenarFormularioFP.py
#!/usr/bin/python3 # Instalar : # * python3-pdfrw import os from pdfrw import PdfWriter, PdfReader, IndirectPdfDict, PdfName, PdfDict,PdfObject INVOICE_TEMPLATE_PATH = 'templates/9_FP_GM_I_GS_AUTOBIS.pdf' # DOCUMENTO BASE INVOICE_OUTPUT_PATH = 'invoice.pdf' #DESTINO ANNOT_KEY = '/Annots' ANNOT_FIELD_KEY = '/T' ANN...
Type = PdfName.XObject ) #assign a stream to it xobj.stream = '''/Tx BMC BT /Helvetica 8.0 Tf 1.0 5.0 Td 0 g ...
if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY: if annotation[ANNOT_FIELD_KEY]: key = annotation[ANNOT_FIELD_KEY][1:-1] if key in data_dict.keys(): #HACK PARA LOS CHECK - Guardar documento a mano con los checks qu...
conditional_block
test_multi.py
#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # vi:ts=4:et # $Id: test_multi.py,v 1.10 2005/03/11 13:24:45 kjetilja Exp $ import pycurl
m.handles = [] c1 = pycurl.Curl() c2 = pycurl.Curl() c1.setopt(c1.URL, 'http://curl.haxx.se') c2.setopt(c2.URL, 'http://cnn.com') c2.setopt(c2.FOLLOWLOCATION, 1) m.add_handle(c1) m.add_handle(c2) m.handles.append(c1) m.handles.append(c2) num_handles = len(m.handles) while num_handles: while 1: ret, num_han...
m = pycurl.CurlMulti()
random_line_split
test_multi.py
#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # vi:ts=4:et # $Id: test_multi.py,v 1.10 2005/03/11 13:24:45 kjetilja Exp $ import pycurl m = pycurl.CurlMulti() m.handles = [] c1 = pycurl.Curl() c2 = pycurl.Curl() c1.setopt(c1.URL, 'http://curl.haxx.se') c2.setopt(c2.URL, 'http://cnn.com') c2.setopt(c2.FOLLOWLOCA...
m.select(1.0) m.remove_handle(c2) m.remove_handle(c1) del m.handles m.close() c1.close() c2.close()
ret, num_handles = m.perform() if ret != pycurl.E_CALL_MULTI_PERFORM: break
conditional_block
instance.d.ts
import { DateOption, Options, ParsedOptions } from "./options"; import { Locale, CustomLocale, key as LocaleKey } from "./locale"; import { RevFormat, Formats, TokenRegex } from "../utils/formatting"; export interface Elements { element: HTMLElement; input: HTMLInputElement; altInput?: HTMLInputElement; ...
_hidePrevMonthArrow: boolean; _hideNextMonthArrow: boolean; prevMonthNav: HTMLElement; nextMonthNav: HTMLElement; timeContainer?: HTMLDivElement; hourElement?: HTMLInputElement; minuteElement?: HTMLInputElement; secondElement?: HTMLInputElement; amPM?: HTMLSpanElement; } export inter...
currentMonthElement: HTMLSpanElement;
random_line_split
guard.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/. */ //! Machinery to conditionally expose things. use js::jsapi::{HandleObject, JSContext}; use util::prefs::get_pref...
} /// A condition to expose things. pub enum Condition { /// The condition is satisfied if the function returns true. Func(unsafe fn(*mut JSContext, HandleObject) -> bool), /// The condition is satisfied if the preference is set. Pref(&'static str), /// The condition is always satisfied. Satisf...
}
random_line_split
guard.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/. */ //! Machinery to conditionally expose things. use js::jsapi::{HandleObject, JSContext}; use util::prefs::get_pref...
(&self, cx: *mut JSContext, obj: HandleObject) -> Option<T> { if self.condition.is_satisfied(cx, obj) { Some(self.value) } else { None } } } /// A condition to expose things. pub enum Condition { /// The condition is satisfied if the function returns true. Fu...
expose
identifier_name
guard.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/. */ //! Machinery to conditionally expose things. use js::jsapi::{HandleObject, JSContext}; use util::prefs::get_pref...
}
{ match *self { Condition::Pref(name) => get_pref(name).as_boolean().unwrap_or(false), Condition::Func(f) => f(cx, obj), Condition::Satisfied => true, } }
identifier_body
contact.rs
use crate::math::{Point, Vector}; use crate::query::ContactKinematic; use na::{self, RealField, Unit}; use slotmap::Key; use std::mem; slotmap::new_key_type! { /// A contact identifier which is unique within a contact manifold. pub struct ContactId; } /// Geometric description of a contact. #[derive(Debug, Pa...
/// The sine of angular regularization for the first solid. #[inline] pub fn sin_angular1(&self) -> N { self.sin_angular1 } /// The sine angular regularization for the second solid. #[inline] pub fn sin_angular2(&self) -> N { self.sin_angular2 } }
{ self.cos_angular2 }
identifier_body
contact.rs
use crate::math::{Point, Vector}; use crate::query::ContactKinematic; use na::{self, RealField, Unit}; use slotmap::Key; use std::mem; slotmap::new_key_type! { /// A contact identifier which is unique within a contact manifold. pub struct ContactId; } /// Geometric description of a contact. #[derive(Debug, Pa...
(world1: Point<N>, world2: Point<N>, normal: Unit<Vector<N>>) -> Contact<N> { let depth = -normal.dot(&(world2 - world1)); Self::new(world1, world2, normal, depth) } } impl<N: RealField> Contact<N> { /// Reverts the contact normal and swaps `world1` and `world2`. #[inline] pub fn flip(&...
new_wo_depth
identifier_name
contact.rs
use crate::math::{Point, Vector}; use crate::query::ContactKinematic; use na::{self, RealField, Unit}; use slotmap::Key; use std::mem; slotmap::new_key_type! { /// A contact identifier which is unique within a contact manifold. pub struct ContactId; } /// Geometric description of a contact. #[derive(Debug, Pa...
sin_angular2: angular2.sin(), } } /// The linear prediction. #[inline] pub fn linear(&self) -> N { self.linear } /// Sets linear prediction. #[inline] pub fn set_linear(&mut self, val: N) { self.linear = val } /// The angular regularization ...
random_line_split
moves.ts
export const Moves: {[k: string]: ModdedMoveData} = { allyswitch: { inherit: true, priority: 1, }, darkvoid: { inherit: true, accuracy: 80, onTry() {}, }, destinybond: { inherit: true, onPrepareHit(pokemon) { pokemon.removeVolatile('destinybond'); }, }, diamondstorm: { inherit: true, self:...
for (const moveSlot of pokemon.moveSlots) { if (moveSlot.id !== this.effectData.move) { pokemon.disableMove(moveSlot.id); } } }, }, }, fellstinger: { inherit: true, basePower: 30, onAfterMoveSecondarySelf(pokemon, target, move) { if (!target || target.fainted || target.hp <= 0) t...
random_line_split
moves.ts
export const Moves: {[k: string]: ModdedMoveData} = { allyswitch: { inherit: true, priority: 1, }, darkvoid: { inherit: true, accuracy: 80, onTry() {}, }, destinybond: { inherit: true, onPrepareHit(pokemon) { pokemon.removeVolatile('destinybond'); }, }, diamondstorm: { inherit: true, self:...
, }, }, suckerpunch: { inherit: true, basePower: 80, }, swagger: { inherit: true, accuracy: 90, }, tackle: { inherit: true, basePower: 50, }, thousandarrows: { inherit: true, isNonstandard: "Unobtainable", }, thousandwaves: { inherit: true, isNonstandard: "Unobtainable", }, thunderwave...
{ const layers = this.effectData.layers * -1; this.effectData.layers = 0; this.boost({def: layers, spd: layers}, target, target); this.add('-end', target, 'Stockpile'); }
identifier_body
moves.ts
export const Moves: {[k: string]: ModdedMoveData} = { allyswitch: { inherit: true, priority: 1, }, darkvoid: { inherit: true, accuracy: 80, onTry() {}, }, destinybond: { inherit: true, onPrepareHit(pokemon) { pokemon.removeVolatile('destinybond'); }, }, diamondstorm: { inherit: true, self:...
return accuracy; }, }, }, mistyterrain: { inherit: true, condition: { duration: 5, durationCallback(source, effect) { if (source?.hasItem('terrainextender')) { return 8; } return 5; }, onSetStatus(status, target, source, effect) { if (!target.isGrounded() || target.isSem...
{ return true; }
conditional_block
moves.ts
export const Moves: {[k: string]: ModdedMoveData} = { allyswitch: { inherit: true, priority: 1, }, darkvoid: { inherit: true, accuracy: 80, onTry() {}, }, destinybond: { inherit: true, onPrepareHit(pokemon) { pokemon.removeVolatile('destinybond'); }, }, diamondstorm: { inherit: true, self:...
(target, source) { this.add('-singleturn', source, 'Wide Guard'); }, onTryHitPriority: 4, onTryHit(target, source, effect) { // Wide Guard blocks damaging spread moves if ( effect && (effect.category === 'Status' || (effect.target !== 'allAdjacent' && effect.target !== 'allAdjacentFoes'))...
onStart
identifier_name
diagnostics.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
export class NullDiagnosticsService implements IDiagnosticsService { _serviceBrand: undefined; async getPerformanceInfo(mainProcessInfo: IMainProcessInfo, remoteInfo: (IRemoteDiagnosticInfo | IRemoteDiagnosticError)[]): Promise<PerformanceInfo> { return {}; } async getSystemInfo(mainProcessInfo: IMainProcessI...
{ return !!x.hostName && !!x.errorMessage; }
identifier_body
diagnostics.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} export interface SystemInfo extends IMachineInfo { processArgs: string; gpuStatus: any; screenReader: string; remoteData: (IRemoteDiagnosticInfo | IRemoteDiagnosticError)[]; load?: string; } export interface IRemoteDiagnosticInfo extends IDiagnosticInfo { hostName: string; } export interface IRemoteDiagnostic...
random_line_split
diagnostics.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(workspace: IWorkspaceInformation): Promise<void> { } }
reportWorkspaceStats
identifier_name
entities.rs
.twitter.com/overview/api/entities //! [obj]: https://dev.twitter.com/overview/api/entities-in-twitter-objects //! //! ## Entity Ranges //! //! Entities that refer to elements within a text have a `range` field that contains the text span //! that is being referenced. The numbers in question are byte offsets, so if you...
nullable_str
identifier_name
entities.rs
tag, and media information. //! //! These structures are meant to be received in an API call to describe the data they accompany. //! For example, a `UrlEntity` describes a hyperlink in a tweet or user description text, and a //! `HashtagEntity` describes a hashtag or stock symbol extracted from a tweet. //! //! For m...
pub media_type: MediaType, ///The t.co link from the original text. pub url: String, ///For media entities corresponding to videos, this contains extra information about the linked ///video. pub video_info: Option<VideoInfo>, ///Media alt text, if present. pub ext_alt_text: Option<String...
pub source_status_id: Option<u64>, ///The type of media being represented. #[serde(rename = "type")]
random_line_split
FileService.ts
/** * FileUploader.ts * Created by xperiments on 03/06/14. */ ///<reference path="../reference.ts"/> module xp.mdposteditor.services { import DI = xp.mdposteditor.DI; export interface IFileUploaderFile { contents:any; name:string; } export class
{ static $inject = [DI.$http]; constructor( private $http:ng.IHttpService ){} uploadFilesToUrl( uploadUrl:string, contents:IFileUploaderFile[], uploadDir:string, type:string = "image", postPublished:string = "0" ):ng.IPromise<any> { var fd:FormData = new FormData(); fd.append('uploadDir', uploadDir); ...
FileService
identifier_name
FileService.ts
/** * FileUploader.ts * Created by xperiments on 03/06/14. */ ///<reference path="../reference.ts"/> module xp.mdposteditor.services { import DI = xp.mdposteditor.DI; export interface IFileUploaderFile { contents:any;
constructor( private $http:ng.IHttpService ){} uploadFilesToUrl( uploadUrl:string, contents:IFileUploaderFile[], uploadDir:string, type:string = "image", postPublished:string = "0" ):ng.IPromise<any> { var fd:FormData = new FormData(); fd.append('uploadDir', uploadDir); fd.append('type', type); fd.app...
name:string; } export class FileService { static $inject = [DI.$http];
random_line_split
FileService.ts
/** * FileUploader.ts * Created by xperiments on 03/06/14. */ ///<reference path="../reference.ts"/> module xp.mdposteditor.services { import DI = xp.mdposteditor.DI; export interface IFileUploaderFile { contents:any; name:string; } export class FileService { static $inject = [DI.$http]; constructor( p...
getPostFileName( postTile:string ) { return postTile .toLowerCase() // change everything to lowercase .replace(/^\s+|\s+$/g, '') // trim leading and trailing spaces .replace(/[_|\s|\.]+/g, '-') // change all spaces, periods and underscores to a hyphen .replace(/[^a-z\u0400-\u04FF0-9-]+/g, '') //...
{ return this.$http.get('/downloadFile', { params:{ src:source, dst:dest } } ).then( (data)=>{ return data.data; }) }
identifier_body
shampoo.ts
/// <reference path="./typings/promise.d.ts" /> interface Message { type: string; } interface Response extends Message { status: number; message: string; response_data: any; request_id: number; } interface PushMessage extends Message { push_event: string; push_data: any; } interface Reque...
this.eventIndex += 1; evts.push(this.eventIndex); this.events[this.eventIndex] = func; return this.eventIndex; } /** * This binds to push messages by event name. * @param name The event name, this can be anything you like. * @param func Callback function, will ...
{ this.map[name] = evts = []; }
conditional_block
shampoo.ts
/// <reference path="./typings/promise.d.ts" /> interface Message { type: string; } interface Response extends Message { status: number; message: string; response_data: any; request_id: number; } interface PushMessage extends Message { push_event: string; push_data: any; } interface Reque...
(name: string, func: Event) { var evts = this.map[name]; if(!evts) { this.map[name] = evts = []; } this.eventIndex += 1; evts.push(this.eventIndex); this.events[this.eventIndex] = func; return this.eventIndex; } /** * This binds to push...
_on
identifier_name
shampoo.ts
/// <reference path="./typings/promise.d.ts" /> interface Message { type: string; } interface Response extends Message { status: number; message: string; response_data: any; request_id: number; } interface PushMessage extends Message { push_event: string; push_data: any; } interface Reque...
private onPushMessage(data: PushMessage) { let name = data.push_event; this.trigger(`push:${name}`, data.push_data); } /** * Call a method with some data. With Typescript, you can make this * entirely typesafe, how cool is that? * @param method The method name to call. ...
{ this.socket.close(); }
identifier_body
shampoo.ts
/// <reference path="./typings/promise.d.ts" /> interface Message { type: string; } interface Response extends Message { status: number; message: string; response_data: any; request_id: number; } interface PushMessage extends Message { push_event: string; push_data: any; } interface Reque...
socket: WebSocket; ready: boolean = false; private messageMap: MessageMap = {}; private eventIndex: number = 0; private map: EventsMap = {}; private events: eventIndexedEvents = {}; /** * Trigger the event name. If there's nothing to trigger, this'll... well, * just do nothing...
random_line_split
imagevectorsource.js
goog.provide('ol.source.ImageVector'); goog.require('goog.asserts'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.vec.Mat4'); goog.require('ol.dom'); goog.require('ol.extent'); goog.require('ol.render.canvas.ReplayGroup'); goog.require('ol.renderer.vector'); goog.require('ol.s...
var transform = this.getTransform_(ol.extent.getCenter(extent), resolution, pixelRatio, size); replayGroup.replay(this.canvasContext_, pixelRatio, transform, 0, {}); this.replayGroup_ = replayGroup; return this.canvasContext_.canvas; }; /** * @inheritDoc */ ol.source.ImageVector.prototype.forEachF...
{ this.canvasContext_.clearRect(0, 0, size[0], size[1]); }
conditional_block
imagevectorsource.js
goog.provide('ol.source.ImageVector'); goog.require('goog.asserts'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.vec.Mat4'); goog.require('ol.dom'); goog.require('ol.extent'); goog.require('ol.render.canvas.ReplayGroup'); goog.require('ol.renderer.vector'); goog.require('ol.s...
/** * Get the style for features. This returns whatever was passed to the `style` * option at construction or to the `setStyle` method. * @return {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction} * Layer style. * @api stable */ ol.source.ImageVector.prototype.getStyle = function() { return t...
*/ ol.source.ImageVector.prototype.getSource = function() { return this.source_; };
random_line_split
dispatcher.rs
use frame::Frame; use genet_abi::{ context::Context, decoder::{DecoderBox, ExecType, Metadata, WorkerBox}, fixed::MutFixed, layer::{Layer, Parent}, }; use profile::Profile; pub struct Dispatcher { runners: Vec<Runner>, } impl Dispatcher { pub fn new(typ: &ExecType, profile: &Profile) -> Dispat...
} pub fn process_frame(&mut self, frame: &mut Frame) { let mut indices = frame.fetch_tree_indices(); let mut layers = frame.fetch_layers(); let mut offset = 0; let mut runners = self.runners(); loop { let len = layers.len() - offset; for index in ...
pub fn runners(&mut self) -> Vec<OnceRunner> { self.runners .iter_mut() .map(|r| OnceRunner::new(r)) .collect()
random_line_split
dispatcher.rs
use frame::Frame; use genet_abi::{ context::Context, decoder::{DecoderBox, ExecType, Metadata, WorkerBox}, fixed::MutFixed, layer::{Layer, Parent}, }; use profile::Profile; pub struct Dispatcher { runners: Vec<Runner>, } impl Dispatcher { pub fn new(typ: &ExecType, profile: &Profile) -> Dispat...
else { None } } } pub struct OnceRunner<'a> { runner: &'a mut Runner, used: bool, } impl<'a> OnceRunner<'a> { fn new(runner: &'a mut Runner) -> OnceRunner { OnceRunner { runner, used: false, } } fn execute(&mut self, layers: &[MutFi...
{ Some(self.decoder.new_worker(&self.ctx)) }
conditional_block
dispatcher.rs
use frame::Frame; use genet_abi::{ context::Context, decoder::{DecoderBox, ExecType, Metadata, WorkerBox}, fixed::MutFixed, layer::{Layer, Parent}, }; use profile::Profile; pub struct Dispatcher { runners: Vec<Runner>, } impl Dispatcher { pub fn new(typ: &ExecType, profile: &Profile) -> Dispat...
(&mut self) { self.worker = if self.metadata.exec_type == self.typ { Some(self.decoder.new_worker(&self.ctx)) } else { None } } } pub struct OnceRunner<'a> { runner: &'a mut Runner, used: bool, } impl<'a> OnceRunner<'a> { fn new(runner: &'a mut Runner) -...
reset
identifier_name
get-history.py
#! /usr/bin/env python3 """Get historical status data as a CSV file Walks the Git history of the repo, loading each revision where data/ changed, and recording the number of packages for each status. When an existing data file is specified with --update, the file is repeated, with commits that aren't in it appended. ...
tmpdb = os.path.join(tmpclone, 'tmp-portingdb.sqlite') run(['git', 'clone', '.', tmpclone]) prev_data_hash = None prev_batch = [] end_commit = HISTORY_NAMING_END_COMMIT if naming else HISTORY_END_COMMIT for commit in reversed(git_history(end=end_commit)): dat...
excluded = set(BAD_COMMITS) tmpdir = tempfile.mkdtemp() writer = csv.DictWriter(sys.stdout, ['commit', 'date', 'status', 'num_packages'], lineterminator='\n') writer.writeheader() prev_date = None prev_commit = None if update: with...
identifier_body
get-history.py
#! /usr/bin/env python3 """Get historical status data as a CSV file Walks the Git history of the repo, loading each revision where data/ changed, and recording the number of packages for each status. When an existing data file is specified with --update, the file is repeated, with commits that aren't in it appended. ...
(start='HEAD', end=HISTORY_END_COMMIT): """Yield commit IDs along the "main" branch of a project""" args = ['git', 'log', '--pretty=%H', '--first-parent', start, '^' + end] return run(args).strip().splitlines() # Not every commit was tested. Those that wouldn't load # even with the corresponding library v...
git_history
identifier_name
get-history.py
#! /usr/bin/env python3 """Get historical status data as a CSV file Walks the Git history of the repo, loading each revision where data/ changed, and recording the number of packages for each status. When an existing data file is specified with --update, the file is repeated, with commits that aren't in it appended. ...
def git_history(start='HEAD', end=HISTORY_END_COMMIT): """Yield commit IDs along the "main" branch of a project""" args = ['git', 'log', '--pretty=%H', '--first-parent', start, '^' + end] return run(args).strip().splitlines() # Not every commit was tested. Those that wouldn't load # even with the corresp...
kwargs.setdefault('universal_newlines', True) return subprocess.check_output(args, **kwargs)
random_line_split
get-history.py
#! /usr/bin/env python3 """Get historical status data as a CSV file Walks the Git history of the repo, loading each revision where data/ changed, and recording the number of packages for each status. When an existing data file is specified with --update, the file is repeated, with commits that aren't in it appended. ...
prev_batch = [] # Note: we don't remove files that didn't exist in the old # version. run(['git', 'checkout', commit, '--', 'data'], cwd=tmpclone) try: run(['python3', '-m', 'portingdb', '--datadir', tmpdata, ...
prev_commit = commit print('{},{} - skipping'.format(prev_commit, prev_date), file=sys.stderr)
conditional_block
acl.py
# Copyright (C) 2013-2018 Samuel Damashek, Peter Foley, James Forcier, Srijay Kasturi, Reed Koser, Christopher Reffett, and Tris Wilson # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either v...
send(f"{admin.nick} is no longer an {admin.role}.")
send(f"{cmdargs.nick} was not an {cmdargs.role}.") else: session.delete(admin)
random_line_split
acl.py
# Copyright (C) 2013-2018 Samuel Damashek, Peter Foley, James Forcier, Srijay Kasturi, Reed Koser, Christopher Reffett, and Tris Wilson # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either v...
(send, msg, args): """Handles permissions Syntax: {command} (--add|--remove) --nick (nick) --role (admin) """ parser = arguments.ArgParser(args['config']) parser.add_argument('--nick', action=arguments.NickParser, required=True) parser.add_argument('--role', choices=['admin'], required=True) ...
cmd
identifier_name
acl.py
# Copyright (C) 2013-2018 Samuel Damashek, Peter Foley, James Forcier, Srijay Kasturi, Reed Koser, Christopher Reffett, and Tris Wilson # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either v...
if admin is None: send(f"{cmdargs.nick} was not an {cmdargs.role}.") else: session.delete(admin) send(f"{admin.nick} is no longer an {admin.role}.")
conditional_block
acl.py
# Copyright (C) 2013-2018 Samuel Damashek, Peter Foley, James Forcier, Srijay Kasturi, Reed Koser, Christopher Reffett, and Tris Wilson # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either v...
else: send(f"{admin.nick} is already an {admin.role}.") else: if admin is None: send(f"{cmdargs.nick} was not an {cmdargs.role}.") else: session.delete(admin) send(f"{admin.nick} is no longer an {admin.role}.")
"""Handles permissions Syntax: {command} (--add|--remove) --nick (nick) --role (admin) """ parser = arguments.ArgParser(args['config']) parser.add_argument('--nick', action=arguments.NickParser, required=True) parser.add_argument('--role', choices=['admin'], required=True) group = parser.add_mut...
identifier_body
OWSCommon.js
/* Copyright (c) 2006-2015 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Format/XML/VersionedOGC.js */ /** * ...
} return version; }, /** * APIMethod: read * Read an OWSCommon document and return an object. * * Parameters: * data - {String | DOMElement} Data to read. * options - {Object} Options for the reader. * * Returns: * {Object} An object representing th...
{ version = this.defaultVersion; }
conditional_block
OWSCommon.js
/* Copyright (c) 2006-2015 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Format/XML/VersionedOGC.js */ /** * ...
} } return version; }, /** * APIMethod: read * Read an OWSCommon document and return an object. * * Parameters: * data - {String | DOMElement} Data to read. * options - {Object} Options for the reader. * * Returns: * {Object} An object re...
} if(!version) { version = this.defaultVersion;
random_line_split
segmented-bar.d.ts
/** * Contains the SegmentedBar class, which represents a SegmentedBar component. */ declare module "ui/segmented-bar" { import view = require("ui/core/view"); import dependencyObservable = require("ui/core/dependency-observable"); import color = require("color"); import bindable = require("ui/core/bi...
*/ on(event: "selectedIndexChanged", callback: (args: SelectedIndexChangedEventData) => void, thisArg?: any); /** * Called for every child element declared in xml. * @param name - Name of the element. * @param value - Value of the element. */ ...
* Raised when the selected index changes.
random_line_split