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 |
|---|---|---|---|---|
timeout.rs | #[macro_use]
extern crate holmes;
use holmes::simple::*;
use std::time::{Duration, Instant};
// The whole point of this test is to take an excessively long execution
// and make sure it terminates about on time if a limiter is provided
#[test]
pub fn | () {
single(&|holmes: &mut Engine, core: &mut Core| {
// Amount of time holmes gets
let limit = Duration::new(2, 0);
// Wiggle room to shut things down
let wiggle = Duration::new(1, 0);
holmes.limit_time(limit.clone());
let start = Instant::now();
try!(holmes_... | infinity | identifier_name |
cell_renderer_toggle.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Renders a toggle button in a cell
use ffi;
use glib::{to_bool, to_gboolean};
struct... | }
}
impl_drop!(CellRendererToggle);
impl_TraitWidget!(CellRendererToggle);
impl ::CellRendererTrait for CellRendererToggle {} | unsafe {
ffi::gtk_cell_renderer_toggle_set_active(
self.pointer as *mut ffi::C_GtkCellRendererToggle, to_gboolean(active));
} | random_line_split |
cell_renderer_toggle.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Renders a toggle button in a cell
use ffi;
use glib::{to_bool, to_gboolean};
struct... |
pub fn get_radio(&self) -> bool {
unsafe {
to_bool(ffi::gtk_cell_renderer_toggle_get_radio(
self.pointer as *mut ffi::C_GtkCellRendererToggle))
}
}
pub fn set_radio(&self, radio: bool) -> () {
unsafe {
ffi::gtk_cell_renderer_toggle_set_r... | {
let tmp_pointer = unsafe { ffi::gtk_cell_renderer_toggle_new() as *mut ffi::C_GtkWidget };
check_pointer!(tmp_pointer, CellRendererToggle)
} | identifier_body |
cell_renderer_toggle.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Renders a toggle button in a cell
use ffi;
use glib::{to_bool, to_gboolean};
struct... | () -> Option<CellRendererToggle> {
let tmp_pointer = unsafe { ffi::gtk_cell_renderer_toggle_new() as *mut ffi::C_GtkWidget };
check_pointer!(tmp_pointer, CellRendererToggle)
}
pub fn get_radio(&self) -> bool {
unsafe {
to_bool(ffi::gtk_cell_renderer_toggle_get_radio(
... | new | identifier_name |
hipchat.py | import json
from tornado import httpclient as hc
from tornado import gen
from graphite_beacon.handlers import LOGGER, AbstractHandler
class HipChatHandler(AbstractHandler):
name = 'hipchat'
# Default options
defaults = {
'url': 'https://api.hipchat.com',
'room': None,
'key': No... |
@gen.coroutine
def notify(self, level, *args, **kwargs):
LOGGER.debug("Handler (%s) %s", self.name, level)
data = {
'message': self.get_short(level, *args, **kwargs).decode('UTF-8'),
'notify': True,
'color': self.colors.get(level, 'gray'),
'mess... | self.room = self.options.get('room')
self.key = self.options.get('key')
assert self.room, 'Hipchat room is not defined.'
assert self.key, 'Hipchat key is not defined.'
self.client = hc.AsyncHTTPClient() | identifier_body |
hipchat.py | import json
from tornado import httpclient as hc
from tornado import gen
from graphite_beacon.handlers import LOGGER, AbstractHandler
class HipChatHandler(AbstractHandler):
name = 'hipchat'
# Default options
defaults = {
'url': 'https://api.hipchat.com',
'room': None,
'key': No... | (self):
self.room = self.options.get('room')
self.key = self.options.get('key')
assert self.room, 'Hipchat room is not defined.'
assert self.key, 'Hipchat key is not defined.'
self.client = hc.AsyncHTTPClient()
@gen.coroutine
def notify(self, level, *args, **kwargs):
... | init_handler | identifier_name |
hipchat.py | import json
from tornado import httpclient as hc |
class HipChatHandler(AbstractHandler):
name = 'hipchat'
# Default options
defaults = {
'url': 'https://api.hipchat.com',
'room': None,
'key': None,
}
colors = {
'critical': 'red',
'warning': 'yellow',
'normal': 'green',
}
def init_handler(... | from tornado import gen
from graphite_beacon.handlers import LOGGER, AbstractHandler
| random_line_split |
sendfn-generic-fn.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 spawn<A:Copy,B:Copy>(f: extern fn(&~fn(A,B)->Pair<A,B>)) {
let arg: ~fn(A, B) -> Pair<A,B> = |a, b| make_generic_record(a, b);
task::spawn(|| f(&arg));
}
fn test05() {
spawn::<float,~str>(test05_start);
} | random_line_split | |
sendfn-generic-fn.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 ... | (f: &~fn(v: float, v: ~str) -> Pair<float, ~str>) {
let p = (*f)(22.22f, ~"Hi");
info!(copy p);
assert!(p.a == 22.22f);
assert!(p.b == ~"Hi");
let q = (*f)(44.44f, ~"Ho");
info!(copy q);
assert!(q.a == 44.44f);
assert!(q.b == ~"Ho");
}
fn spawn<A:Copy,B:Copy>(f: extern fn(&~fn(A,B)->Pa... | test05_start | identifier_name |
sendfn-generic-fn.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 ... |
struct Pair<A,B> { a: A, b: B }
fn make_generic_record<A:Copy,B:Copy>(a: A, b: B) -> Pair<A,B> {
return Pair {a: a, b: b};
}
fn test05_start(f: &~fn(v: float, v: ~str) -> Pair<float, ~str>) {
let p = (*f)(22.22f, ~"Hi");
info!(copy p);
assert!(p.a == 22.22f);
assert!(p.b == ~"Hi");
let q = ... | { test05(); } | identifier_body |
location_strategy.d.ts | import { OpaqueToken } from 'angular2/core';
import { UrlChangeListener } from './platform_location';
/**
* `LocationStrategy` is responsible for representing and reading route state
* from the browser's URL. Angular provides two strategies:
* {@link HashLocationStrategy} and {@link PathLocationStrategy} (default).
... | * ])
* class AppCmp {
* // ...
* }
*
* bootstrap(AppCmp, [
* ROUTER_PROVIDERS,
* provide(APP_BASE_HREF, {useValue: '/my/app'})
* ]);
* ```
*/
export declare const APP_BASE_HREF: OpaqueToken; | * @Component({directives: [ROUTER_DIRECTIVES]})
* @RouteConfig([
* {...}, | random_line_split |
grid_test.ts | /// <reference path="grid_astar.ts" />
// create abstract grid representation (no nodes here)
var grid =
[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,... |
}
for (var i = 0; i < visited.length; i++) {
var current = visited[i];
context.fillStyle = "lightgreen";
context.fillRect(current.x*tileSize, current.y*tileSize, tileSize-1, tileSize-1)
}
for (var i = 0; i < path.length; i++) {
var current = path[i];
context.fillStyle = "green";
context.fillRect(curr... | {
if (grid[y][x] == 0) {
context.fillStyle = "#999";
} else {
context.fillStyle = "black";
}
context.fillRect(x*tileSize, y*tileSize, tileSize-1, tileSize-1);
} | conditional_block |
grid_test.ts | /// <reference path="grid_astar.ts" />
// create abstract grid representation (no nodes here)
var grid =
[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,... | (){
//test graph with Manhattan distance
testHeuristic(new grid_astar.ManhattanHeuristic());
} | testManhattan | identifier_name |
grid_test.ts | /// <reference path="grid_astar.ts" />
// create abstract grid representation (no nodes here)
var grid =
[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,... | testHeuristic(new grid_astar.DijkstraHeuristic());
}
function testEuclidean(){
//test graph with Euclidean distance
testHeuristic(new grid_astar.EuclidianHeuristic());
}
function testManhattan(){
//test graph with Manhattan distance
testHeuristic(new grid_astar.ManhattanHeuristic());
} | }
}
function testDijkstra(){
//test graph with no heuristics | random_line_split |
grid_test.ts | /// <reference path="grid_astar.ts" />
// create abstract grid representation (no nodes here)
var grid =
[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,... | {
//test graph with Manhattan distance
testHeuristic(new grid_astar.ManhattanHeuristic());
} | identifier_body | |
module.ts | 'use strict';
import Module from '../Module';
import WebServer from './WebServer';
var packageJson = require('../../package.json');
var servers: { [ name: string ]: WebServer } = {};
class Mod extends Module {
getProvides (name: string, ...args: any[]) {
if (name === 'webserver') {
var serverName: string = (<str... |
}
}
constructor (args: any) {
super(args);
this.consumes = [
{
id: 'ninejs'
}
];
this.provides = [
{
id: 'webserver',
version: packageJson.version
}
];
}
}
var result: Module = new Mod(undefined);
result.on('modulesEnabled', function() {
process.nextTick(function() {
var item:... | {
throw new Error('Must configure at least one webserver. See webserver docs');
} | conditional_block |
module.ts | 'use strict';
import Module from '../Module';
import WebServer from './WebServer';
var packageJson = require('../../package.json');
var servers: { [ name: string ]: WebServer } = {};
class Mod extends Module {
getProvides (name: string, ...args: any[]) {
if (name === 'webserver') {
var serverName: string = (<str... | p: string;
for (p in servers) {
if (servers.hasOwnProperty(p)) {
item = servers[p];
promises.push(item.build());
}
}
});
});
export default result; | process.nextTick(function() {
var item: WebServer, | random_line_split |
module.ts | 'use strict';
import Module from '../Module';
import WebServer from './WebServer';
var packageJson = require('../../package.json');
var servers: { [ name: string ]: WebServer } = {};
class | extends Module {
getProvides (name: string, ...args: any[]) {
if (name === 'webserver') {
var serverName: string = (<string>args[0]) || 'default';
return servers[serverName];
}
}
init (name: string, config: any) {
super.init(name, config);
if (name === 'webserver') {
var p: string,
first: WebSe... | Mod | identifier_name |
module.ts | 'use strict';
import Module from '../Module';
import WebServer from './WebServer';
var packageJson = require('../../package.json');
var servers: { [ name: string ]: WebServer } = {};
class Mod extends Module {
getProvides (name: string, ...args: any[]) {
if (name === 'webserver') {
var serverName: string = (<str... | servers['default'] = first;
}
if (!first) {
throw new Error('Must configure at least one webserver. See webserver docs');
}
}
}
constructor (args: any) {
super(args);
this.consumes = [
{
id: 'ninejs'
}
];
this.provides = [
{
id: 'webserver',
version: packageJson.versio... | {
super.init(name, config);
if (name === 'webserver') {
var p: string,
first: WebServer;
for (p in config) {
if (config.hasOwnProperty(p)) {
var server = new WebServer({});
server.getServer = (name: string) => {
return servers[name];
};
server.set('logger', this.getUnit('nine... | identifier_body |
dragon.rs | 7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6,
0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e,
0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7];
#[doc(hidden)]
pub fn mul_pow10<'a>(x: &'a mut Big, n: usize) -> &'a mut Big {
debug_... | else {
mant.mul_pow2(d.exp as usize);
minus.mul_pow2(d.exp as usize);
plus.mul_pow2(d.exp as usize);
}
// divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`.
if k >= 0 {
mul_pow10(&mut scale, k as usize);
} else {
mul_pow10(&mut mant, -k as us... | {
scale.mul_pow2(-d.exp as usize);
} | conditional_block |
dragon.rs | 7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6,
0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e,
0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7];
#[doc(hidden)]
pub fn mul_pow10<'a>(x: &'a mut Big, n: usize) -> &'a mut Big {
debug_... | <'a>(x: &'a mut Big, scale: &Big,
scale2: &Big, scale4: &Big, scale8: &Big) -> (u8, &'a mut Big) {
let mut d = 0;
if *x >= *scale8 { x.sub(scale8); d += 8; }
if *x >= *scale4 { x.sub(scale4); d += 4; }
if *x >= *scale2 { x.sub(scale2); d += 2; }
if *x >= *scale { x.sub(scale)... | div_rem_upto_16 | identifier_name |
dragon.rs | 7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6,
0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e,
0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7];
#[doc(hidden)]
pub fn mul_pow10<'a>(x: &'a mut Big, n: usize) -> &'a mut Big {
debug_... | } else {
mul_pow10(&mut mant, -k as usize);
mul_pow10(&mut minus, -k as usize);
mul_pow10(&mut plus, -k as usize);
}
// fixup when `mant + plus > scale` (or `>=`).
// we are not actually modifying `scale`, since we can skip the initial multiplication instead.
// now `scale <... | }
// divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`.
if k >= 0 {
mul_pow10(&mut scale, k as usize); | random_line_split |
dragon.rs | assert!(d.mant.checked_add(d.plus).is_some());
assert!(d.mant.checked_sub(d.minus).is_some());
assert!(buf.len() >= MAX_SIG_DIGITS);
// `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}`
let rounding = if d.inclusive {Ordering::Greater} else {Ordering::Equal};
// estimate `k_0` from... | {
assert!(d.mant > 0);
assert!(d.minus > 0);
assert!(d.plus > 0);
assert!(d.mant.checked_add(d.plus).is_some());
assert!(d.mant.checked_sub(d.minus).is_some());
// estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`.
let mut k = estimate_scaling_factor(d.mant, d.ex... | identifier_body | |
VSelectList.ts | // Styles
import '../VCard/VCard.sass'
// Components
import VSimpleCheckbox from '../VCheckbox/VSimpleCheckbox'
import VDivider from '../VDivider'
import VSubheader from '../VSubheader'
import {
VList,
VListItem,
VListItemAction,
VListItemContent,
VListItemTitle,
} from '../VList'
// Directives
import rippl... | (item: object) {
return String(getPropertyFromItem(item, this.itemText, item))
},
getValue (item: object) {
return getPropertyFromItem(item, this.itemValue, this.getText(item))
},
},
render (): VNode {
const children = []
for (const item of this.items) {
if (this.hideSelected... | getText | identifier_name |
VSelectList.ts | // Styles
import '../VCard/VCard.sass'
// Components
import VSimpleCheckbox from '../VCheckbox/VSimpleCheckbox'
import VDivider from '../VDivider'
import VSubheader from '../VSubheader'
import {
VList,
VListItem,
VListItemAction,
VListItemContent,
VListItemTitle,
} from '../VList'
// Directives
import rippl... | slot![0].componentOptions.Ctor.options.name !== 'v-list-item'
},
getDisabled (item: object) {
return Boolean(getPropertyFromItem(item, this.itemDisabled, false))
},
getText (item: object) {
return String(getPropertyFromItem(item, this.itemText, item))
},
getValue (item: objec... | slot![0].componentOptions == null || | random_line_split |
VSelectList.ts | // Styles
import '../VCard/VCard.sass'
// Components
import VSimpleCheckbox from '../VCheckbox/VSimpleCheckbox'
import VDivider from '../VDivider'
import VSubheader from '../VSubheader'
import {
VList,
VListItem,
VListItemAction,
VListItemContent,
VListItemTitle,
} from '../VList'
// Directives
import rippl... | ,
staticNoDataTile (): VNode {
const tile = {
attrs: {
role: undefined,
},
on: {
mousedown: (e: Event) => e.preventDefault(), // Prevent onBlur from being called
},
}
return this.$createElement(VListItem, tile, [
this.genTileContent(this... | {
return Object.keys(this.setTextColor(this.color).class || {}).join(' ')
} | identifier_body |
VSelectList.ts | // Styles
import '../VCard/VCard.sass'
// Components
import VSimpleCheckbox from '../VCheckbox/VSimpleCheckbox'
import VDivider from '../VDivider'
import VSubheader from '../VSubheader'
import {
VList,
VListItem,
VListItemAction,
VListItemContent,
VListItemTitle,
} from '../VList'
// Directives
import rippl... |
const tile = {
attrs: {
// Default behavior in list does not
// contain aria-selected by default
'aria-selected': String(value),
'aria-labelledby': this.genLabelledBy(item),
role: 'option',
},
on: {
mousedown: (e: Event) => {
... | {
disabled = disabled !== null
? disabled
: this.getDisabled(item)
} | conditional_block |
latexexport.py | # -*- coding: utf-8 -*-
# import the main window object (mw) from ankiqt
from aqt import mw
# import the "show info" tool from utils.py
from aqt.utils import showInfo
# import all of the Qt GUI library
from aqt.qt import *
from anki.exporting import *
from anki.hooks import addHook
class LatexNoteExporter(Exporter):
... | where cards.id in %s)""" % ids2str(cardIds)):
latexnote = []
TAB = " "
latexnote.append(r"\begin{note}")
# fields
for f in splitFields(flds):
newf = self.replaceLineBreaks(f)
if newf.find("[latex]") != -1:
... | (select nid from cards | random_line_split |
latexexport.py | # -*- coding: utf-8 -*-
# import the main window object (mw) from ankiqt
from aqt import mw
# import the "show info" tool from utils.py
from aqt.utils import showInfo
# import all of the Qt GUI library
from aqt.qt import *
from anki.exporting import *
from anki.hooks import addHook
class LatexNoteExporter(Exporter):
... |
# tags
if self.includeTags:
cleantag = tags.strip()
if cleantag != "":
latexnote.append(TAB + r"\tags{" + tags.strip() + r"}")
latexnote.append(r"\end{note}" + "\n")
data.append("\n".join(latexnote))
self.count ... | latexnote.pop() | conditional_block |
latexexport.py | # -*- coding: utf-8 -*-
# import the main window object (mw) from ankiqt
from aqt import mw
# import the "show info" tool from utils.py
from aqt.utils import showInfo
# import all of the Qt GUI library
from aqt.qt import *
from anki.exporting import *
from anki.hooks import addHook
class LatexNoteExporter(Exporter):
... | return text
def stripNewLines(self,text):
"Remove newlines at beginning and end of text, and replace double blank lines by single blank lines"
text = re.sub("\n\s*\n+","\n\n",text).strip()
#the following is superfluous as its done automatically by strip()
#while len(text... | key = _("Notes in Latex")
ext = ".tex"
def __init__(self, col):
Exporter.__init__(self, col)
self.includeID = True
self.includeTags = True
def replaceLineBreaks(self,text):
"Replace html-line breaks by plain-text line breaks"
#remove plain-text line breaks (most pro... | identifier_body |
latexexport.py | # -*- coding: utf-8 -*-
# import the main window object (mw) from ankiqt
from aqt import mw
# import the "show info" tool from utils.py
from aqt.utils import showInfo
# import all of the Qt GUI library
from aqt.qt import *
from anki.exporting import *
from anki.hooks import addHook
class LatexNoteExporter(Exporter):
... | (self,text):
"Replace html-line breaks by plain-text line breaks"
#remove plain-text line breaks (most probobly there aren't any to begin with)
text = text.replace("\n","")
#convert some html
htmldict = {r"<br>":"\n",
r"<br />":"\n",
r"<div... | replaceLineBreaks | identifier_name |
parse.js | 'use strict'
const _toArray = require('lodash.toarray')
const shelljs = require('shelljs')
module.exports = function (config) {
// parse loader
[
'loaders',
'preLoaders',
'postLoaders'
].forEach(key => {
config.module[key] = _toArray(config.module[key])
})
// parse plugin
config.plugins = ... |
// update path
config.output.publicPath = config.devServer.publicPath || config.output.publicPath || '/'
}
// load hot loader
config.entry = require('./hot-reload')(
config.entry,
process.env.NODE_ENV === 'development' ? config.devServer : false
)
if (config.__XDC_CLEAN__) {
shelljs.rm(... | } | random_line_split |
parse.js | 'use strict'
const _toArray = require('lodash.toarray')
const shelljs = require('shelljs')
module.exports = function (config) {
// parse loader
[
'loaders',
'preLoaders',
'postLoaders'
].forEach(key => {
config.module[key] = _toArray(config.module[key])
})
// parse plugin
config.plugins = ... |
return config
}
| {
shelljs.rm('-rf', config.output.path)
} | conditional_block |
mod.rs | use crate::{config::WorkMode, env::Env, file_saver::*};
use std::path::Path;
mod alias;
mod child_properties;
mod constants;
mod doc;
mod enums;
mod flags;
pub mod function;
mod function_body_chunk;
mod functions;
mod general;
mod object;
mod objects;
mod parameter;
mod properties;
mod property_body;
mod record;
mod r... | records::generate(env, root_path, &mut mod_rs);
enums::generate(env, root_path, &mut mod_rs);
flags::generate(env, root_path, &mut mod_rs);
alias::generate(env, root_path, &mut mod_rs);
functions::generate(env, root_path, &mut mod_rs);
constants::generate(env, root_path, &mut mod_rs);
gener... | generate_single_version_file(env);
objects::generate(env, root_path, &mut mod_rs, &mut traits); | random_line_split |
mod.rs | use crate::{config::WorkMode, env::Env, file_saver::*};
use std::path::Path;
mod alias;
mod child_properties;
mod constants;
mod doc;
mod enums;
mod flags;
pub mod function;
mod function_body_chunk;
mod functions;
mod general;
mod object;
mod objects;
mod parameter;
mod properties;
mod property_body;
mod record;
mod r... | (env: &Env) {
if let Some(ref path) = env.config.single_version_file {
save_to_file(path, env.config.make_backup, |w| {
general::single_version_file(w, &env.config)
});
}
}
| generate_single_version_file | identifier_name |
mod.rs | use crate::{config::WorkMode, env::Env, file_saver::*};
use std::path::Path;
mod alias;
mod child_properties;
mod constants;
mod doc;
mod enums;
mod flags;
pub mod function;
mod function_body_chunk;
mod functions;
mod general;
mod object;
mod objects;
mod parameter;
mod properties;
mod property_body;
mod record;
mod r... |
pub fn generate_mod_rs(env: &Env, root_path: &Path, mod_rs: &[String], traits: &[String]) {
let path = root_path.join("mod.rs");
save_to_file(path, env.config.make_backup, |w| {
general::start_comments(w, &env.config)?;
general::write_vec(w, mod_rs)?;
writeln!(w)?;
writeln!(w, ... | {
let mut mod_rs: Vec<String> = Vec::new();
let mut traits: Vec<String> = Vec::new();
let root_path = env.config.auto_path.as_path();
generate_single_version_file(env);
objects::generate(env, root_path, &mut mod_rs, &mut traits);
records::generate(env, root_path, &mut mod_rs);
enums::genera... | identifier_body |
mod.rs | use crate::{config::WorkMode, env::Env, file_saver::*};
use std::path::Path;
mod alias;
mod child_properties;
mod constants;
mod doc;
mod enums;
mod flags;
pub mod function;
mod function_body_chunk;
mod functions;
mod general;
mod object;
mod objects;
mod parameter;
mod properties;
mod property_body;
mod record;
mod r... |
}
| {
save_to_file(path, env.config.make_backup, |w| {
general::single_version_file(w, &env.config)
});
} | conditional_block |
portal.rs | use app;
use components::*;
use specs::Join;
use specs;
use levels;
#[derive(Clone)]
pub struct Portal {
destination: levels::Level,
}
impl specs::Component for Portal {
type Storage = specs::VecStorage<Self>;
}
impl Portal {
pub fn new(destination: levels::Level) -> Self |
}
pub struct PortalSystem;
impl specs::System<app::UpdateContext> for PortalSystem {
fn run(&mut self, arg: specs::RunArg, context: app::UpdateContext) {
let (grid_squares, players, states, portals, entities) = arg.fetch(|world| {
(
world.read::<GridSquare>(),
w... | {
Portal {
destination: destination,
}
} | identifier_body |
portal.rs | use app;
use components::*;
use specs::Join;
use specs;
use levels;
#[derive(Clone)]
pub struct Portal {
destination: levels::Level,
}
impl specs::Component for Portal {
type Storage = specs::VecStorage<Self>;
}
impl Portal {
pub fn new(destination: levels::Level) -> Self {
Portal {
des... |
}
}
}
}
| {
context.control_tx.send(app::Control::GotoLevel(portal.destination.clone())).unwrap();
} | conditional_block |
portal.rs | use app;
use components::*;
use specs::Join;
use specs;
use levels;
#[derive(Clone)]
pub struct Portal {
destination: levels::Level,
}
impl specs::Component for Portal {
type Storage = specs::VecStorage<Self>;
}
impl Portal {
pub fn new(destination: levels::Level) -> Self {
Portal {
des... | if (player_pos[0] - pos[0]).powi(2) + (player_pos[1] - pos[1]).powi(2) < 0.01 {
context.control_tx.send(app::Control::GotoLevel(portal.destination.clone())).unwrap();
}
}
}
}
} | for (portal,entity) in (&portals, &entities).iter() {
let pos = grid_squares.get(entity).expect("portal expect grid square component").position; | random_line_split |
portal.rs | use app;
use components::*;
use specs::Join;
use specs;
use levels;
#[derive(Clone)]
pub struct | {
destination: levels::Level,
}
impl specs::Component for Portal {
type Storage = specs::VecStorage<Self>;
}
impl Portal {
pub fn new(destination: levels::Level) -> Self {
Portal {
destination: destination,
}
}
}
pub struct PortalSystem;
impl specs::System<app::UpdateContex... | Portal | identifier_name |
usuario-service.service.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http'
import 'rxjs/add/operator/map'
import { GlobalParamsService } from '../global-params.service';
import { UserLogin } from './userLogin';
@Injectable()
export class UsuarioService {
constructor(private _http:Http,
private _globalParams... |
}
| {
return this._http.post(this.domain+'authenticate', userLogin)
.map((res)=>{
// login successful if there's a jwt token in the response
let user = res.json();
if (user && user._id) {
// store user details and jwt token in local storage to keep user logged in bet... | identifier_body |
usuario-service.service.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http'
import 'rxjs/add/operator/map'
import { GlobalParamsService } from '../global-params.service';
import { UserLogin } from './userLogin';
@Injectable()
export class | {
constructor(private _http:Http,
private _globalParams:GlobalParamsService) { }
private apiURL = '/api/usuario/';
private domain=this._globalParams.domain+this.apiURL;
autenticar(userLogin:UserLogin){
return this._http.post(this.domain+'authenticate', userLogin)
.map((res)=>{
// login succe... | UsuarioService | identifier_name |
usuario-service.service.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http'
import 'rxjs/add/operator/map'
import { GlobalParamsService } from '../global-params.service';
import { UserLogin } from './userLogin';
@Injectable()
export class UsuarioService {
constructor(private _http:Http,
private _globalParams... | if (user && user._id) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
return user;
})
}
} | random_line_split | |
usuario-service.service.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http'
import 'rxjs/add/operator/map'
import { GlobalParamsService } from '../global-params.service';
import { UserLogin } from './userLogin';
@Injectable()
export class UsuarioService {
constructor(private _http:Http,
private _globalParams... |
return user;
})
}
}
| {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
} | conditional_block |
__init__.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# | # 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 your option) any later version.
#
# This program is distributed in the hope that it will ... | # Copyright (C) 2016 Didotech srl (<http://www.didotech.com>).
#
# All Rights Reserved
# | random_line_split |
base64.rs | : &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz",
"0123456789-_");
/// A trait for converting a value to base64 encoding.
pub trait ToBase64 {
/// Converts the value of `self` to a base64 value... | * # Example
*
* This converts a string literal to base64 and back.
*
* ```rust
* extern crate serialize;
* use serialize::base64::{ToBase64, FromBase64, STANDARD};
*
* fn main () {
* let hello_str = bytes!("Hello, World").to_base64(STANDARD);
* println!("ba... | * | random_line_split |
base64.rs |
*
* ```rust
* extern crate serialize;
* use serialize::base64::{ToBase64, STANDARD};
*
* fn main () {
* let str = [52,32].to_base64(STANDARD);
* println!("base 64 output: {}", str);
* }
* ```
*/
fn to_base64(&self, config: Config) -> StrBuf {
l... | {
assert_eq!("f".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zg".to_strbuf());
assert_eq!("fo".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zm8".to_strbuf());
} | identifier_body | |
base64.rs | : &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz",
"0123456789-_");
/// A trait for converting a value to base64 encoding.
pub trait ToBase64 {
/// Converts the value of `self` to a base64 value... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
InvalidBase64Character(ch, idx) =>
write!(f, "Invalid character '{}' at position {}", ch, idx),
InvalidBase64Length => write!(f, "Invalid length"),
}
}
}
impl<'a> FromBase64 for &'a str {
/**
... | fmt | identifier_name |
globalSettings.js | // Copyright (c) 2012-2014 Lotaris SA
//
// This file is part of ROX Center.
//
// ROX Center is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later... | // GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with ROX Center. If not, see <http://www.gnu.org/licenses/>.
App.autoModule('globalSettings', function() {
var Settings = Backbone.Model.extend({
url: LegacyApiPath.builder('settings'... | //
// ROX Center 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 | random_line_split |
globalSettings.js | // Copyright (c) 2012-2014 Lotaris SA
//
// This file is part of ROX Center.
//
// ROX Center is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later... | else if (type == 'error') {
$('<span class="text-danger" />').text(I18n.t('jst.globalSettings.error')).insertAfter(this.ui.saveButton).hide().fadeIn('fast');
}
},
requestOptions: function() {
return {
dataType: 'json',
accepts: {
json: 'application/json'
}... | {
$('<span class="text-success" />').text(I18n.t('jst.globalSettings.success')).insertAfter(this.ui.saveButton).hide().fadeIn('fast');
} | conditional_block |
uniform_assigner.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from ..builder import BBOX_ASSIGNERS
from ..iou_calculators import build_iou_calculator
from ..transforms import bbox_xyxy_to_cxcywh
from .assign_result import AssignResult
from .base_assigner import BaseAssigner
@BBOX_ASSIGNERS.register_module()
class Uni... |
else:
assigned_labels = None
assign_result = AssignResult(
num_gts,
assigned_gt_inds,
anchor_max_overlaps,
labels=assigned_labels)
assign_result.set_extra_property('pos_idx', ~pos_ignore_idx)
assign_result.set_extra_property('... | assigned_labels[pos_inds] = gt_labels[
assigned_gt_inds[pos_inds] - 1] | conditional_block |
uniform_assigner.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from ..builder import BBOX_ASSIGNERS
from ..iou_calculators import build_iou_calculator
from ..transforms import bbox_xyxy_to_cxcywh
from .assign_result import AssignResult
from .base_assigner import BaseAssigner
@BBOX_ASSIGNERS.register_module()
class | (BaseAssigner):
"""Uniform Matching between the anchors and gt boxes, which can achieve
balance in positive anchors, and gt_bboxes_ignore was not considered for
now.
Args:
pos_ignore_thr (float): the threshold to ignore positive anchors
neg_ignore_thr (float): the threshold to ignore ne... | UniformAssigner | identifier_name |
uniform_assigner.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from ..builder import BBOX_ASSIGNERS
from ..iou_calculators import build_iou_calculator
from ..transforms import bbox_xyxy_to_cxcywh
from .assign_result import AssignResult
from .base_assigner import BaseAssigner
@BBOX_ASSIGNERS.register_module()
class Uni... | assign_result.set_extra_property('target_boxes',
bbox_pred.new_empty((0, 4)))
return assign_result
# 2. Compute the L1 cost between boxes
# Note that we use anchors and predict boxes both
cost_bbox = torch.cdist(
b... | num_gts, num_bboxes = gt_bboxes.size(0), bbox_pred.size(0)
# 1. assign -1 by default
assigned_gt_inds = bbox_pred.new_full((num_bboxes, ),
0,
dtype=torch.long)
assigned_labels = bbox_pred.new_full((num_b... | identifier_body |
uniform_assigner.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from ..builder import BBOX_ASSIGNERS
from ..iou_calculators import build_iou_calculator
from ..transforms import bbox_xyxy_to_cxcywh
from .assign_result import AssignResult
from .base_assigner import BaseAssigner
@BBOX_ASSIGNERS.register_module()
class Uni... | gt_bboxes[pos_gt_index])
return assign_result | assign_result.set_extra_property('target_boxes', | random_line_split |
lib.rs | 0u8, 1, 2] });
}
// Now, panic while allocating
arena.alloc::<Rc<i32>, _>(|| {
panic!();
});
}
/// A faster arena that can hold objects of only one type.
pub struct TypedArena<T> {
/// A pointer to the next object to be allocated.
ptr: Cell<*const T>,
/// A pointer to the end of th... | {
let arena = TypedArena::new();
b.iter(|| {
arena.alloc(Noncopy {
string: "hello world".to_string(),
array: vec!( 1, 2, 3, 4, 5 ),
})
})
} | identifier_body | |
lib.rs | );
let end = start + n_bytes;
if end > self.chunk_size() {
return self.alloc_copy_grow(n_bytes, align);
}
let copy_head = self.copy_head.borrow();
copy_head.fill.set(end);
unsafe {
copy_head.as_ptr().offset(start as isize)
}
}
#... | {
self.grow()
} | conditional_block | |
lib.rs | Arena {
head: RefCell::new(chunk(initial_size, false)),
copy_head: RefCell::new(chunk(initial_size, true)),
chunks: RefCell::new(Vec::new()),
_marker: marker::PhantomData,
}
}
}
fn chunk(size: usize, is_copy: bool) -> Chunk {
Chunk {
data: Rc::ne... | TypedArena | identifier_name | |
lib.rs | ::new();
// Put some stuff in the arena.
for i in 0..10 {
// Arena allocate something with drop glue to make sure it
// doesn't leak.
arena.alloc(|| { Rc::new(i) });
// Allocate something with funny size and alignment, to keep
// things interesting.
arena.alloc(||... | array: vec!( 1, 2, 3, 4, 5 ),
});
}
}
| random_line_split | |
parsers_cache.py | import os
import pickle
from parsers_backend import get_tree
from directories import dirs
def get_cached_sentence_image(argv, output_path, img_path):
"""Returns if the image is already generated or not, and avoids generating if yes.
Args:
argv: The command line arguments.
output_path: The pa... |
else:
return os.path.isfile(cache_file_final)
def get_cached_tokens(argv):
"""Returns the already parsed sentences containing the word being search, if the folder was not modified.
Args:
argv: The command line arguments.
Returns:
A list of tree.FullSentence objects, the sent... | return False | conditional_block |
parsers_cache.py | import os
import pickle
from parsers_backend import get_tree
from directories import dirs
def get_cached_sentence_image(argv, output_path, img_path):
|
def get_cached_tokens(argv):
"""Returns the already parsed sentences containing the word being search, if the folder was not modified.
Args:
argv: The command line arguments.
Returns:
A list of tree.FullSentence objects, the sentences parsed from the raw text.
"""
updated_at_da... | """Returns if the image is already generated or not, and avoids generating if yes.
Args:
argv: The command line arguments.
output_path: The path for the output folder.
img_path: The path to the image file to be checked.
Returns:
A boolean flagging if image is already generated ... | identifier_body |
parsers_cache.py | import os
import pickle
from parsers_backend import get_tree
from directories import dirs
def get_cached_sentence_image(argv, output_path, img_path):
"""Returns if the image is already generated or not, and avoids generating if yes.
Args:
argv: The command line arguments.
output_path: The pa... |
if argv.tetre_force_clean:
return False
else:
return os.path.isfile(cache_file_final)
def get_cached_tokens(argv):
"""Returns the already parsed sentences containing the word being search, if the folder was not modified.
Args:
argv: The command line arguments.
Returns:
... | random_line_split | |
parsers_cache.py | import os
import pickle
from parsers_backend import get_tree
from directories import dirs
def get_cached_sentence_image(argv, output_path, img_path):
"""Returns if the image is already generated or not, and avoids generating if yes.
Args:
argv: The command line arguments.
output_path: The pa... | (argv):
"""Returns the already parsed sentences containing the word being search, if the folder was not modified.
Args:
argv: The command line arguments.
Returns:
A list of tree.FullSentence objects, the sentences parsed from the raw text.
"""
updated_at_date = os.path.getmtime(di... | get_cached_tokens | identifier_name |
rom_nist256_32.rs | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this f... | pub const AESKEY: usize = 16; | pub const SIGN_OF_X: SignOfX = SignOfX::NOT;
pub const HASH_TYPE: usize = 32; | random_line_split |
DepVar.js | // import React and Redux dependencies
var React = require('react');
var connect = require('react-redux').connect;
var Measure = require('./Measure');
function mapStatetoProps (state, ownProps) |
var DepVar = React.createClass({
render: function () {
var measures = this.props.measureIds.map(function(measureId) {
return <Measure key={measureId} measureId={measureId} />;
});
return (
<div className="sample-measure-input-container">
<h2 className="section-title">Effect</h2>
... | {
return {
name: state.DepVars.getIn([ownProps.depVarId, 'name']),
measureIds: state.DepVars.getIn([ownProps.depVarId, 'measures']).toJS(),
};
} | identifier_body |
DepVar.js | // import React and Redux dependencies
var React = require('react');
var connect = require('react-redux').connect;
var Measure = require('./Measure');
function | (state, ownProps) {
return {
name: state.DepVars.getIn([ownProps.depVarId, 'name']),
measureIds: state.DepVars.getIn([ownProps.depVarId, 'measures']).toJS(),
};
}
var DepVar = React.createClass({
render: function () {
var measures = this.props.measureIds.map(function(measureId) {
return <Measu... | mapStatetoProps | identifier_name |
DepVar.js | // import React and Redux dependencies
var React = require('react');
var connect = require('react-redux').connect;
var Measure = require('./Measure');
function mapStatetoProps (state, ownProps) {
return {
name: state.DepVars.getIn([ownProps.depVarId, 'name']),
measureIds: state.DepVars.getIn([ownProps.depVa... | var measures = this.props.measureIds.map(function(measureId) {
return <Measure key={measureId} measureId={measureId} />;
});
return (
<div className="sample-measure-input-container">
<h2 className="section-title">Effect</h2>
<div>
<p className="sample-depvar-question">E... | };
}
var DepVar = React.createClass({
render: function () { | random_line_split |
videojs.autoplay-toggle.js | 'use strict';
(function (window, document, videojs) {
/**
* Cookie access functions.
* From: https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
*/
var cookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(
document.cookie.repl... |
}
}
return obj;
},
/**
* Default settings for this plugin.
*/
defaults = {
namespace: 'autoplay-toggle', // namespace for cookie/localstorage
},
/**
* Autoplay toggle plugin setup.
*/
autoplayToggle = function (options) {
var player = this,
settings = extend... | {
obj[k] = arg[k];
} | conditional_block |
videojs.autoplay-toggle.js | 'use strict';
(function (window, document, videojs) {
/**
* Cookie access functions.
* From: https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
*/
var cookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(
document.cookie.repl... |
player.me.autoplay = true;
setTimeout(function () {
player.tech_.play();
}, 0)
}
// initialize autoplay toggle
autoplayToggleButton(turnOn);
// set up toggle click
autoplayBtn.onclick = function () {
// check if key in storage and do the opposite of ... | // we want this to autoplay | random_line_split |
shootout-nbody.rs | use std::f64;
use std::from_str::FromStr;
use std::os;
use std::uint::range;
use std::vec;
static PI: f64 = 3.141592653589793;
static SOLAR_MASS: f64 = 4.0 * PI * PI;
static YEAR: f64 = 365.24;
static N_BODIES: uint = 5;
static BODIES: [Planet, ..N_BODIES] = [
// Sun
Planet {
x: [ 0.0, 0.0, 0.0 ],
... | d[2] = bodies[i].x[2] - bodies[j].x[2];
let d2 = d[0]*d[0] + d[1]*d[1] + d[2]*d[2];
let mag = dt / (d2 * f64::sqrt(d2));
let a_mass = bodies[i].mass;
let b_mass = bodies[j].mass;
bodies[i].v[0] -= d[0] * b_mass * mag;
... | for range(0, N_BODIES) |i| {
for range(i + 1, N_BODIES) |j| {
d[0] = bodies[i].x[0] - bodies[j].x[0];
d[1] = bodies[i].x[1] - bodies[j].x[1]; | random_line_split |
shootout-nbody.rs | use std::f64;
use std::from_str::FromStr;
use std::os;
use std::uint::range;
use std::vec;
static PI: f64 = 3.141592653589793;
static SOLAR_MASS: f64 = 4.0 * PI * PI;
static YEAR: f64 = 365.24;
static N_BODIES: uint = 5;
static BODIES: [Planet, ..N_BODIES] = [
// Sun
Planet {
x: [ 0.0, 0.0, 0.0 ],
... | bodies[j].v[2] += d[2] * a_mass * mag;
}
}
for bodies.mut_iter().advance |a| {
a.x[0] += dt * a.v[0];
a.x[1] += dt * a.v[1];
a.x[2] += dt * a.v[2];
}
}
}
fn energy(bodies: &[Planet, ..N_BODIES]) -> f64 {
let mut e = 0.0;
... | {
let mut d = [ 0.0, ..3 ];
for (steps as uint).times {
for range(0, N_BODIES) |i| {
for range(i + 1, N_BODIES) |j| {
d[0] = bodies[i].x[0] - bodies[j].x[0];
d[1] = bodies[i].x[1] - bodies[j].x[1];
d[2] = bodies[i].x[2] - bodies[j].x[2];
... | identifier_body |
shootout-nbody.rs | use std::f64;
use std::from_str::FromStr;
use std::os;
use std::uint::range;
use std::vec;
static PI: f64 = 3.141592653589793;
static SOLAR_MASS: f64 = 4.0 * PI * PI;
static YEAR: f64 = 365.24;
static N_BODIES: uint = 5;
static BODIES: [Planet, ..N_BODIES] = [
// Sun
Planet {
x: [ 0.0, 0.0, 0.0 ],
... | () {
let n: i32 = FromStr::from_str(os::args()[1]).get();
let mut bodies = BODIES;
offset_momentum(&mut bodies);
println(fmt!("%.9f", energy(&bodies) as float));
advance(&mut bodies, 0.01, n);
println(fmt!("%.9f", energy(&bodies) as float));
}
| main | identifier_name |
api-helper.js | /*******************************************************************************
* Copyright [2017] [Quirino Brizi (quirino.brizi@gmail.com)]
*
* 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... | console.error("received error: ", err.stack);
var statusCode = (!err.statusCode || err.statusCode == 0) ? 500 : err.statusCode,
message = !err.error ? !err.body ? { message: "Internal Server Error" } : err.body : err.error;
res.status(statusCode).send(message);
},
}; | random_line_split | |
sdl.rs | 3 = 32,
N4 = 33,
N5 = 34,
N6 = 35,
N7 = 36,
N8 = 37,
N9 = 38,
N0 = 39,
RETURN = 40,
ESCAPE = 41,
BACKSPACE = 42,
TAB = 43,
SPACE = 44,
MINUS = 45,
EQUALS = 46,
LEFTBRACKET = 47,
RIGHTBRACKET = 48, | COMMA = 54,
PERIOD = 55,
SLASH = 56,
CAPSLOCK = 57,
F1 = 58,
F2 = 59,
F3 = 60,
F4 = 61,
F5 = 62,
F6 = 63,
F7 = 64,
F8 = 65,
F9 = 66,
F10 = 67,
F11 = 68,
F12 = 69,
PRINTSCREEN = 70,
SCROLLLOCK = 71,
PAUSE = 72,
INSERT = 73,
HOME = 74,
... | BACKSLASH = 49,
NONUSHASH = 50,
SEMICOLON = 51,
APOSTROPHE = 52,
GRAVE = 53, | random_line_split |
sdl.rs | 75,
DELETE = 76,
END = 77,
PAGEDOWN = 78,
RIGHT = 79,
LEFT = 80,
DOWN = 81,
UP = 82,
NUMLOCKCLEAR = 83,
KP_DIVIDE = 84,
KP_MULTIPLY = 85,
KP_MINUS = 86,
KP_PLUS = 87,
KP_ENTER = 88,
KP_1 = 89,
KP_2 = 90,
KP_3 = 91,
KP_4 = 92,
KP_5 = 93,
KP_6 = ... | SDL_Renderer | identifier_name | |
__init__.py | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from pathlib import Path
from flask import (Flask, session, redirect, url_for, flash, g, request,
render_template)
from flask_assets import Environment
from flask_babel import gettext
from flask_wtf.csrf import CSRFProtect, CSRFError
... | (config: 'SDConfig') -> Flask:
app = Flask(__name__,
template_folder=config.JOURNALIST_TEMPLATES_DIR,
static_folder=path.join(config.SECUREDROP_ROOT, 'static'))
app.config.from_object(config.JOURNALIST_APP_FLASK_CONFIG_CLS)
app.session_interface = JournalistInterfaceSessionI... | create_app | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from pathlib import Path
from flask import (Flask, session, redirect, url_for, flash, g, request,
render_template)
from flask_assets import Environment
from flask_babel import gettext
from flask_wtf.csrf import CSRFProtect, CSRFError
... |
session['expires'] = datetime.utcnow() + \
timedelta(minutes=getattr(config,
'SESSION_EXPIRATION_MINUTES',
120))
# Work around https://github.com/lepture/flask-wtf/issues/275
# -- after upgrading from Pyth... | session.clear()
flash(gettext('You have been logged out due to password change'),
'error') | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from pathlib import Path |
from flask import (Flask, session, redirect, url_for, flash, g, request,
render_template)
from flask_assets import Environment
from flask_babel import gettext
from flask_wtf.csrf import CSRFProtect, CSRFError
from os import path
import sys
from werkzeug.exceptions import default_exceptions
import i... | random_line_split | |
__init__.py | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from pathlib import Path
from flask import (Flask, session, redirect, url_for, flash, g, request,
render_template)
from flask_assets import Environment
from flask_babel import gettext
from flask_wtf.csrf import CSRFProtect, CSRFError
... |
def create_app(config: 'SDConfig') -> Flask:
app = Flask(__name__,
template_folder=config.JOURNALIST_TEMPLATES_DIR,
static_folder=path.join(config.SECUREDROP_ROOT, 'static'))
app.config.from_object(config.JOURNALIST_APP_FLASK_CONFIG_CLS)
app.session_interface = Journalist... | if not app.static_folder:
raise FileNotFoundError
custom_logo_filename = "i/custom_logo.png"
default_logo_filename = "i/logo.png"
custom_logo_path = Path(app.static_folder) / custom_logo_filename
default_logo_path = Path(app.static_folder) / default_logo_filename
if custom_logo_path.is_file... | identifier_body |
build.rs | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::env;
use std::io::Write;
use std::path::Path;
use std::process::Command;
use std::str::{self, FromStr};
fn main() {
println!("cargo:rustc-cf... | Ok(())
}
fn rustc_minor_version() -> Option<u32> {
let rustc = match env::var_os("RUSTC") {
Some(rustc) => rustc,
None => return None,
};
let output = match Command::new(rustc).arg("--version").output() {
Ok(output) => output,
Err(_) => return None,
};
let vers... | let mut file = std::fs::File::create(output_dir.join("generated.rs"))?;
file.write_all(b"fn run_some_generated_code() -> u32 { 42 }")?; | random_line_split |
build.rs | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::env;
use std::io::Write;
use std::path::Path;
use std::process::Command;
use std::str::{self, FromStr};
fn main() {
println!("cargo:rustc-cf... |
let next = match pieces.next() {
Some(next) => next,
None => return None,
};
u32::from_str(next).ok()
}
| {
let rustc = match env::var_os("RUSTC") {
Some(rustc) => rustc,
None => return None,
};
let output = match Command::new(rustc).arg("--version").output() {
Ok(output) => output,
Err(_) => return None,
};
let version = match str::from_utf8(&output.stdout) {
O... | identifier_body |
build.rs | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::env;
use std::io::Write;
use std::path::Path;
use std::process::Command;
use std::str::{self, FromStr};
fn | () {
println!("cargo:rustc-cfg=build_script_ran");
let minor = match rustc_minor_version() {
Some(minor) => minor,
None => return,
};
let target = env::var("TARGET").unwrap();
if minor >= 34 {
println!("cargo:rustc-cfg=is_new_rustc");
} else {
println!("cargo:ru... | main | identifier_name |
benchmark.ndarray_nd_noncontiguous_generic.native.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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 a... | * @private
* @param {Benchmark} b - benchmark instance
*/
function benchmark( b ) {
var y;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
y = abs( x );
if ( isnan( y.data[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y.data[ i%len ] ) ) {
b.fail( '... | {
var buf;
var sh;
var st;
var x;
var i;
buf = [];
for ( i = 0; i < len*2; i++ ) {
buf.push( rand() );
}
sh = [ len/2, 2, 1 ];
st = [ 4, 1, 1 ];
x = ndarray( 'generic', buf, sh, st, 0, 'row-major' );
return benchmark;
/**
* Benchmark function.
* | identifier_body |
benchmark.ndarray_nd_noncontiguous_generic.native.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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 a... |
}
b.toc();
if ( isnan( y.data[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i ... | {
b.fail( 'should not return NaN' );
} | conditional_block |
benchmark.ndarray_nd_noncontiguous_generic.native.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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 a... | ( len ) {
var buf;
var sh;
var st;
var x;
var i;
buf = [];
for ( i = 0; i < len*2; i++ ) {
buf.push( rand() );
}
sh = [ len/2, 2, 1 ];
st = [ 4, 1, 1 ];
x = ndarray( 'generic', buf, sh, st, 0, 'row-major' );
return benchmark;
/**
* Benchmark function.
*
* @private
* @param {Benchmark} b - benchmar... | createBenchmark | identifier_name |
benchmark.ndarray_nd_noncontiguous_generic.native.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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 a... | var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
y = abs( x );
if ( isnan( y.data[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y.data[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**... | */
function benchmark( b ) {
var y; | random_line_split |
status.js | import { combineReducers } from 'redux'
import {
FETCH_NEWS,
FETCH_NEWS_FULFILLED,
FETCH_NEWS_REJECTED
} from '../actions/news' | import { CLOSE_DIALOG } from '../actions/dialog'
const isFetching = (state = false, action) => {
switch (action.type) {
case FETCH_NEWS:
case FETCH_STORY:
return true
case FETCH_NEWS_FULFILLED:
case FETCH_STORY_FULFILLED:
return false
default:
return state
}
}
const error = (st... | import {
FETCH_STORY,
FETCH_STORY_REJECTED,
FETCH_STORY_FULFILLED
} from '../actions/story' | random_line_split |
utils.py | """
This module is not part of the original setuptools code.
It was created because much of the code in order modules was (and still
is) unorganized and simple utility functions were defined as class methods
for no obious reason, uselessly cluttering some of the large classes.
This module is a place such functions.
""... | z.close()
def samefile(p1, p2):
"""
Similar as os.path.samefile
Note:
Only on Macintosh and Unix is the function os.path.samefile available.
"""
if(hasattr(os.path, 'samefile') and
os.path.exists(p1) and
os.path.exists(p2)
):
return os.path.samefile(p1... | fo = open(path, 'wb')
fo.write(z.read(name))
fo.close() | random_line_split |
utils.py | """
This module is not part of the original setuptools code.
It was created because much of the code in order modules was (and still
is) unorganized and simple utility functions were defined as class methods
for no obious reason, uselessly cluttering some of the large classes.
This module is a place such functions.
""... | (p1, p2):
"""
Similar as os.path.samefile
Note:
Only on Macintosh and Unix is the function os.path.samefile available.
"""
if(hasattr(os.path, 'samefile') and
os.path.exists(p1) and
os.path.exists(p2)
):
return os.path.samefile(p1,p2)
return bool(os.pat... | samefile | identifier_name |
utils.py | """
This module is not part of the original setuptools code.
It was created because much of the code in order modules was (and still
is) unorganized and simple utility functions were defined as class methods
for no obious reason, uselessly cluttering some of the large classes.
This module is a place such functions.
""... |
def execute_script(py_path):
"""
Execute the python script (located at path) and log error message
when the return value of the subprocess was non-zero.
"""
retcode = subprocess.call([sys.executable, py_path])
if retcode != 0:
log.warn("WARNING: executing Python script %r returned %i... | """
Removes the file or directory (if it exists),
returns 0 on success, 1 on failure.
"""
if not path.exists(file_or_dir):
return 0
retcode = 0
try:
if path.isdir(file_or_dir):
shutil.rmtree(file_or_dir)
else:
os.remove(file_or_dir)
except (I... | identifier_body |
utils.py | """
This module is not part of the original setuptools code.
It was created because much of the code in order modules was (and still
is) unorganized and simple utility functions were defined as class methods
for no obious reason, uselessly cluttering some of the large classes.
This module is a place such functions.
""... |
except (IOError, OSError), err :
log.error("Error: could not remove %s: %s", file_or_dir, err)
retcode = 1
return retcode
def execute_script(py_path):
"""
Execute the python script (located at path) and log error message
when the return value of the subprocess was non-zero.
... | os.remove(file_or_dir) | conditional_block |
base.js | /**
@module ember-flexberry-gis
*/
import Ember from 'ember';
/**
Class implementing base stylization for markers.
@class BaseMarkerStyle
*/
export default Ember.Object.extend({
/**
Gets default style settings.
@method getDefaultStyleSettings
@return {Object} Hash containing default style settin... | ,
/**
Renderes layer-style preview on the specified canvas element.
@method renderOnCanvas
@param {Object} options Method options.
@param {<a =ref="https://developer.mozilla.org/ru/docs/Web/HTML/Element/canvas">Canvas</a>} options.canvas Canvas element on which marker-style preview must be rendered.... | {
throw `Method 'renderOnLeafletMarker' isn't implemented in 'base' marker-style`;
} | identifier_body |
base.js | /**
@module ember-flexberry-gis
*/ | Class implementing base stylization for markers.
@class BaseMarkerStyle
*/
export default Ember.Object.extend({
/**
Gets default style settings.
@method getDefaultStyleSettings
@return {Object} Hash containing default style settings.
*/
getDefaultStyleSettings() {
return null;
},
/**
... |
import Ember from 'ember';
/** | random_line_split |
base.js | /**
@module ember-flexberry-gis
*/
import Ember from 'ember';
/**
Class implementing base stylization for markers.
@class BaseMarkerStyle
*/
export default Ember.Object.extend({
/**
Gets default style settings.
@method getDefaultStyleSettings
@return {Object} Hash containing default style settin... | ({ canvas, style, target }) {
throw `Method 'renderOnCanvas' isn't implemented in 'base' marker-style`;
}
});
| renderOnCanvas | identifier_name |
index.js | 'use strict';
var nextTick = require('just-next-tick');
var toStr = Object.prototype.toString;
var isFunction = function (value) {
return toStr.call(value) === '[object Function]';
};
/*
* Big Integer Minimum
*
* Pass in two strings that are otherwise valid integers, positive or negative.
* No leading zeroes.
... | }
} else if (aNegative || bNegative) {
// signs are different
if (bNegative) {
smallest = numberB;
}
} else if (lengthA > lengthB) { // both positive
// positive number with the least digits is smallest
smallest = numberB;
} else if (lengthA === lengthB) {
// lengths are the same; both po... | smallest = numberB;
} else if (lengthA === lengthB) {
// lengths are the same; both negative
smallest = numberA < numberB ? numberB : numberA; | random_line_split |
index.js | 'use strict';
var nextTick = require('just-next-tick');
var toStr = Object.prototype.toString;
var isFunction = function (value) {
return toStr.call(value) === '[object Function]';
};
/*
* Big Integer Minimum
*
* Pass in two strings that are otherwise valid integers, positive or negative.
* No leading zeroes.
... | else if (lengthA > lengthB) { // both positive
// positive number with the least digits is smallest
smallest = numberB;
} else if (lengthA === lengthB) {
// lengths are the same; both positive
smallest = numberA < numberB ? numberA : numberB;
}
}
return smallest;
};
var dispatcher = function (number... | {
// signs are different
if (bNegative) {
smallest = numberB;
}
} | conditional_block |
update.rs | use std::env;
use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::find_root_manifest_for_cwd;
#[derive(RustcDecodable)]
struct Options {
flag_package: Option<String>,
flag_aggressive: bool,
flag_precise: Option<String>,
flag_manifest_path: Option<String>,
... | (options: Options, config: &Config) -> CliResult<Option<()>> {
debug!("executing; cmd=cargo-update; args={:?}", env::args().collect::<Vec<_>>());
config.shell().set_verbose(options.flag_verbose);
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path));
let spec = options.flag_package.as... | execute | identifier_name |
update.rs | use std::env;
use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::find_root_manifest_for_cwd;
#[derive(RustcDecodable)]
struct Options {
flag_package: Option<String>,
flag_aggressive: bool,
flag_precise: Option<String>,
flag_manifest_path: Option<String>,
... |
If SPEC is given, then a conservative update of the lockfile will be
performed. This means that only the dependency specified by SPEC will be
updated. Its transitive dependencies will be updated only if SPEC cannot be
updated without updating dependencies. All other dependencies will remain
locked at their currently ... | --manifest-path PATH Path to the manifest to compile
-v, --verbose Use verbose output
This command requires that a `Cargo.lock` already exists as generated by
`cargo build` or related commands. | random_line_split |
minimal-config.ts | import { writeFile, writeMultipleFiles } from '../../utils/fs';
import { ng } from '../../utils/process';
|
return Promise.resolve()
.then(() => writeFile('angular.json', JSON.stringify({
apps: [{
root: 'src',
main: 'main.ts',
scripts: [
'../node_modules/core-js/client/shim.min.js',
'../node_modules/zone.js/dist/zone.js'
]
}],
e2e: { protractor: { c... | export default function () {
// TODO(architect): Figure out what a minimal config is for architect apps.
return; | random_line_split |
webInterface.js | = require('co'),
compress = require('compression');
const packageJson = require('../package.json');
const MAX_CONTENT_SIZE = 1024 * 2000; // 2000kb
/**
*
*
* @class webInterface
* @extends {events.EventEmitter}
*/
class webInterface extends events.EventEmitter {
/**
* Creates an instance of webInterface... | return next();
});
app.use(bodyParser.json());
app.get('/latestLog', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
recorder.getRecords(null, 10000, (err, docs) => {
if (err) {
res.end(err.toString());
} else {
re... | app.use((req, res, next) => {
res.setHeader('note', 'THIS IS A REQUEST FROM ANYPROXY WEB INTERFACE'); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.