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 |
|---|---|---|---|---|
insert_equations.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 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... |
// Case 2: replace existing node...
else if ( EQN_END.test( parent.children[ index+2 ].value ) ) {
debug( 'Replacing existing node...' );
parent.children[ index+1 ] = newNode;
}
else {
debug( 'Invalid node: %s', node.value );
throw new Error( 'invalid node. Invalid equation comment. Ensure that the... | {
debug( 'Inserting new node...' );
parent.children.splice( index+1, 0, newNode );
} | conditional_block |
insert_equations.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 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... |
// VARIABLES //
var debug = logger( 'remark-img-equations:insert_equations' );
var EQN_START = /<!-- <equation.*> -->/;
var EQN_END = /<!-- <\/equation> -->/;
var LABEL = /label="([^"]*)"/;
var ALT = /alt="([^"]*)"/;
var RAW = /raw="([^"]*)"/;
// MAIN //
/**
* Inserts an image equation element into a Markdown AST... | var createElement = require( '@stdlib/_tools/markdown/img-svg-equation' ); | random_line_split |
insert_equations.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 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... | ( node, index, parent ) {
var newNode;
var label;
var html;
var opts;
var alt;
var raw;
if ( EQN_START.test( node.value ) === true ) {
debug( 'Found an equation...' );
label = LABEL.exec( node.value );
if ( label === null ) {
debug( 'Invalid node: %s', node.value );
throw new Error( 'invalid node. ... | insertEquations | identifier_name |
insert_equations.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 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... | if ( alt === null ) {
debug( 'Invalid node: %s', node.value );
throw new Error( 'invalid node. Equation comments must have valid alternate text. Node: '+node.value+'.' );
}
alt = alt[ 1 ];
debug( 'Alternate text: %s', alt );
raw = RAW.exec( node.value );
if ( raw === null ) {
debug( 'Invalid node:... | {
var newNode;
var label;
var html;
var opts;
var alt;
var raw;
if ( EQN_START.test( node.value ) === true ) {
debug( 'Found an equation...' );
label = LABEL.exec( node.value );
if ( label === null ) {
debug( 'Invalid node: %s', node.value );
throw new Error( 'invalid node. Equation comments must h... | identifier_body |
form_view.js | 'use strict';
angular.module('myApp.form', ['ngRoute'])
.controller('FormCtrl', ["$location", "config", 'cardsServicesRequests', function ($location, config, cardsServicesRequests) { |
vm.card = {};
vm.sendPost = function () {
cardsServicesRequests.postCard(vm.card).then(function (response) {
vm.data = response.data;
$location.path('/success');
}, function (response) {
vm.errors = response.data.errors;
... | var vm = this;
vm.errors={}; | random_line_split |
form_view.js | 'use strict';
angular.module('myApp.form', ['ngRoute'])
.controller('FormCtrl', ["$location", "config", 'cardsServicesRequests', function ($location, config, cardsServicesRequests) {
var vm = this;
vm.errors={};
vm.card = {};
vm.sendPost = function () {
cardsServic... |
else {
vm.card.limit=null;
}
vm.sendPost();
}
catch(err){
$location.path('/error');
}
}
}]);
| {
vm.card.limit=vm.card_limit*100;
} | conditional_block |
lib.rs | #![cfg_attr(test, feature(plugin))]
#![warn(
clippy::empty_enum,
clippy::filter_map,
clippy::if_not_else,
clippy::invalid_upcast_comparisons,
clippy::items_after_statements,
clippy::mut_mut,
clippy::nonminimal_bool,
clippy::option_map_unwrap_or,
clippy::option_map_unwrap_or_else,
... | let finished_levels: usize = stats.iter().map(|x| x.solved_levels).sum();
let collections_started = stats.iter().filter(|x| x.started() && !x.solved()).count();
println!(
"{}",
Yellow.bold().paint(" Collections Levels")
);
println!("------------------------------------... | let finished_collections = stats.iter().filter(|x| x.solved()).count(); | random_line_split |
lib.rs | #![cfg_attr(test, feature(plugin))]
#![warn(
clippy::empty_enum,
clippy::filter_map,
clippy::if_not_else,
clippy::invalid_upcast_comparisons,
clippy::items_after_statements,
clippy::mut_mut,
clippy::nonminimal_bool,
clippy::option_map_unwrap_or,
clippy::option_map_unwrap_or_else,
... | );
} else {
let solved = if collection.started() {
Blue.paint("solved")
} else {
White.paint("solved")
};
println!(
" {}{}{:>10} {}",
padded_short_name,
White.bold().paint(... | {
let stats = gather_stats();
println!(
" {} {}",
Yellow.bold().paint("File name"),
Yellow.bold().paint("Collection name")
);
println!("--------------------------------------------------------------------------------");
for collection in stats {
let pa... | identifier_body |
lib.rs | #![cfg_attr(test, feature(plugin))]
#![warn(
clippy::empty_enum,
clippy::filter_map,
clippy::if_not_else,
clippy::invalid_upcast_comparisons,
clippy::items_after_statements,
clippy::mut_mut,
clippy::nonminimal_bool,
clippy::option_map_unwrap_or,
clippy::option_map_unwrap_or_else,
... | else {
White.paint("solved")
};
println!(
" {}{}{:>10} {}",
padded_short_name,
White.bold().paint(padded_full_name),
format!("{}/{}", collection.solved_levels, collection.total_levels),
solved
... | {
Blue.paint("solved")
} | conditional_block |
lib.rs | #![cfg_attr(test, feature(plugin))]
#![warn(
clippy::empty_enum,
clippy::filter_map,
clippy::if_not_else,
clippy::invalid_upcast_comparisons,
clippy::items_after_statements,
clippy::mut_mut,
clippy::nonminimal_bool,
clippy::option_map_unwrap_or,
clippy::option_map_unwrap_or_else,
... | () {
let stats = gather_stats();
let num_collections = stats.len();
let num_levels: usize = stats.iter().map(|x| x.total_levels).sum();
let finished_collections = stats.iter().filter(|x| x.solved()).count();
let finished_levels: usize = stats.iter().map(|x| x.solved_levels).sum();
let collect... | print_stats | identifier_name |
fakeListRemote.spec.ts | import * as chai from "chai";
import { ListRemote } from "../../database/listRemote";
const expect = chai.expect;
/**
* `FakeListRemote` is a test fixture for verifying logic lives in the
* `DatabaseRemove` class. It is essentially a mock for the Realtime Database
* that accepts a JSON tree to serve upon construc... |
private size(data: any): number {
if (typeof data === "number") {
return data;
}
let size = 0;
for (const key of Object.keys(data)) {
size += this.size(data[key]);
}
return size;
}
private dataAtPath(path: string): any {
const splitedPath = path.slice(1).split("/");
... | {
if (timeout === 0) {
return Promise.reject(new Error("timeout"));
}
const d = this.dataAtPath(path);
if (d) {
let keys = Object.keys(d);
/*
* We mirror a critical implementation detail of here. Namely, the
* `startAfter` option (if it exists) is applied to the resulting... | identifier_body |
fakeListRemote.spec.ts | import * as chai from "chai";
import { ListRemote } from "../../database/listRemote";
const expect = chai.expect;
/**
* `FakeListRemote` is a test fixture for verifying logic lives in the
* `DatabaseRemove` class. It is essentially a mock for the Realtime Database
* that accepts a JSON tree to serve upon construc... | (data: any): number {
if (typeof data === "number") {
return data;
}
let size = 0;
for (const key of Object.keys(data)) {
size += this.size(data[key]);
}
return size;
}
private dataAtPath(path: string): any {
const splitedPath = path.slice(1).split("/");
let d = this.dat... | size | identifier_name |
fakeListRemote.spec.ts | import * as chai from "chai";
import { ListRemote } from "../../database/listRemote";
const expect = chai.expect;
/**
* `FakeListRemote` is a test fixture for verifying logic lives in the
* `DatabaseRemove` class. It is essentially a mock for the Realtime Database
* that accepts a JSON tree to serve upon construc... | let keys = Object.keys(d);
/*
* We mirror a critical implementation detail of here. Namely, the
* `startAfter` option (if it exists) is applied to the resulting key set
* before the `limitToFirst` option.
*/
if (startAfter) {
keys = keys.filter((key) => key > startA... | if (timeout === 0) {
return Promise.reject(new Error("timeout"));
}
const d = this.dataAtPath(path);
if (d) { | random_line_split |
fakeListRemote.spec.ts | import * as chai from "chai";
import { ListRemote } from "../../database/listRemote";
const expect = chai.expect;
/**
* `FakeListRemote` is a test fixture for verifying logic lives in the
* `DatabaseRemove` class. It is essentially a mock for the Realtime Database
* that accepts a JSON tree to serve upon construc... |
}
}
return d;
}
}
describe("FakeListRemote", () => {
it("should return limit the number of subpaths returned", async () => {
const fakeDb = new FakeListRemote({ 1: 1, 2: 2, 3: 3, 4: 4 });
await expect(fakeDb.listPath("/", 4)).to.eventually.eql(["1", "2", "3", "4"]);
await expect(fakeDb.l... | {
d = d[p];
} | conditional_block |
common.js |
( function( exports ) {
/**
* @class
* @param params
* @constructor
*/
function BulkLoader( params ) | case "audio":
case "music":
object = new Audio( param.url, Audio.MUSIC );
break;
case "se":
object = new Audio( param.url, Audio.SE );
break;
}
object.id = id;
... | {
this.params = params;
this._ids = [];
this.results = {};
this._objects = []; // GC対策
this.cache = {};
var self = this;
this._handler = function( e ) {
self._onLoadHandler( e );
};
for ( var id in this.params ) {
... | identifier_body |
common.js |
( function( exports ) {
/**
* @class
* @param params
* @constructor
*/
function BulkLoader( params ) {
this.params = params;
this._ids = [];
this.results = {};
this._objects = []; // GC対策
this.cache = {};
var self = this;
... | return this.cache[id];
};
BulkLoader.prototype.get = function( id ) {
return this.results[id];
};
BulkLoader.prototype.onload = null;
exports.BulkLoader = BulkLoader;
} )( this );
( function( exports ) {
var Observer = function () {
this.listeners = {};
... | this.cache[id] = new BitmapData(this.results[id]);
this.results[id] = null;
}
| conditional_block |
common.js | ( function( exports ) {
/**
* @class
* @param params
* @constructor
*/
function BulkLoader( params ) {
this.params = params;
this._ids = [];
this.results = {};
this._objects = []; // GC対策
this.cache = {};
var self = this;
... | object = new Audio( param.url, Audio.SE );
break;
}
object.id = id;
object.onload = this._handler;
this._objects.push( object );
}
}
BulkLoader.prototype = {};
BulkLoader.prototype._onLoadHandler = fun... | case "music":
object = new Audio( param.url, Audio.MUSIC );
break;
case "se":
| random_line_split |
common.js |
( function( exports ) {
/**
* @class
* @param params
* @constructor
*/
function | ( params ) {
this.params = params;
this._ids = [];
this.results = {};
this._objects = []; // GC対策
this.cache = {};
var self = this;
this._handler = function( e ) {
self._onLoadHandler( e );
};
for ( var id in this.params ) {
... | BulkLoader | identifier_name |
ionic-router-reuse-strategy.ts | import {
ActivatedRouteSnapshot,
DetachedRouteHandle,
RouteReuseStrategy
} from '@angular/router';
import { deepEqual, objectValues } from './util';
export class IonicRouteStrategy implements RouteReuseStrategy {
shouldDetach(_route: ActivatedRouteSnapshot): boolean {
return false;
}
// tslint:disable... | else {
return future.routeConfig === curr.routeConfig;
}
}
}
| {
// If the router params do not match, render the new component
return (
deepEqual(future.params, curr.params) &&
future.routeConfig === curr.routeConfig
);
} | conditional_block |
ionic-router-reuse-strategy.ts | import {
ActivatedRouteSnapshot,
DetachedRouteHandle,
RouteReuseStrategy
} from '@angular/router';
import { deepEqual, objectValues } from './util';
export class IonicRouteStrategy implements RouteReuseStrategy {
| (_route: ActivatedRouteSnapshot): boolean {
return false;
}
// tslint:disable-next-line
store(_route: ActivatedRouteSnapshot, _detachedTree: DetachedRouteHandle): void {}
shouldAttach(_route: ActivatedRouteSnapshot): boolean {
return false;
}
retrieve(_route: ActivatedRouteSnapshot): DetachedRout... | shouldDetach | identifier_name |
ionic-router-reuse-strategy.ts | import {
ActivatedRouteSnapshot,
DetachedRouteHandle,
RouteReuseStrategy
} from '@angular/router';
import { deepEqual, objectValues } from './util';
export class IonicRouteStrategy implements RouteReuseStrategy {
shouldDetach(_route: ActivatedRouteSnapshot): boolean {
return false;
}
// tslint:disable... | } else {
return future.routeConfig === curr.routeConfig;
}
}
} | // If the router params do not match, render the new component
return (
deepEqual(future.params, curr.params) &&
future.routeConfig === curr.routeConfig
); | random_line_split |
ready.js | define([
"../core",
"../core/init",
"../deferred"
], function( jQuery ) {
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isR... |
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here:... | {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
} | identifier_body |
ready.js | define([
"../core",
"../core/init",
"../deferred"
], function( jQuery ) {
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isR... | else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Kick off the DOM ready check even if the use... | {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} | conditional_block |
ready.js | define([
"../core",
"../core/init",
"../deferred"
], function( jQuery ) {
| jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( ... | // The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback | random_line_split |
ready.js | define([
"../core",
"../core/init",
"../deferred"
], function( jQuery ) {
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isR... | () {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser... | completed | identifier_name |
jsonConverterSpec.js | /**
* Created by Administrator on 2015/1/6.
*/
var grunt = require("grunt");
var htmlConverter = require("../tasks/lib/text").init(grunt);
describe("Test JSON Converter",function(){
it("should convert JSON to cmd module",function(){ | var e = 'define("test",[],"{\\\"test\\\":\\\"test\\\",\\\"value\\\":1,\\\"number\\\":2.2}");';
expect(htmlConverter.html2js(code,"test")).toEqual(e);
});
it("should convert JSON file to cmd module",function(){
var src = "test/fixture/no-modifier.json";
var dest = "test/tmp/no-mod... | var code = JSON.stringify({test:"test",value:1,number:2.2}); | random_line_split |
trivia.js | $(document).ready(function() {
//questions
var questions = [{
'questionNum': 1,
'question': 'When was the first mobile phone, Motorola Dyna TAC 8000X manufactured?',
'answer': ['1981', '1983', '1995', '1991'],
'correctAnswer': '1983',
}, {
'questionNum': 2,
... | ;
});
| {
var oneMinutes = 60 * 1,
// $('#time').append('<div class="timer">' + oneMinutes + '</div>');
display = document.querySelector("#time");
startTimer(oneMinutes, display);
} | identifier_body |
trivia.js | $(document).ready(function() {
//questions
var questions = [{
'questionNum': 1,
'question': 'When was the first mobile phone, Motorola Dyna TAC 8000X manufactured?',
'answer': ['1981', '1983', '1995', '1991'],
'correctAnswer': '1983',
}, {
'questionNum': 2,
... | () {
var oneMinutes = 60 * 1,
// $('#time').append('<div class="timer">' + oneMinutes + '</div>');
display = document.querySelector("#time");
startTimer(oneMinutes, display);
};
});
| countdown | identifier_name |
trivia.js | $(document).ready(function() {
//questions
var questions = [{
'questionNum': 1,
'question': 'When was the first mobile phone, Motorola Dyna TAC 8000X manufactured?',
'answer': ['1981', '1983', '1995', '1991'],
'correctAnswer': '1983',
}, {
'questionNum': 2,
... | '<label class="radio answer">' +
'<input class="answer js-check" type="radio" name="' + i +
'" data-name="' + questions[i].answer[a] +
'">' + questions[i].answer[a] +
'</input>' +
'</label>';
... |
for (var a = 0; a < questions[i].answer.length; a++) {
answerString += | random_line_split |
trivia.js | $(document).ready(function() {
//questions
var questions = [{
'questionNum': 1,
'question': 'When was the first mobile phone, Motorola Dyna TAC 8000X manufactured?',
'answer': ['1981', '1983', '1995', '1991'],
'correctAnswer': '1983',
}, {
'questionNum': 2,
... | else {
alert("try again");
wrong++;
// alert(wrong);
}
});
})
/* FUNCTIONS */
function startGame() {
var questionString = '';
for (var i = 0; i < questions.length; i++) {
var answerString = '';
q... | {
alert("Correct!!");
right++;
// alert(right);
} | conditional_block |
misc.ts | 'use strict';
import * as vsc from 'vscode';
export const D_MODE = { language: 'd', scheme: 'file' };
export function getRootPath() {
return vsc.workspace.workspaceFolders
? vsc.window.activeTextEditor
? (vsc.workspace.getWorkspaceFolder(vsc.window.activeTextEditor.document.uri) || vsc.worksp... | () {
if (!vsc.workspace.workspaceFolders) {
return Promise.resolve<string>(null);
}
const stdRootPath = Promise.resolve(vsc.workspace.workspaceFolders[0].uri.fsPath);
let rootPath: Thenable<string> = stdRootPath;
if (vsc.workspace.workspaceFolders.length > 1) {
rootPath = vsc.windo... | chooseRootPath | identifier_name |
misc.ts | 'use strict';
import * as vsc from 'vscode';
export const D_MODE = { language: 'd', scheme: 'file' };
export function getRootPath() {
return vsc.workspace.workspaceFolders
? vsc.window.activeTextEditor
? (vsc.workspace.getWorkspaceFolder(vsc.window.activeTextEditor.document.uri) || vsc.worksp... |
return rootPath;
} | {
rootPath = vsc.window.showQuickPick(vsc.workspace.workspaceFolders.map((f) => f.uri.fsPath))
.then((rp) => rp || stdRootPath);
} | conditional_block |
misc.ts | 'use strict';
import * as vsc from 'vscode';
export const D_MODE = { language: 'd', scheme: 'file' };
export function getRootPath() {
return vsc.workspace.workspaceFolders
? vsc.window.activeTextEditor
? (vsc.workspace.getWorkspaceFolder(vsc.window.activeTextEditor.document.uri) || vsc.worksp... | if (!vsc.workspace.workspaceFolders) {
return Promise.resolve<string>(null);
}
const stdRootPath = Promise.resolve(vsc.workspace.workspaceFolders[0].uri.fsPath);
let rootPath: Thenable<string> = stdRootPath;
if (vsc.workspace.workspaceFolders.length > 1) {
rootPath = vsc.window.sho... | : vsc.workspace.workspaceFolders[0].uri.fsPath
: null;
};
export function chooseRootPath() { | random_line_split |
misc.ts | 'use strict';
import * as vsc from 'vscode';
export const D_MODE = { language: 'd', scheme: 'file' };
export function getRootPath() | ;
export function chooseRootPath() {
if (!vsc.workspace.workspaceFolders) {
return Promise.resolve<string>(null);
}
const stdRootPath = Promise.resolve(vsc.workspace.workspaceFolders[0].uri.fsPath);
let rootPath: Thenable<string> = stdRootPath;
if (vsc.workspace.workspaceFolders.length > ... | {
return vsc.workspace.workspaceFolders
? vsc.window.activeTextEditor
? (vsc.workspace.getWorkspaceFolder(vsc.window.activeTextEditor.document.uri) || vsc.workspace.workspaceFolders[0]).uri.fsPath
: vsc.workspace.workspaceFolders[0].uri.fsPath
: null;
} | identifier_body |
SQL_Det_Pop_Sum_by_Column.py | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 22 23:03:45 2017
@author: Shabaka
"""
# import pandas
import pandas as pd
# Import Pyplot as plt from matplotlib
import matplotlib.pyplot as plt
from sqlalchemy import create_engine
# Import func
from sqlalchemy.sql import func
from sqlalchemy import ... | # Set Column names
df.columns = results[0].keys()
# Print the DataFrame
print(df)
# Plot the DataFrame
df.plot.bar()
plt.show() | # Create a DataFrame from the results: df
df = pd.DataFrame(results)
| random_line_split |
config.js | import { configLoaderCreator } from '@storybook/core/server';
import { logger } from '@storybook/node-logger';
import defaultConfig from './config/babel';
import loadTsConfig from './ts_config'; | import {
getAngularCliWebpackConfigOptions,
applyAngularCliWebpackConfig,
} from './angular-cli_config';
const cliWebpackConfigOptions = getAngularCliWebpackConfigOptions(process.cwd());
if (cliWebpackConfigOptions) {
logger.info('=> Loading angular-cli config.');
}
const configLoader = configLoaderCreator({
... | random_line_split | |
config.js | import { configLoaderCreator } from '@storybook/core/server';
import { logger } from '@storybook/node-logger';
import defaultConfig from './config/babel';
import loadTsConfig from './ts_config';
import {
getAngularCliWebpackConfigOptions,
applyAngularCliWebpackConfig,
} from './angular-cli_config';
const cliWebp... |
const configLoader = configLoaderCreator({
defaultConfigName: 'angular-cli',
defaultBabelConfig: defaultConfig,
wrapInitialConfig: (config, configDir) => {
const tsRule = config.module.rules[1];
tsRule.loaders[0].options = loadTsConfig(configDir);
return config;
},
wrapDefaultConfig: config =>... | {
logger.info('=> Loading angular-cli config.');
} | conditional_block |
render_alphabetsoup.py | x)**(1.0/3.0))
def findRealRoots(a,b,c,d):
if a != 0:
a, b, c, d = 1, b/float(a), c/float(a), d/float(a) # Divide through by a
t = b / 3.0
p, q = c - 3 * t**2, d - c * t + 2 * t**3
u, v = solveQuadratic(1, q, -(p/3.0)**3)
if type(u) == type(0j): # Complex Cubic Root
r = math.sqrt(u.real**2 + u.imag**2)... |
else:
#inkex.debug("[")
stack.pop(0)
images = [] # list of daughter images
nodes = [] # list of daughter names
while (stack[0] != "]"): # for all nodes in stack
newstate = stack[0] # the new state
newimage, width, height = draw( stack ) # draw the daughter state
if... | if (len(syntax[state]) == 1): # this state is a terminal node
return image, width, height
else:
substack = generate( state ) # generate random substack
return draw( substack ) # draw random substack | conditional_block |
render_alphabetsoup.py | nc.append([last[0], last[1][2:4] + last[1][:2] + this[1][-2:]])
else:
nc.append([last[0], this[1][-2:]])
last = this
return nc
def reversePath(sp):
rp = []
component = []
for p in sp:
cmd, params = p
if cmd == 'Z':
rp.extend(reverseComponent(component))
rp.append(['Z', []])
component = []
... | if cmd == 'C': | random_line_split | |
render_alphabetsoup.py | ule = findrule( state, nodes ) # find the rule for this subtree
for i in range( 0, len(images)):
currimg, width, height = images[i]
if currimg:
#box = getPathBoundingBox(currimg)
dx = rule[i][1]*units
dy = rule[i][2]*units
#newbox = ((box[0]+dx),(box[1]+dy),(box[2]+dx),(box[3]+dy))
sim... | effect | identifier_name | |
render_alphabetsoup.py | 0 + 3*by1)
ts = findRealRoots(0, a, b, c)
for t in ts:
if t >= 0 and t <= 1:
y = (-by0 + 3*by1 - 3*by2 + by3)*(t**3) + \
(3*by0 - 6*by1 + 3*by2)*(t**2) + \
(-3*by0 + 3*by1)*t + \
by0
segmentBox = (segmentBox[0], segmentBox[1], min(segmentBox[2], y), max(segmentBox[3], y))... | left = []
right = []
resolution = 8
for i in range( 0, 18 * resolution ):
y = 1.0/resolution * (i + 0.5) * zoom
xmin = None
xmax = None
for cmd,params in image:
segmentBox = None
if cmd == 'M':
# A move cannot contribute to the bounding box
last = params[:]
lastctrl = params[:]
elif... | identifier_body | |
can-place-flowers.py | # Time: O(n)
# Space: O(1)
# Suppose you have a long flowerbed in which some of the plots are planted and some are not.
# However, flowers cannot be planted in adjacent plots - they would compete for water
# and both would die.
#
# Given a flowerbed (represented as an array containing 0 and 1,
# where 0 means empty a... |
return False
| return True | conditional_block |
can-place-flowers.py | # Time: O(n)
# Space: O(1) |
# Suppose you have a long flowerbed in which some of the plots are planted and some are not.
# However, flowers cannot be planted in adjacent plots - they would compete for water
# and both would die.
#
# Given a flowerbed (represented as an array containing 0 and 1,
# where 0 means empty and 1 means not empty), and a... | random_line_split | |
can-place-flowers.py | # Time: O(n)
# Space: O(1)
# Suppose you have a long flowerbed in which some of the plots are planted and some are not.
# However, flowers cannot be planted in adjacent plots - they would compete for water
# and both would die.
#
# Given a flowerbed (represented as an array containing 0 and 1,
# where 0 means empty a... | """
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
for i in xrange(len(flowerbed)):
if flowerbed[i] == 0 and (i == 0 or flowerbed[i-1] == 0) and \
(i == len(flowerbed)-1 or flowerbed[i+1] == 0):
flowerbed[i] = 1
... | identifier_body | |
can-place-flowers.py | # Time: O(n)
# Space: O(1)
# Suppose you have a long flowerbed in which some of the plots are planted and some are not.
# However, flowers cannot be planted in adjacent plots - they would compete for water
# and both would die.
#
# Given a flowerbed (represented as an array containing 0 and 1,
# where 0 means empty a... | (object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
for i in xrange(len(flowerbed)):
if flowerbed[i] == 0 and (i == 0 or flowerbed[i-1] == 0) and \
(i == len(flowerbed)-1 or flower... | Solution | identifier_name |
HowMuch.rs | fn how_much(mut m: i32, mut n: i32) -> Vec<(String, String, String)> {
if m > n {
std::mem::swap(&mut m, &mut n);
}
let mut result: Vec<(String, String, String)> = Vec::new();
let mut c: f32;
let mut b: f32;
for i in m..n+1 {
c = (i as f32-1f32)/9f32;
b = (i as f32-2f32... |
if c.fract() == 0f32 && b.fract() == 0f32 {
let r_tuple = (format!("M: {}", i),
format!("B: {}", b as i32),
format!("C: {}", c as i32));
result.push(r_tuple);
}
}
return result;
}
fn testing(m: i32, n: i32, exp: Ve... | {
continue;
} | conditional_block |
HowMuch.rs | fn how_much(mut m: i32, mut n: i32) -> Vec<(String, String, String)> {
if m > n {
std::mem::swap(&mut m, &mut n);
}
let mut result: Vec<(String, String, String)> = Vec::new();
let mut c: f32;
let mut b: f32;
for i in m..n+1 {
c = (i as f32-1f32)/9f32;
b = (i as f32-2f32... |
fn tests() {
testing(1, 100, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11")]);
testing(1000, 1100, vec![("M: 1045", "B: 149", "C: 116")]);
testing(10000, 9950, vec![("M: 9991", "B: 1427", "C: 1110")]);
testing(0, 200, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11"), ("M: 163"... | {
let ans: String = format!("{:?}", how_much(m, n));
let sol: String = format!("{:?}", exp);
assert_eq!(ans, sol)
} | identifier_body |
HowMuch.rs | fn | (mut m: i32, mut n: i32) -> Vec<(String, String, String)> {
if m > n {
std::mem::swap(&mut m, &mut n);
}
let mut result: Vec<(String, String, String)> = Vec::new();
let mut c: f32;
let mut b: f32;
for i in m..n+1 {
c = (i as f32-1f32)/9f32;
b = (i as f32-2f32)/7f32;
... | how_much | identifier_name |
HowMuch.rs | fn how_much(mut m: i32, mut n: i32) -> Vec<(String, String, String)> {
if m > n {
std::mem::swap(&mut m, &mut n);
}
let mut result: Vec<(String, String, String)> = Vec::new();
let mut c: f32;
let mut b: f32;
for i in m..n+1 {
c = (i as f32-1f32)/9f32; | if c.fract() == 0f32 && b.fract() == 0f32 {
let r_tuple = (format!("M: {}", i),
format!("B: {}", b as i32),
format!("C: {}", c as i32));
result.push(r_tuple);
}
}
return result;
}
fn testing(m: i32, n: i32, exp: Vec... | b = (i as f32-2f32)/7f32;
if c < 0f32 || b < 0f32 {
continue;
} | random_line_split |
normalize.js | var normalize = require("../lib/normalize");
var yaml = require("../lib/yaml");
var Plugins = require("../lib/plugins");
var async = require("async");
var fs = require("fs");
var path = require("path");
var chai = require("chai");
chai.should();
chai.config.showDiff = true;
var plugins = new Plugins();
describe("Norm... | (dir, done) {
if(process.env.OVERWRITE_RESULTS === "true") return overwrite_normalization_results(dir, done);
async.each(fs.readdirSync(path.join(__dirname, dir)), function(filename) {
if(path.extname(filename)===".normal") {
var compare = path.basename(filename, ".normal");
it(path.join(dir, compare), functi... | run_normalization_tests | identifier_name |
normalize.js | var normalize = require("../lib/normalize");
var yaml = require("../lib/yaml");
var Plugins = require("../lib/plugins");
var async = require("async");
var fs = require("fs");
var path = require("path");
var chai = require("chai");
chai.should();
chai.config.showDiff = true;
var plugins = new Plugins();
describe("Norm... |
function overwrite_normalization_results(dir, done) {
async.each(fs.readdirSync(path.join(__dirname, dir)), function(filename, inner_done) {
if(path.extname(filename)===".yml") {
var to_normalize = yaml.loadFile(path.join(__dirname, dir, filename));
var normalized = normalize(to_normalize, plugins);
fs.wr... | {
if(process.env.OVERWRITE_RESULTS === "true") return overwrite_normalization_results(dir, done);
async.each(fs.readdirSync(path.join(__dirname, dir)), function(filename) {
if(path.extname(filename)===".normal") {
var compare = path.basename(filename, ".normal");
it(path.join(dir, compare), function(done) {
... | identifier_body |
normalize.js | var normalize = require("../lib/normalize");
var yaml = require("../lib/yaml");
var Plugins = require("../lib/plugins");
var async = require("async");
var fs = require("fs");
var path = require("path");
var chai = require("chai");
chai.should();
chai.config.showDiff = true;
var plugins = new Plugins();
describe("Norm... | var expected = yaml.loadFile(path.join(__dirname, dir, filename));
var normalized = normalize(to_normalize, plugins);
normalized.should.deep.equal(expected, JSON.stringify(normalized));
done();
});
}
}, done);
}
function overwrite_normalization_results(dir, done) {
async.each(fs.readdirSync(pat... | random_line_split | |
core.js | /* public/core.js */
var angTodo = angular.module('angTodo', []);
function mainController($scope, $http) | })
.error(function(data) {
console.log('Error: ' + data);
});
};
/* delete a todo after checking it */
$scope.deleteTodo = function(id) {
$http.delete('/api/todos/' + id)
.success(function(data) {
$scope.todos = data;... | {
$scope.formData = {};
/* when landing on the page, get all todos and show them */
$http.get('/api/todos')
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
... | identifier_body |
core.js | /* public/core.js */
var angTodo = angular.module('angTodo', []);
function mainController($scope, $http) {
$scope.formData = {};
/* when landing on the page, get all todos and show them */
$http.get('/api/todos')
.success(function(data) {
$scope.todos = data;
console.l... | $http.delete('/api/todos/' + id)
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
} /* function mainController */ | });
};
/* delete a todo after checking it */
$scope.deleteTodo = function(id) { | random_line_split |
core.js | /* public/core.js */
var angTodo = angular.module('angTodo', []);
function | ($scope, $http) {
$scope.formData = {};
/* when landing on the page, get all todos and show them */
$http.get('/api/todos')
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data... | mainController | identifier_name |
test_pygeonet_processing.py | # pyGeoNet_readGeotiff
#import sys
#import os
from osgeo import gdal
#from string import *
import numpy as np
from time import clock
import pygeonet_defaults as defaults
import pygeonet_prepare as Parameters
from math import modf, floor
#from scipy.stats.mstats import mquantiles
def read_dem_from_geotiff(demFileName... | specify q=0.5.
References:
http://reference.wolfram.com/mathematica/ref/Quantile.html
http://wiki.r-project.org/rwiki/doku.php?id=rdoc:stats:quantile
Author:
Ernesto P.Adorio Ph.D.
UP Extension Program in Pampanga, Clark Field.
"""
if not issorted:
y = sorted(x)
else:
y = x
if not (1 <= qtype <... | q - quantile
qtype - algorithm
issorted- True if x already sorted.
Compute quantiles from input array x given q.For median, | random_line_split |
test_pygeonet_processing.py | # pyGeoNet_readGeotiff
#import sys
#import os
from osgeo import gdal
#from string import *
import numpy as np
from time import clock
import pygeonet_defaults as defaults
import pygeonet_prepare as Parameters
from math import modf, floor
#from scipy.stats.mstats import mquantiles
def read_dem_from_geotiff(demFileName... | else:
y = x
if not (1 <= qtype <= 9):
return None # error!
# Parameters for the Hyndman and Fan algorithm
abcd = [(0, 0, 1, 0), # inverse empirical distrib.function., R type 1
(0.5, 0, 1, 0), # similar to type 1, averaged, R type 2
(0.5, 0, 0, 0), # nearest order statistic,(SAS) R type 3
(0, ... | """
Args:
x - input data
q - quantile
qtype - algorithm
issorted- True if x already sorted.
Compute quantiles from input array x given q.For median,
specify q=0.5.
References:
http://reference.wolfram.com/mathematica/ref/Quantile.html
http://wiki.r-project.org/rwiki/doku.php?id=rdoc:stat... | identifier_body |
test_pygeonet_processing.py | # pyGeoNet_readGeotiff
#import sys
#import os
from osgeo import gdal
#from string import *
import numpy as np
from time import clock
import pygeonet_defaults as defaults
import pygeonet_prepare as Parameters
from math import modf, floor
#from scipy.stats.mstats import mquantiles
def | (demFileName,demFilePath):
# Open the GeoTIFF format DEM
fullFilePath = demFilePath + demFileName
#fullFilePath = "G:\\HarishLaptop_Backup\\TI102782W0E\\PythonScripts\\pyGeoNet1.0\\data\\skunk.tif"
print fullFilePath
ary = []
ds = gdal.Open(fullFilePath, gdal.GA_ReadOnly)
geotransform = ds.G... | read_dem_from_geotiff | identifier_name |
test_pygeonet_processing.py | # pyGeoNet_readGeotiff
#import sys
#import os
from osgeo import gdal
#from string import *
import numpy as np
from time import clock
import pygeonet_defaults as defaults
import pygeonet_prepare as Parameters
from math import modf, floor
#from scipy.stats.mstats import mquantiles
def read_dem_from_geotiff(demFileName... |
# Parameters for the Hyndman and Fan algorithm
abcd = [(0, 0, 1, 0), # inverse empirical distrib.function., R type 1
(0.5, 0, 1, 0), # similar to type 1, averaged, R type 2
(0.5, 0, 0, 0), # nearest order statistic,(SAS) R type 3
(0, 0, 0, 1), # California linear interpolation, R type 4
(0.5, 0, ... | return None # error! | conditional_block |
authUser.model.ts | import * as firebase from 'firebase';
import { AuthService } from './auth.service';
export class AuthUser implements firebase.UserInfo {
displayName: string|null;
email: string|null;
photoURL: string|null;
providerId: string;
uid: string;
joined: number;
updated: number;
roles: Array<an... |
return false;
}
} | {
if(this.providers[i].af_provider === id) {
return true;
}
} | conditional_block |
authUser.model.ts | import * as firebase from 'firebase';
import { AuthService } from './auth.service';
export class AuthUser implements firebase.UserInfo {
displayName: string|null;
email: string|null;
photoURL: string|null;
providerId: string;
uid: string;
joined: number;
updated: number;
roles: Array<an... | (firebaseAuthInfo: firebase.User,
dbAuthInfo: any,
lookupFn: Function) {
// Firebase Auth information
this.displayName = firebaseAuthInfo.displayName;
this.email = firebaseAuthInfo.email;
this.photoURL = firebaseAuthInfo.photoURL;
this.providerId... | constructor | identifier_name |
authUser.model.ts | import * as firebase from 'firebase';
import { AuthService } from './auth.service';
export class AuthUser implements firebase.UserInfo {
displayName: string|null;
email: string|null;
photoURL: string|null;
providerId: string;
uid: string;
joined: number;
updated: number;
roles: Array<an... | this.email = firebaseAuthInfo.email;
this.photoURL = firebaseAuthInfo.photoURL;
this.providerId = firebaseAuthInfo.providerId;
this.uid = firebaseAuthInfo.uid;
for(var i = 0; i < firebaseAuthInfo.providerData.length; i++) {
var fbProviderData = firebaseAuthInfo.provi... | // Firebase Auth information
this.displayName = firebaseAuthInfo.displayName; | random_line_split |
authUser.model.ts | import * as firebase from 'firebase';
import { AuthService } from './auth.service';
export class AuthUser implements firebase.UserInfo {
displayName: string|null;
email: string|null;
photoURL: string|null;
providerId: string;
uid: string;
joined: number;
updated: number;
roles: Array<an... | }
hasProvider(id: Number): boolean {
for(var i = 0; i < this.providers.length; i++) {
if(this.providers[i].af_provider === id) {
return true;
}
}
return false;
}
} | {
// Firebase Auth information
this.displayName = firebaseAuthInfo.displayName;
this.email = firebaseAuthInfo.email;
this.photoURL = firebaseAuthInfo.photoURL;
this.providerId = firebaseAuthInfo.providerId;
this.uid = firebaseAuthInfo.uid;
for(var i = 0; i < fir... | identifier_body |
trivial-bounds-lint.rs | #![feature(trivial_bounds)]
#![allow(unused)]
#![deny(trivial_bounds)]
struct A where i32: Copy; //~ ERROR
trait X<T: Copy> {}
trait Y<T>: Copy {}
trait Z {
type S: Copy;
}
// Check only the bound the user writes trigger the lint
fn trivial_elaboration<T>() where T: X<i32> + Z<S = i32>, i32: Y<T> {} // OK
fn ... | // OK
fn global_outlives() where 'static: 'static {} //~ ERROR
// Check that each bound is checked individually
fn mixed_bounds<T: Copy>() where i32: X<T> + Copy {} //~ ERROR
fn main() {}
| {} | identifier_body |
trivial-bounds-lint.rs | #![feature(trivial_bounds)]
#![allow(unused)]
#![deny(trivial_bounds)]
struct A where i32: Copy; //~ ERROR
trait X<T: Copy> {}
trait Y<T>: Copy {}
trait Z {
type S: Copy; |
fn global_param() where i32: X<()> {} //~ ERROR
// Should only error on the trait bound, not the implicit
// projection bound <i32 as Z>::S == i32.
fn global_projection() where i32: Z<S = i32> {} //~ ERROR
impl A {
fn new() -> A { A }
}
// Lifetime bounds should be linted as well
fn global_lifetimes() where i32... | }
// Check only the bound the user writes trigger the lint
fn trivial_elaboration<T>() where T: X<i32> + Z<S = i32>, i32: Y<T> {} // OK | random_line_split |
trivial-bounds-lint.rs | #![feature(trivial_bounds)]
#![allow(unused)]
#![deny(trivial_bounds)]
struct | where i32: Copy; //~ ERROR
trait X<T: Copy> {}
trait Y<T>: Copy {}
trait Z {
type S: Copy;
}
// Check only the bound the user writes trigger the lint
fn trivial_elaboration<T>() where T: X<i32> + Z<S = i32>, i32: Y<T> {} // OK
fn global_param() where i32: X<()> {} //~ ERROR
// Should only error on the trait ... | A | identifier_name |
bluetooth.js | /*
* Copyright (c) 2016-17 Francesco Marino
*
* @author Francesco Marino <francesco@360fun.net>
* @website www.360fun.net
*
* This is just a basic Class to start playing with the new Web Bluetooth API,
* specifications can change at any time so keep in mind that all of this is
* mostly experimental! ;)
*
* Ch... | );
})
.then( () => {
this._log('Found service "' + serviceId + '"');
})
.catch( e => { this._error('Service "' + serviceId + '"') } );
})
);
});
}
disconnect() {
return new Promise( (resolve, reject) => {
if( this.isConnected() ) {
resolve();
... | }) | random_line_split |
bluetooth.js | /*
* Copyright (c) 2016-17 Francesco Marino
*
* @author Francesco Marino <francesco@360fun.net>
* @website www.360fun.net
*
* This is just a basic Class to start playing with the new Web Bluetooth API,
* specifications can change at any time so keep in mind that all of this is
* mostly experimental! ;)
*
* Ch... | else {
reject('Device not connected');
}
}
).then( ()=> {
let characteristic = this._characteristics.get(characteristicUuid);
return characteristic.readValue()
.then(value => {
// In Chrome 50+, a DataView is returned instead of an ArrayBuffer.
value = value.buf... | {
resolve();
} | conditional_block |
bluetooth.js | /*
* Copyright (c) 2016-17 Francesco Marino
*
* @author Francesco Marino <francesco@360fun.net>
* @website www.360fun.net
*
* This is just a basic Class to start playing with the new Web Bluetooth API,
* specifications can change at any time so keep in mind that all of this is
* mostly experimental! ;)
*
* Ch... | () {
return this.device && this.device.gatt.connected;
}
connect(options,services) {
return navigator.bluetooth.requestDevice(options)
.then(device => {
this.device = device;
this._log('Connected to device named "' + device.name + '" with ID "' + device.id + '"');
return device.gatt... | isConnected | identifier_name |
99-serios-so-request.js | module.exports = function(RED) {
"use strict";
var http = require("follow-redirects").http;
var https = require("follow-redirects").https;
var urllib = require("url");
var mustache = require("mustache");
var querystring = require("querystring");
var cookie = require("cookie");
var hashSu... | (n) {
RED.nodes.createNode(this,n);
var node = this;
var nodeSeriosUrl = n.seriosurl;
var nodeSOID = n.soid;
var nodeStream = n.stream;
if (RED.settings.httpRequestTimeout) {
this.reqTimeout = parseInt(RED.settings.httpRequestTimeout) || 120000;
} els... | SORequest | identifier_name |
99-serios-so-request.js | module.exports = function(RED) {
"use strict";
var http = require("follow-redirects").http;
var https = require("follow-redirects").https;
var urllib = require("url");
var mustache = require("mustache");
var querystring = require("querystring");
var cookie = require("cookie");
var hashSu... |
}
var opts = {};
opts.url = "http://localhost:3000/oauth2/token";
opts.method = "POST";
opts.form = {grant_type: 'client_credentials'},
opts.headers = {'Authorization': 'Basic '+new Buffer(this.credentials.client+":"+this.credentials.password).to... | {
url = "http://"+url;
} | conditional_block |
99-serios-so-request.js | module.exports = function(RED) {
"use strict";
var http = require("follow-redirects").http;
var https = require("follow-redirects").https;
var urllib = require("url");
var mustache = require("mustache");
var querystring = require("querystring");
var cookie = require("cookie");
var hashSu... | if (!url) {
node.error(RED._("httpin.errors.no-url"),msg);
return;
}
// url must start http:// or https:// so assume http:// if not set
if (url.indexOf("://") !== -1 && url.indexOf("http") !== 0) {
node.warn(RED._("httpin.er... | if (msg.seriosurl && nodeSeropsUrl && (nodeSeriosUrl !== msg.seriosurl)) { // revert change below when warning is finally removed
node.warn(RED._("common.errors.nooverride"));
}
| random_line_split |
99-serios-so-request.js | module.exports = function(RED) {
"use strict";
var http = require("follow-redirects").http;
var https = require("follow-redirects").https;
var urllib = require("url");
var mustache = require("mustache");
var querystring = require("querystring");
var cookie = require("cookie");
var hashSu... | }
if (!url) {
node.error(RED._("httpin.errors.no-url"),msg);
return;
}
// url must start http:// or https:// so assume http:// if not set
if (url.indexOf("://") !== -1 && url.indexOf("http") !== 0) {
node.warn(R... | {
RED.nodes.createNode(this,n);
var node = this;
var nodeSeriosUrl = n.seriosurl;
var nodeSOID = n.soid;
var nodeStream = n.stream;
if (RED.settings.httpRequestTimeout) {
this.reqTimeout = parseInt(RED.settings.httpRequestTimeout) || 120000;
} else {
... | identifier_body |
debug.rs | /* This Source Code Form is subject to the terms of the Mozilla Public | use std::cast::transmute;
use std::mem::size_of;
fn hexdump_slice(buf: &[u8]) {
let stderr = io::stderr();
stderr.write_str(" ");
for (i, &v) in buf.iter().enumerate() {
stderr.write_str(fmt!("%02X ", v as uint));
match i % 16 {
15 => stderr.write_str("\n "),
... | * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::io;
use std::vec::raw::buf_as_slice; | random_line_split |
debug.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::io;
use std::vec::raw::buf_as_slice;
use std::cast::transmute;
use std::mem::size_of;
fn hexdump_slice(b... |
pub fn hexdump<T>(obj: &T) {
unsafe {
let buf: *u8 = transmute(obj);
debug!("dumping at %p", buf);
buf_as_slice(buf, size_of::<T>(), hexdump_slice);
}
}
| {
let stderr = io::stderr();
stderr.write_str(" ");
for (i, &v) in buf.iter().enumerate() {
stderr.write_str(fmt!("%02X ", v as uint));
match i % 16 {
15 => stderr.write_str("\n "),
7 => stderr.write_str(" "),
_ => ()
}
stderr.flu... | identifier_body |
debug.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::io;
use std::vec::raw::buf_as_slice;
use std::cast::transmute;
use std::mem::size_of;
fn | (buf: &[u8]) {
let stderr = io::stderr();
stderr.write_str(" ");
for (i, &v) in buf.iter().enumerate() {
stderr.write_str(fmt!("%02X ", v as uint));
match i % 16 {
15 => stderr.write_str("\n "),
7 => stderr.write_str(" "),
_ => ()
}
... | hexdump_slice | identifier_name |
Team.tsx | import React from 'react'
import Img, { GatsbyImageProps } from 'gatsby-image'
import styled from 'styled-components'
import { Grid, Paper as MuiPaper, Container as MuiContainer, Typography } from '@material-ui/core'
import { graphql, useStaticQuery } from 'gatsby'
import { FormattedMessage } from 'react-intl'
import... | (props: Props) {
const data = useStaticQuery(graphql`
query {
leandro: file(relativePath: { eq: "team/leandro.jpg" }) {
childImageSharp {
fixed(width: 240) {
...GatsbyImageSharpFixed
}
}
}
cesar: file(relativePath: { eq: "team/cesar.jpg" }) {
... | Team | identifier_name |
Team.tsx | import React from 'react'
import Img, { GatsbyImageProps } from 'gatsby-image'
import styled from 'styled-components'
import { Grid, Paper as MuiPaper, Container as MuiContainer, Typography } from '@material-ui/core'
import { graphql, useStaticQuery } from 'gatsby'
import { FormattedMessage } from 'react-intl'
import... | <Typography variant='body2'>{team[member]}</Typography>
</Grid>
))}
</Grid>
</Container>
)
}
export default Team | <Circle elevation={elevation}>
<Image fixed={data[member].childImageSharp.fixed} />
</Circle> | random_line_split |
Team.tsx | import React from 'react'
import Img, { GatsbyImageProps } from 'gatsby-image'
import styled from 'styled-components'
import { Grid, Paper as MuiPaper, Container as MuiContainer, Typography } from '@material-ui/core'
import { graphql, useStaticQuery } from 'gatsby'
import { FormattedMessage } from 'react-intl'
import... | ...GatsbyImageSharpFixed
}
}
}
borborema: file(relativePath: { eq: "team/borborema.jpg" }) {
childImageSharp {
fixed(width: 240) {
...GatsbyImageSharpFixed
}
}
}
yuri: file(relativePath: { eq: "team/yuri.jpg" }) {
... | {
const data = useStaticQuery(graphql`
query {
leandro: file(relativePath: { eq: "team/leandro.jpg" }) {
childImageSharp {
fixed(width: 240) {
...GatsbyImageSharpFixed
}
}
}
cesar: file(relativePath: { eq: "team/cesar.jpg" }) {
childImageSh... | identifier_body |
test_source_data_file.py | from __future__ import unicode_literals
import datetime
import django
from django.utils.timezone import now
from django.test import TransactionTestCase
from mock import call, patch
from job.seed.metadata import SeedMetadata
from source.configuration.source_data_file import SourceDataFileParseSaver
from storage.model... | """Tests calling SourceDataFileParseSaver.save_parse_results_v6() successfully"""
started = '2018-06-01T00:00:00Z'
ended = '2018-06-01T01:00:00Z'
types = ['one', 'two', 'three']
new_workspace_path = 'awful/path'
data = {
'type': 'Feature',
... | random_line_split | |
test_source_data_file.py | from __future__ import unicode_literals
import datetime
import django
from django.utils.timezone import now
from django.test import TransactionTestCase
from mock import call, patch
from job.seed.metadata import SeedMetadata
from source.configuration.source_data_file import SourceDataFileParseSaver
from storage.model... |
geo_json = {'type': 'Feature'}
started = now()
ended = started + datetime.timedelta(days=1)
# quick hack to give these a valid timezone. Easier than creating a TZ object since we don't really care about the time for this test.
started = parse_datetime(started.isoformat() + "Z")
... | def setUp(self):
django.setup()
self.workspace = Workspace.objects.create(name='Test workspace')
self.file_name_1 = 'my_file.txt'
self.media_type_1 = 'text/plain'
self.source_file_1 = ScaleFile.objects.create(file_name=self.file_name_1, file_type='SOURCE',
... | identifier_body |
test_source_data_file.py | from __future__ import unicode_literals
import datetime
import django
from django.utils.timezone import now
from django.test import TransactionTestCase
from mock import call, patch
from job.seed.metadata import SeedMetadata
from source.configuration.source_data_file import SourceDataFileParseSaver
from storage.model... | (self):
django.setup()
self.workspace = Workspace.objects.create(name='Test workspace')
self.file_name_1 = 'my_file.txt'
self.media_type_1 = 'text/plain'
self.source_file_1 = ScaleFile.objects.create(file_name=self.file_name_1, file_type='SOURCE',
... | setUp | identifier_name |
pubEdgeOptions.ts | import {
Community,
CollectionPub,
ExternalPublication,
includeUserModel,
Pub,
PubAttribution, | export const getOptionsForIncludedPub = ({ includeCommunity }) => {
return [
includeCommunity && { model: Community, as: 'community' },
{
model: CollectionPub,
as: 'collectionPubs',
},
{
model: Release,
as: 'releases',
},
{
separate: true,
model: PubAttribution,
as: 'attributions',
... | Release,
} from 'server/models';
import { PubEdgeIncludesOptions } from 'types';
| random_line_split |
importer.ts | import type { TBabelCore, TBabelJest, TTypeScript } from '../types'
import type { TEsBuild } from '../types'
import { rootLogger } from './logger'
import { Memoize } from './memoize'
import { Errors, Helps, ImportReasons, interpolate } from './messages'
import { VersionCheckers } from './version-checkers'
// eslint-d... | {
@Memoize()
static get instance(): Importer {
logger.debug('creating Importer singleton')
// here we can define patches to apply to modules.
// it could be fixes that are not deployed, or
// abstractions so that multiple versions work the same
return new Importer({
'@babel/core': [passT... | Importer | identifier_name |
importer.ts | import type { TBabelCore, TBabelJest, TTypeScript } from '../types'
import type { TEsBuild } from '../types'
import { rootLogger } from './logger'
import { Memoize } from './memoize'
import { Errors, Helps, ImportReasons, interpolate } from './messages'
import { VersionCheckers } from './version-checkers'
// eslint-d... |
babelCore(why: ImportReasons): TBabelCore {
return this._import(why, '@babel/core')
}
typescript(why: ImportReasons, which: string): TTypeScript {
return this._import(why, which)
}
esBuild(why: ImportReasons): TEsBuild {
return this._import(why, 'esbuild')
}
@Memoize((...args: string[]) =... | {
return this._import(why, 'babel-jest')
} | identifier_body |
importer.ts | import type { TBabelCore, TBabelJest, TTypeScript } from '../types'
import type { TEsBuild } from '../types'
import { rootLogger } from './logger'
import { Memoize } from './memoize'
import { Errors, Helps, ImportReasons, interpolate } from './messages'
import { VersionCheckers } from './version-checkers'
// eslint-d... |
return this._patches[name].reduce((mod, patcher) => patcher(mod), unpatched)
}
return unpatched
}
protected _import<T>(
why: string,
moduleName: string,
{ alternatives = [], installTip = moduleName }: ImportOptions = {},
// eslint-disable-next-line @typescript-eslint/no-explicit-any... | protected _patch<T>(name: string, unpatched: T): T {
if (name in this._patches) {
logger.debug('patching', name) | random_line_split |
dir-reader.js | // A thing that emits "entry" events with Reader objects
// Pausing it causes it to stop emitting entry events, and also
// pauses the current entry if there is one.
module.exports = DirReader
var fs = require('graceful-fs')
var inherits = require('inherits')
var path = require('path')
var Reader = require('./reader.... | throw new Error('Non-directory type ' + props.type)
}
self.entries = null
self._entries = []
self._index = -1
self._paused = false
self._length = -1
if (props.sort) {
this.sort = props.sort
}
Reader.call(this, props)
}
DirReader.prototype._getEntries = function () {
var self = this
//... | random_line_split | |
dir-reader.js | // A thing that emits "entry" events with Reader objects
// Pausing it causes it to stop emitting entry events, and also
// pauses the current entry if there is one.
module.exports = DirReader
var fs = require('graceful-fs')
var inherits = require('inherits')
var path = require('path')
var Reader = require('./reader.... |
})
}
// start walking the dir, and emit an "entry" event for each one.
DirReader.prototype._read = function () {
var self = this
if (!self.entries) return self._getEntries()
if (self._paused || self._currentEntry || self._aborted) {
// console.error('DR paused=%j, current=%j, aborted=%j', self._paused, ... | {
self._length = self.entries.length
if (typeof self.sort === 'function') {
self.entries = self.entries.sort(self.sort.bind(self))
}
self._read()
} | identifier_body |
dir-reader.js | // A thing that emits "entry" events with Reader objects
// Pausing it causes it to stop emitting entry events, and also
// pauses the current entry if there is one.
module.exports = DirReader
var fs = require('graceful-fs')
var inherits = require('inherits')
var path = require('path')
var Reader = require('./reader.... |
})
entry.on('stat', function (props) {
self.emit('_entryStat', entry, props)
if (entry._aborted) return
if (entry._paused) {
entry.once('resume', function () {
self.emit('entryStat', entry, props)
})
} else self.emit('entryStat', entry, props)
})
entr... | {
self.resume(who)
} | conditional_block |
dir-reader.js | // A thing that emits "entry" events with Reader objects
// Pausing it causes it to stop emitting entry events, and also
// pauses the current entry if there is one.
module.exports = DirReader
var fs = require('graceful-fs')
var inherits = require('inherits')
var path = require('path')
var Reader = require('./reader.... | () {
if (ended) return
ended = true
self.emit('childEnd', entry)
self.emit('entryEnd', entry)
self._currentEntry = null
if (!self._paused) {
self._read()
}
}
// XXX Remove this. Works in node as of 0.6.2 or so.
// Long filenames should not break stuff.
... | onend | identifier_name |
template.py | metadata = {
"sample_name": "",
"group_name": "",
"file_names": "",
"sequencing_platform": "",
"sequencing_type": "",
"pre_assembled": "",
"sample_type": "",
"organism": "",
"strain": "",
"subtype": {},
"country": "",
"region": "",
"city": "",
"zip_code": "",
... | "release_date": "",
"email_address": "",
"notes": "",
"batch": "true"
}
default = {
"mandatory": [
"sequencing_platform",
"sequencing_type",
"collection_date"
],
"seed": {
"pre_assembled": "no",
"country": "unknown",
"isolation_source": "unkno... | random_line_split | |
numbers.rs | //! Functions operating on numbers.
use rand::{Rng, SeedableRng, StdRng};
use std::sync::Mutex;
use remacs_macros::lisp_fn;
use remacs_sys::{EmacsInt, INTMASK};
use lisp::LispObject;
use lisp::defsubr;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT i... | pub fn integer_or_marker_p(object: LispObject) -> bool {
object.is_marker() || object.is_integer()
}
/// Return t if OBJECT is a non-negative integer.
#[lisp_fn]
pub fn natnump(object: LispObject) -> bool {
object.is_natnum()
}
/// Return t if OBJECT is a number (floating point or integer).
#[lisp_fn]
pub fn ... |
/// Return t if OBJECT is an integer or a marker (editor pointer).
#[lisp_fn] | random_line_split |
numbers.rs | //! Functions operating on numbers.
use rand::{Rng, SeedableRng, StdRng};
use std::sync::Mutex;
use remacs_macros::lisp_fn;
use remacs_sys::{EmacsInt, INTMASK};
use lisp::LispObject;
use lisp::defsubr;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT i... |
/// Return t if OBJECT is a non-negative integer.
#[lisp_fn]
pub fn natnump(object: LispObject) -> bool {
object.is_natnum()
}
/// Return t if OBJECT is a number (floating point or integer).
#[lisp_fn]
pub fn numberp(object: LispObject) -> bool {
object.is_number()
}
/// Return t if OBJECT is a number or a ... | {
object.is_marker() || object.is_integer()
} | identifier_body |
numbers.rs | //! Functions operating on numbers.
use rand::{Rng, SeedableRng, StdRng};
use std::sync::Mutex;
use remacs_macros::lisp_fn;
use remacs_sys::{EmacsInt, INTMASK};
use lisp::LispObject;
use lisp::defsubr;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT i... |
if let Some(limit) = limit.as_fixnum() {
// Return the remainder, except reject the rare case where
// get_random returns a number so close to INTMASK that the
// remainder isn't random.
loop {
let val: EmacsInt = rng.gen();
let remainder = val.abs() % limit... | {
let values: Vec<usize> = s.as_slice().iter().map(|&x| x as usize).collect();
rng.reseed(&values);
} | conditional_block |
numbers.rs | //! Functions operating on numbers.
use rand::{Rng, SeedableRng, StdRng};
use std::sync::Mutex;
use remacs_macros::lisp_fn;
use remacs_sys::{EmacsInt, INTMASK};
use lisp::LispObject;
use lisp::defsubr;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT i... | (object: LispObject) -> bool {
object.is_number() || object.is_marker()
}
/// Return a pseudo-random number.
/// All integers representable in Lisp, i.e. between `most-negative-fixnum'
/// and `most-positive-fixnum', inclusive, are equally likely.
///
/// With positive integer LIMIT, return random number in interv... | number_or_marker_p | identifier_name |
ToolbarUtils.ts | import { Waiter } from '@ephox/agar';
import { Type } from '@ephox/katamari';
import { TinyUiActions } from '@ephox/mcagar';
import { Height, SugarElement, SugarLocation, Width } from '@ephox/sugar';
import { assert } from 'chai';
import Editor from 'tinymce/core/api/Editor';
import { ToolbarMode } from 'tinymce/theme... | await pOpenMore(ToolbarMode.floating);
await pAssertFloatingToolbarPosition(editor, getTop, 105, 465);
if (Type.isNonNullable(pActions)) {
await pActions();
}
await pCloseMore(ToolbarMode.floating);
};
export {
pAssertFloatingToolbarHeight,
pAssertFloatingToolbarPosition,
pOpenFloatingToolbarAndAss... | const height = Height.get(toolbar);
assert.approximately(height, expectedHeight, 1, `Drawer height ${height}px should be ~${expectedHeight}px`);
};
const pOpenFloatingToolbarAndAssertPosition = async (editor: Editor, getTop: () => number, pActions?: () => Promise<void>) => { | random_line_split |
ToolbarUtils.ts | import { Waiter } from '@ephox/agar';
import { Type } from '@ephox/katamari';
import { TinyUiActions } from '@ephox/mcagar';
import { Height, SugarElement, SugarLocation, Width } from '@ephox/sugar';
import { assert } from 'chai';
import Editor from 'tinymce/core/api/Editor';
import { ToolbarMode } from 'tinymce/theme... |
await pCloseMore(ToolbarMode.floating);
};
export {
pAssertFloatingToolbarHeight,
pAssertFloatingToolbarPosition,
pOpenFloatingToolbarAndAssertPosition
};
| {
await pActions();
} | conditional_block |
extract_cats_dogs.py | """One-time script for extracting all the cat and dog images from CIFAR-10."""
import cPickle
import numpy as np
from PIL import Image
TRAIN_FILES = ['cifar-10-batches-py/data_batch_%d' % i for i in range(1,6)]
TEST_FILE = 'test_batch'
CAT_INPUT_LABEL = 3
DOG_INPUT_LABEL = 5
CAT_OUTPUT_LABEL = 1
DOG_OUTPUT_LABEL = ... |
if label == DOG_INPUT_LABEL:
num_dogs += 1
# Copy the cats/dogs into new array
images = np.empty((num_cats + num_dogs, 32, 32, 3), dtype=np.uint8)
labels = np.empty((num_cats + num_dogs), dtype=np.uint8)
index = 0
for data_batch in data:
for batch_index, label in enumerate(data_batch['labels']):
if l... | num_cats += 1 | conditional_block |
extract_cats_dogs.py | """One-time script for extracting all the cat and dog images from CIFAR-10."""
import cPickle
import numpy as np
from PIL import Image
TRAIN_FILES = ['cifar-10-batches-py/data_batch_%d' % i for i in range(1,6)]
TEST_FILE = 'test_batch'
CAT_INPUT_LABEL = 3
DOG_INPUT_LABEL = 5
CAT_OUTPUT_LABEL = 1
DOG_OUTPUT_LABEL = ... | (file):
with open(file, 'rb') as fo:
dict = cPickle.load(fo)
return dict
data = []
# Count number of cats/dogs
num_cats = 0
num_dogs = 0
for data_file in TRAIN_FILES:
d = unpickle(data_file)
data.append(d)
for label in d['labels']:
if label == CAT_INPUT_LABEL:
num_cats += 1
if label ==... | unpickle | identifier_name |
extract_cats_dogs.py | """One-time script for extracting all the cat and dog images from CIFAR-10."""
import cPickle
import numpy as np
from PIL import Image
TRAIN_FILES = ['cifar-10-batches-py/data_batch_%d' % i for i in range(1,6)]
TEST_FILE = 'test_batch'
CAT_INPUT_LABEL = 3
DOG_INPUT_LABEL = 5
CAT_OUTPUT_LABEL = 1
DOG_OUTPUT_LABEL = ... |
data = []
# Count number of cats/dogs
num_cats = 0
num_dogs = 0
for data_file in TRAIN_FILES:
d = unpickle(data_file)
data.append(d)
for label in d['labels']:
if label == CAT_INPUT_LABEL:
num_cats += 1
if label == DOG_INPUT_LABEL:
num_dogs += 1
# Copy the cats/dogs into new array
images ... | with open(file, 'rb') as fo:
dict = cPickle.load(fo)
return dict | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.