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 |
|---|---|---|---|---|
build.js | function load(/*String*/fileName){
//summary: opens the file at fileName and evals the contents as JavaScript.
//Read the file
var fileContents = readFile(fileName);
//Eval the contents.
var Context = Packages.org.mozilla.javascript.Context;
var context = Context.enter();
try{
return context.evaluateString(... |
if(cdnType != "google" && cdnType != "aol"){
return "invalide CDN type";
}
if(optimizeType != "comments" && optimizeType != "shrinksafe"
&& optimizeType != "none" && optimizeType != "shrinksafe.keepLines"){
return "invalid optimize type";
}
if(!dependencies.match(/^[\w\-\,\s\.]+$/)){
return "inva... | {
return "invalid version";
} | conditional_block |
build.js | function | (/*String*/fileName){
//summary: opens the file at fileName and evals the contents as JavaScript.
//Read the file
var fileContents = readFile(fileName);
//Eval the contents.
var Context = Packages.org.mozilla.javascript.Context;
var context = Context.enter();
try{
return context.evaluateString(this, fileCon... | load | identifier_name |
Animation.ts | import { Node } from './Node';
import { Transformation } from './Transformation';
import { remove } from 'lodash';
/**
* Parameters that an end user passes in to define a keyframed animation.
*/
export type AnimationDescriptionParams = {
/**
* The node being animated.
*/
node: Node;
/**
... | * @param {AnimationDescriptionParams} params The information about the new animation.
*/
export function create(params: AnimationDescriptionParams) {
const animation = {
node: params.node,
to: params.to,
finalTransform: null,
start: params.start !== ... | }
/**
* Creates and queues up an animation with the given parameters.
* | random_line_split |
Animation.ts | import { Node } from './Node';
import { Transformation } from './Transformation';
import { remove } from 'lodash';
/**
* Parameters that an end user passes in to define a keyframed animation.
*/
export type AnimationDescriptionParams = {
/**
* The node being animated.
*/
node: Node;
/**
... | () {
queue.length = 0;
current.length = 0;
}
/**
* @returns {number} The current time, in milliseconds since the epoch.
*/
export function now(): number {
return new Date().getTime();
}
/**
* Creates and queues up an animation with the given parameters.
... | resetAll | identifier_name |
Animation.ts | import { Node } from './Node';
import { Transformation } from './Transformation';
import { remove } from 'lodash';
/**
* Parameters that an end user passes in to define a keyframed animation.
*/
export type AnimationDescriptionParams = {
/**
* The node being animated.
*/
node: Node;
/**
... |
}
/**
* Updates the nodes for all currently active animations, interpolating between the given
* animation states.
*/
function applyCurrentAnimations(currentTime: number) {
// TODO: use curves that aren't linear
current.forEach((animation: AnimationDescription) => {
... | {
current.push(queue[0]);
queue.shift();
} | conditional_block |
Animation.ts | import { Node } from './Node';
import { Transformation } from './Transformation';
import { remove } from 'lodash';
/**
* Parameters that an end user passes in to define a keyframed animation.
*/
export type AnimationDescriptionParams = {
/**
* The node being animated.
*/
node: Node;
/**
... |
/**
* Updates the state of all animations according to the current time.
*/
export function tick() {
const currentTime = Animation.now();
dequeueNewAnimations(currentTime);
applyCurrentAnimations(currentTime);
removeFinishedAnimations(currentTime);
}
/**
... | {
const animation = {
node: params.node,
to: params.to,
finalTransform: null,
start: params.start !== undefined ? params.start : Animation.now(),
duration: params.duration,
times: params.times !== undefined ? params.times : 1,
r... | identifier_body |
highlightsidebar.js | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed un... | .waitForElementPresent('.add-new-database-btn', waitTime, false)
.click('a[href="#/replication"]')
.pause(1000)
.waitForElementVisible('.replication__activity_header-btn', waitTime, false)
.assert.cssClassPresent('li[data-nav-name="Replication"]', 'active')
.end();
}
}; | .loginToGUI()
.url(baseUrl) | random_line_split |
tnaflix.py | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
parse_duration,
fix_xml_ampersands,
)
class TNAFlixIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?tnaflix\.com/(?P<cat_id>[\w-]+)/(?P<display_id>[\w-]+)/video(?P<id>\d+)'
_TITLE_REGEX = r... | 'format_id': format_id,
}
m = re.search(r'^(\d+)', format_id)
if m:
fmt['height'] = int(m.group(1))
formats.append(fmt)
self._sort_formats(formats)
return {
'id': video_id,
'display_id': display_id,
... | format_id = item.find('res').text
fmt = {
'url': video_url, | random_line_split |
tnaflix.py | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
parse_duration,
fix_xml_ampersands,
)
class TNAFlixIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?tnaflix\.com/(?P<cat_id>[\w-]+)/(?P<display_id>[\w-]+)/video(?P<id>\d+)'
_TITLE_REGEX = r... |
formats.append(fmt)
self._sort_formats(formats)
return {
'id': video_id,
'display_id': display_id,
'title': title,
'description': description,
'thumbnail': thumbnail,
'duration': duration,
'age_limit': age_... | fmt['height'] = int(m.group(1)) | conditional_block |
tnaflix.py | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
parse_duration,
fix_xml_ampersands,
)
class TNAFlixIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?tnaflix\.com/(?P<cat_id>[\w-]+)/(?P<display_id>[\w-]+)/video(?P<id>\d+)'
_TITLE_REGEX = r... | cfg_xml = self._download_xml(
cfg_url, display_id, note='Downloading metadata',
transform_source=fix_xml_ampersands)
thumbnail = cfg_xml.find('./startThumb').text
formats = []
for item in cfg_xml.findall('./quality/item'):
video_url = re.sub('speed=\... | mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id')
display_id = mobj.group('display_id')
webpage = self._download_webpage(url, display_id)
title = self._html_search_regex(
self._TITLE_REGEX, webpage, 'title') if self._TITLE_REGEX else self._og_search_title(we... | identifier_body |
tnaflix.py | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
parse_duration,
fix_xml_ampersands,
)
class | (InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?tnaflix\.com/(?P<cat_id>[\w-]+)/(?P<display_id>[\w-]+)/video(?P<id>\d+)'
_TITLE_REGEX = r'<title>(.+?) - TNAFlix Porn Videos</title>'
_DESCRIPTION_REGEX = r'<h3 itemprop="description">([^<]+)</h3>'
_CONFIG_REGEX = r'flashvars\.config\s*=\s*escape\("([^... | TNAFlixIE | identifier_name |
wrap_unhygienic_example.rs | // Copyright 2017 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 ... | // (c)
::unhygienic_example::unhygienic_macro!();
// ^ Even though we invoke an unhygienic macro, `hygienic_macro` remains hygienic.
// In the above expansion:
// (1) `my_crate` always resolves to (b) regardless of invocation site.
// (2) The defined function `f` is only usable inside this macro de... | {} | identifier_body |
wrap_unhygienic_example.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
#[allow(unused)]
fn test_hygienic_macro() {
hygienic_macro!();
fn f() {} // (d) no conflict
f(); // resolves to (d)
}
fn main() {} |
f();
} | random_line_split |
wrap_unhygienic_example.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {}
| main | identifier_name |
texture.rs | use glium::{self, backend::Facade, texture::Texture2d};
use crate::backend::{Direction, Position, ASSETS};
pub struct Textures {
pub crate_: Texture2d,
pub floor: Texture2d,
pub goal: Texture2d,
pub wall: Texture2d,
pub worker: Texture2d,
}
impl Textures {
/// Load all textures.
pub fn ne... | (display: &dyn Facade, name: &str) -> Texture2d {
let mut path = ASSETS.join("images");
path.push(name);
path.set_extension("png");
let image = image::open(path).unwrap().to_rgba();
let image_dimensions = image.dimensions();
let image =
glium::texture::RawImage2d::from_raw_rgba_reversed(... | load | identifier_name |
texture.rs | use glium::{self, backend::Facade, texture::Texture2d};
use crate::backend::{Direction, Position, ASSETS};
pub struct Textures {
pub crate_: Texture2d,
pub floor: Texture2d,
pub goal: Texture2d,
pub wall: Texture2d,
pub worker: Texture2d,
}
impl Textures {
/// Load all textures.
pub fn ne... | }
/// Create a rectangle covering the entire viewport.
pub fn full_screen() -> Vec<Vertex> {
lrtb_to_vertices(-1.0, 1.0, -1.0, 1.0, Direction::Left)
} | random_line_split | |
texture.rs | use glium::{self, backend::Facade, texture::Texture2d};
use crate::backend::{Direction, Position, ASSETS};
pub struct Textures {
pub crate_: Texture2d,
pub floor: Texture2d,
pub goal: Texture2d,
pub wall: Texture2d,
pub worker: Texture2d,
}
impl Textures {
/// Load all textures.
pub fn ne... |
/// Create a rectangle covering the entire viewport.
pub fn full_screen() -> Vec<Vertex> {
lrtb_to_vertices(-1.0, 1.0, -1.0, 1.0, Direction::Left)
}
| {
let left = 2.0 * pos.x as f32 / columns as f32 - 1.0;
let right = left + 2.0 / columns as f32;
let bottom = -2.0 * pos.y as f32 / rows as f32 + 1.0;
let top = bottom - 2.0 / rows as f32;
lrtb_to_vertices(left, right, top, bottom, Direction::Left)
} | identifier_body |
Router.d.ts | import { Component, ComponentClass, ClassAttributes, ReactNode, StatelessComponent } from "react";
import {
Action,
History,
Href,
Location,
LocationDescriptor,
LocationKey,
LocationState,
Path,
Pathname,
Query,
Search
} from "history";
import { PlainRoute } from "react-route... | routes?: RouteConfig;
history?: History;
createElement?(component: RouteComponent, props: any): any;
onError?(error: any): any;
onUpdate?(): any;
render?(props: any): ReactNode;
}
type Router = ComponentClass<RouterProps>;
declare const Router: Router;
export default Router; | routeParams: R;
}
export interface RouterProps extends ClassAttributes<any> { | random_line_split |
util-gis.js | /*
* Conversión de UTM to LngLat *
* Example: UtmToLatLng("638149","5857111","32718");
* Return: Object(lng,lat)
*/
function UtmToLatLng(x,y,zonaUTM)
{ |
/* Convert LatLng to UTM*/
/* Example: LatLngToUtm(-73.43871,-37.42252) */
/* Return: Object(x,y,zone)
*/
function LatLngToUtm(lng,lat)
{
// get zone UTM from Lng
zona=parseInt((lng / 6) + 31);
zonaUTM="327"+zona;
Proj4js.defs["EPSG:" + zonaUTM] = "+proj=utm +zone=" + zona + " +south +ellps=WGS84 +datum=WGS84 +un... |
var zona=zonaUTM.substring(zonaUTM.length-2,zonaUTM.length);
Proj4js.defs["EPSG:" + zonaUTM] = "+proj=utm +zone=" + zona + " +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs";
var source = new Proj4js.Proj('EPSG:'+zonaUTM); // orignn UTM18
var dest = new Proj4js.Proj('EPSG:4326'); // Destino LatLng
... | identifier_body |
util-gis.js | /*
* Conversión de UTM to LngLat *
* Example: UtmToLatLng("638149","5857111","32718");
* Return: Object(lng,lat)
*/
function UtmToLatLng(x,y,zonaUTM)
{
var zona=zonaUTM.substring(zonaUTM.length-2,zonaUTM.length);
Proj4js.defs["EPSG:" + zonaUTM] = "+proj=utm +zone=" + zona + " +south +ellps=WGS84 +datum=WGS84 +uni... | lng,lat)
{
// get zone UTM from Lng
zona=parseInt((lng / 6) + 31);
zonaUTM="327"+zona;
Proj4js.defs["EPSG:" + zonaUTM] = "+proj=utm +zone=" + zona + " +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs"; // UTM12
var source = new Proj4js.Proj('EPSG:4326'); // Origen LatLng
var dest = new Proj4js.Proj('EPSG:'+... | atLngToUtm( | identifier_name |
util-gis.js | /*
* Conversión de UTM to LngLat *
* Example: UtmToLatLng("638149","5857111","32718");
* Return: Object(lng,lat)
*/
function UtmToLatLng(x,y,zonaUTM)
{ | var source = new Proj4js.Proj('EPSG:'+zonaUTM); // orignn UTM18
var dest = new Proj4js.Proj('EPSG:4326'); // Destino LatLng
// transforming point coordinates
var p = new Proj4js.Point(x,y); // pto x,y
//console.log(Proj4js.transform(source, dest, p));
var pto=Proj4js.transform(source, dest,... | var zona=zonaUTM.substring(zonaUTM.length-2,zonaUTM.length);
Proj4js.defs["EPSG:" + zonaUTM] = "+proj=utm +zone=" + zona + " +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs"; | random_line_split |
bench.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | roughput!(easy0_32, easy0(), 32);
throughput!(easy0_1K, easy0(), 1<<10);
throughput!(easy0_32K, easy0(), 32<<10);
throughput!(easy0_1MB, easy0(), 1<<20);
throughput!(easy1_32, easy1(), 32);
throughput!(easy1_1K, easy1(), 1<<10);
throughput!(easy1_32K, easy1(), 32<<10);
throughput!(easy1_1MB, easy1(), 1<<20);
throughp... | let mut rng = thread_rng();
let mut bytes = rng.gen_ascii_chars().map(|n| n as u8).take(n)
.collect::<Vec<u8>>();
for (i, b) in bytes.iter_mut().enumerate() {
if i % 20 == 0 {
*b = b'\n'
}
}
String::from_utf8(bytes).unwrap()
}
th | identifier_body |
bench.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
#[bench]
fn anchored_literal_short_match(b: &mut Bencher) {
let re = regex!("^.bc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
#[bench]
fn anchored_literal_long_match(b: &mut Bencher) {
let re = regex!("^.bc(d|e)");
let text: String = repeat("abcdefghijklmnopq... | fn anchored_literal_long_non_match(b: &mut Bencher) {
let re = regex!("^zbc(d|e)");
let text: String = repeat("abcdefghijklmnopqrstuvwxyz").take(15).collect();
b.iter(|| re.is_match(&text)); | random_line_split |
bench.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (b: &mut Bencher, re: Regex, text: &str) {
b.iter(|| if !re.is_match(text) { panic!("no match") });
}
#[bench]
fn no_exponential(b: &mut Bencher) {
let n = 100;
let regex_string = format!(
"{}{}",
repeat("a?").take(n).collect::<String>(),
repeat("a").take(n).collect::<String>());
... | bench_assert_match | identifier_name |
bench.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | );
}
#[bench]
fn no_exponential(b: &mut Bencher) {
let n = 100;
let regex_string = format!(
"{}{}",
repeat("a?").take(n).collect::<String>(),
repeat("a").take(n).collect::<String>());
let re = Regex::new(®ex_string).unwrap();
let text: String = repeat("a").take(n).collect();
... | { panic!("no match") } | conditional_block |
redis.js | 'use strict';
/**
* @module
* @copyright paywell Team at byteskode <www.byteskode.com>
* @description redis client factories
* @since 0.1.0
* @author lally elias<lallyelias87@gmail.com, lally.elias@byteskode.com>
* @singleton
* @public
*/
//dependencies
const path = require('path');
const redis = require('r... |
//remember created client(s) for later safe shutdown
exports._clients = _.compact([].concat(exports._clients).concat(client));
return client;
};
/**
* @function
* @name init
* @description initialize redis client and pubsub
* @return {Object} redis client
* @since 0.1.0
* @public
*/
exports.init = exp... | {
client.select(options.redis.db);
} | conditional_block |
redis.js | 'use strict';
/**
* @module
* @copyright paywell Team at byteskode <www.byteskode.com>
* @description redis client factories
* @since 0.1.0
* @author lally elias<lallyelias87@gmail.com, lally.elias@byteskode.com>
* @singleton
* @public
*/
//dependencies
const path = require('path');
const redis = require('r... | exports.subscriber._id = Date.now();
}
//exports pub/sub clients
return { publisher: exports.publisher, subscriber: exports.subscriber };
};
/**
* @function
* @name multi
* @description initialize redis multi command object
* @return {Object} redis multi command object
* @since 0.3.0
* @see {@link ht... | exports.subscriber = exports.createClient(); | random_line_split |
date.ts | // automatically generated by the FlatBuffers compiler, do not modify
import * as flatbuffers from 'flatbuffers';
import { DateUnit } from './date-unit.js';
/**
* Date is either a 32-bit or 64-bit signed integer type representing an
* elapsed time since UNIX epoch (1970-01-01), stored in either of two units:
*
... |
static addUnit(builder:flatbuffers.Builder, unit:DateUnit) {
builder.addFieldInt16(0, unit, DateUnit.MILLISECOND);
}
static endDate(builder:flatbuffers.Builder):flatbuffers.Offset {
const offset = builder.endObject();
return offset;
}
static createDate(builder:flatbuffers.Builder, unit:DateUnit):flatbuffers.O... | {
builder.startObject(1);
} | identifier_body |
date.ts | // automatically generated by the FlatBuffers compiler, do not modify
import * as flatbuffers from 'flatbuffers';
import { DateUnit } from './date-unit.js';
/**
* Date is either a 32-bit or 64-bit signed integer type representing an
* elapsed time since UNIX epoch (1970-01-01), stored in either of two units:
*
... | (i:number, bb:flatbuffers.ByteBuffer):Date {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsDate(bb:flatbuffers.ByteBuffer, obj?:Date):Date {
return (obj || new Date()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsDate(bb:flatbuffers.ByteBuffer, obj?:Da... | __init | identifier_name |
date.ts | // automatically generated by the FlatBuffers compiler, do not modify
import * as flatbuffers from 'flatbuffers';
import { DateUnit } from './date-unit.js';
/**
* Date is either a 32-bit or 64-bit signed integer type representing an
* elapsed time since UNIX epoch (1970-01-01), stored in either of two units:
*
... | }
static createDate(builder:flatbuffers.Builder, unit:DateUnit):flatbuffers.Offset {
Date.startDate(builder);
Date.addUnit(builder, unit);
return Date.endDate(builder);
}
} | const offset = builder.endObject();
return offset; | random_line_split |
ModelNodesLoader.js | Ext.namespace("Inubit.WebModeler");
Inubit.WebModeler.ModelNodesLoader = Ext.extend(Inubit.WebModeler.Loader, {
constructor : function (config) {
this.chunkSize = 25;
this.loaded = 0;
this.toLoad = 0;
this.currentChunk = 0;
this.chunks = new Array();
this.nodes = new Array();
this.mode = config.mode;
... | else {
// do something on error
}
},
failure : function(){
this.fireEvent("error");
// do something on error
}
});
},
loadNextChunk : function( canvas ) {
var chunk = this.chunks[this.currentChunk];
if(!Ext.isDefined(chunk)) {
... | {
// forbidden..... do something
} | conditional_block |
ModelNodesLoader.js | Ext.namespace("Inubit.WebModeler");
Inubit.WebModeler.ModelNodesLoader = Ext.extend(Inubit.WebModeler.Loader, {
constructor : function (config) {
this.chunkSize = 25;
this.loaded = 0;
this.toLoad = 0;
this.currentChunk = 0;
this.chunks = new Array();
this.nodes = new Array();
this.mode = config.mode;
... | this.loaded = 0;
this.loadNextChunk(canvas);
}
},
getNodes : function() {
return this.nodes;
}
}); | random_line_split | |
index.js | import {Layer} from "stratocacher";
import LRU from "lru-cache";
import Q from "q";
const CACHES = {};
function cache(layer) {
const {cid} = layer;
if (!CACHES[cid]) {
CACHES[cid] = LRU({max: layer.opt.max});
}
return CACHES[cid];
}
export default class LayerLRU extends Layer {
static reset() {
super.reset... | (layer){
const {opt} = layer;
return opt.copy || !opt.hasOwnProperty('copy');
}
| shouldCopy | identifier_name |
index.js | import {Layer} from "stratocacher";
import LRU from "lru-cache";
import Q from "q";
const CACHES = {};
function cache(layer) {
const {cid} = layer;
if (!CACHES[cid]) {
CACHES[cid] = LRU({max: layer.opt.max});
}
return CACHES[cid];
}
export default class LayerLRU extends Layer {
static reset() {
super.reset... |
cache(this).set(this.key, val);
return Q(); // We're synchronous but need to return a promise.
}
}
function shouldCopy(layer){
const {opt} = layer;
return opt.copy || !opt.hasOwnProperty('copy');
}
| {
val = JSON.stringify(val);
} | conditional_block |
index.js | import {Layer} from "stratocacher";
import LRU from "lru-cache";
import Q from "q";
| function cache(layer) {
const {cid} = layer;
if (!CACHES[cid]) {
CACHES[cid] = LRU({max: layer.opt.max});
}
return CACHES[cid];
}
export default class LayerLRU extends Layer {
static reset() {
super.reset();
Object.keys(CACHES).forEach(k => delete CACHES[k]);
}
get() {
let val = cache(this).get(this.k... | const CACHES = {}; | random_line_split |
utils.js | exports.readTemplate = function(name) {
return fs.readFileSync(path.join(__dirname,'template',name),'utf8');
};
exports.evaluateTemplate = function(name, o) {
return _.template(exports.readTemplate(name), o);
};
exports.getAndValidateProjectPaths = function(argPath, opts) {
opts = opts || {};
var projectPath = pa... | (id) {
var wFile;
try {
wFile = resolve.sync(path.join(CONST.NPM_WIDGET_PREFIX + id, 'widget'), { basedir: path.join(appDir,'..'), extensions | findWidgetAsNodeModule | identifier_name |
utils.js | Paths.push(path.join(__dirname,'..','widgets'));
widgetPaths.push(path.join(appDir,'widgets'));
_.each(widgetPaths, function(widgetPath) {
if (fs.existsSync(widgetPath)) {
var wFiles = fs.readdirSync(widgetPath);
for (var i = 0; i < wFiles.length; i++) {
var wDir = path.join(widgetPath,wFiles[i]);
if... | {
throw new TypeError('bad argument');
} | conditional_block | |
utils.js | indexBase: path.join(CONST.DIR.CONTROLLER,CONST.NAME_DEFAULT + '.' + CONST.FILE_EXT.CONTROLLER)
};
paths.index = path.join(paths.app,paths.indexBase);
paths.assets = path.join(paths.app,'assets');
paths.resources = path.join(paths.project,'Resources');
paths.resourcesAlloy = path.join(paths.resources,'alloy');
... | {
var wFile;
try {
wFile = resolve.sync(path.join(CONST.NPM_WIDGET_PREFIX + id, 'widget'), { basedir: path.join(appDir,'..'), extensions: [ '.json' ], paths: paths() });
} catch (err) {
return;
}
var collection = parseManifestAsCollection(wFile);
if (collection.manifest.id !== id) {
return logger.... | identifier_body | |
utils.js | if (!fs.existsSync(path.join(paths.project,'tiapp.xml'))) {
exports.die('Invalid Titanium project path (no tiapp.xml) at "' + paths.project + '"');
} else if (!fs.existsSync(paths.app)) {
exports.die('Alloy "app" directory does not exist at "' + paths.app + '"');
} else if (!fs.existsSync(paths.index) && (opts.c... | }
| random_line_split | |
mutex.rs | == N {
/// tx.send(()).unwrap();
/// }
/// // the lock is unlocked here when `data` goes out of scope.
/// });
/// }
///
/// rx.recv().unwrap();
/// ```
///
/// To recover from a poisoned mutex:
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let lock = Arc::ne... | // dropped, that's not our job)
unsafe { self.inner.lock.destroy() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + fmt::Debug + 'static> fmt::Debug for Mutex<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.try_lock() {
Ok(guard) =>... | #[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Drop for Mutex<T> {
fn drop(&mut self) {
// This is actually safe b/c we know that there is no further usage of
// this mutex (it's up to the user to arrange for a mutex to get | random_line_split |
mutex.rs | mutex to get
// dropped, that's not our job)
unsafe { self.inner.lock.destroy() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + fmt::Debug + 'static> fmt::Debug for Mutex<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.try_lock() {
... | Unwinder | identifier_name | |
cgs.rs | use super::*;
pub fn new() -> System {
System {
name: "CGS",
module: "cgs",
doc_prelude: "The Gaussian CGS unit system
Note: this system is incomplete. More derived units and constants are coming.
",
base: base_units!(
SQRTCM: SqrtCentimeter, sqrtcm;
SQRTG:... |
S2: Second2 = Second * Second;
S3: Second3 = Second2 * Second;
S4: Second4 = Second3 * Second;
CMPS: CentimeterPerSecond = Centimeter / Second, Velocity;
CMPS3: CentimeterPerSecond3 = Centimeter / Second3, Jerk;
CMPS4: CentimeterPerSecond4 = Cent... | CM: Centimeter = SqrtCentimeter * SqrtCentimeter, Length;
G: Gram = SqrtGram * SqrtGram, Mass;
CM2: Centimeter2 = Centimeter * Centimeter, Area;
CM3: Centimeter3 = Centimeter2 * Centimeter, Volume; | random_line_split |
cgs.rs | use super::*;
pub fn new() -> System |
S2: Second2 = Second * Second;
S3: Second3 = Second2 * Second;
S4: Second4 = Second3 * Second;
CMPS: CentimeterPerSecond = Centimeter / Second, Velocity;
CMPS3: CentimeterPerSecond3 = Centimeter / Second3, Jerk;
CMPS4: CentimeterPerSecond4 = Cent... | {
System {
name: "CGS",
module: "cgs",
doc_prelude: "The Gaussian CGS unit system
Note: this system is incomplete. More derived units and constants are coming.
",
base: base_units!(
SQRTCM: SqrtCentimeter, sqrtcm;
SQRTG: SqrtGram, sqrtg;
S: Secon... | identifier_body |
cgs.rs | use super::*;
pub fn | () -> System {
System {
name: "CGS",
module: "cgs",
doc_prelude: "The Gaussian CGS unit system
Note: this system is incomplete. More derived units and constants are coming.
",
base: base_units!(
SQRTCM: SqrtCentimeter, sqrtcm;
SQRTG: SqrtGram, sqrtg;
... | new | identifier_name |
html_writer.py | self.div_counter = 0
pass
def relative_to_full_path(self, relpath):
raise Exception("class not implemented")
def write(self, s):
raise Exception("class not implemented")
def write_header(self):
self.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "h... | import numpy as np
import xml.dom.minidom
class BaseHtmlWriter:
def __init__(self): | random_line_split | |
html_writer.py | raise Exception("class not implemented")
def write_header(self):
self.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')
self.write('<head>\n')
self.write('<script type="text/javascript" src="expandCollapse.js"></script>... | def __init__(self, filename, force_path_creation=True, flush_always=True):
BaseHtmlWriter.__init__(self)
self.filename = filename
self.filepath = os.path.dirname(filename)
self.flush_always = flush_always
if not os.path.exists(self.filepath):
if force_path_creation:
... | identifier_body | |
html_writer.py | relpath):
raise Exception("class not implemented")
def write(self, s):
raise Exception("class not implemented")
def write_header(self):
self.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')
self.write('<he... |
headers = sorted(headers)
self.write('<table border=%d>\n' % border)
self.write('<tr><td><b>' + '</b></td><td><b>'.join(headers) + '</b></td></tr>\n')
for i, rowdict in enumerate(rowdicts):
rowdict['#'] = '%d' % i
values = [to_string(rowdict.get(key,... | headers.add(to_string(key)) | conditional_block |
html_writer.py | relpath):
raise Exception("class not implemented")
def write(self, s):
raise Exception("class not implemented")
def write_header(self):
self.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')
self.write('<he... | (self, div_id=None, start_here=False, label='Show'):
if not div_id:
div_id = "DIV%05d" % self.div_counter
self.div_counter += 1
elif type(div_id) != types.StringType:
raise ValueError("HTML div ID must be a string")
self.write('<input type="button" class="butt... | insert_toggle | identifier_name |
PullRequest.ts | /*
* Copyright 2015-2017 Atomist Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | */
closedAt(): string;
/**
* contains - PullRequest -> Commit
*
* @returns {Commit[]}
*/
contains(): Commit[];
/**
* String
*
* @returns {string}
*/
createdAt(): string;
/**
* hasComment - PullRequest -> Comment
*
* @retu... | /**
* String
*
* @returns {string} | random_line_split |
schemas.js | import classic from 'ember-classic-decorator';
import { filterBy } from '@ember/object/computed';
import Service, { inject as service } from '@ember/service';
import RefParser from 'json-schema-ref-parser';
import request from 'ember-ajax/request';
import { task, all, timeout } from 'ember-concurrency';
import {
// i... |
return request(itm.uri)
.then((response) => {
// `response` is the data from the server
if (semver.valid(response.version)) {
itm.set('remoteVersion', response.version);
} else {
throw new Error('Invalid version');
}
... | } | random_line_split |
schemas.js | import classic from 'ember-classic-decorator';
import { filterBy } from '@ember/object/computed';
import Service, { inject as service } from '@ember/service';
import RefParser from 'json-schema-ref-parser';
import request from 'ember-ajax/request';
import { task, all, timeout } from 'ember-concurrency';
import {
// i... | extends Service {
init() {
super.init(...arguments);
/**
* Instance of JSON Schema $Ref Parser
*
* @method parser
* @protected
* @return {Object}
*/
this.parser = parser;
this.schemas = this.store.peekAll('schema');
}
@service
store;
@service
flashMessages;... | SchemasService | identifier_name |
schemas.js | import classic from 'ember-classic-decorator';
import { filterBy } from '@ember/object/computed';
import Service, { inject as service } from '@ember/service';
import RefParser from 'json-schema-ref-parser';
import request from 'ember-ajax/request';
import { task, all, timeout } from 'ember-concurrency';
import {
// i... |
return response;
})
.catch((error) => {
if (isNotFoundError(error)) {
this.flashMessages.danger(
`Could not load schema for "${itm.title}". Schema not found.`
);
} else {
this.flashMessages.danger(
... | {
throw new Error('Invalid version');
} | conditional_block |
no_0491_increasing_subsequences.rs | struct Solution;
impl Solution {
pub fn find_subsequences(nums: Vec<i32>) -> Vec<Vec<i32>> |
fn dfs(cur: usize, last: i32, nums: &Vec<i32>, temp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
if cur == nums.len() {
if temp.len() >= 2 {
ans.push(temp.clone());
}
return;
}
let cur_val = nums[cur];
if cur_val >= last {
... | {
let mut temp = Vec::new();
let mut ans = Vec::new();
Self::dfs(0, std::i32::MIN, &nums, &mut temp, &mut ans);
ans
} | identifier_body |
no_0491_increasing_subsequences.rs | struct Solution;
impl Solution {
pub fn find_subsequences(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut temp = Vec::new();
let mut ans = Vec::new();
Self::dfs(0, std::i32::MIN, &nums, &mut temp, &mut ans);
ans
}
fn dfs(cur: usize, last: i32, nums: &Vec<i32>, temp: &mut Vec<i32>... |
return;
}
let cur_val = nums[cur];
if cur_val >= last {
temp.push(cur_val);
Self::dfs(cur + 1, cur_val, nums, temp, ans);
temp.pop();
}
if cur_val != last {
Self::dfs(cur + 1, last, nums, temp, ans);
}
}
}
... | {
ans.push(temp.clone());
} | conditional_block |
no_0491_increasing_subsequences.rs | struct Solution;
impl Solution {
pub fn find_subsequences(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut temp = Vec::new();
let mut ans = Vec::new();
Self::dfs(0, std::i32::MIN, &nums, &mut temp, &mut ans);
ans
}
fn | (cur: usize, last: i32, nums: &Vec<i32>, temp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
if cur == nums.len() {
if temp.len() >= 2 {
ans.push(temp.clone());
}
return;
}
let cur_val = nums[cur];
if cur_val >= last {
temp.push... | dfs | identifier_name |
no_0491_increasing_subsequences.rs | struct Solution;
impl Solution {
pub fn find_subsequences(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut temp = Vec::new();
let mut ans = Vec::new();
Self::dfs(0, std::i32::MIN, &nums, &mut temp, &mut ans);
ans
}
fn dfs(cur: usize, last: i32, nums: &Vec<i32>, temp: &mut Vec<i32>... | }
} | random_line_split | |
installed.py | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | test.write('mocFromH.h', """\
#include <qobject.h>
class MyClass2 : public QObject {
Q_OBJECT;
public:
MyClass2();
public slots:
void myslot();
};
void mocFromH();
""")
test.write('mocFromH.cpp', """\
#include "mocFromH.h"
MyClass2::MyClass2() : QObject() {}
void MyClass2::myslot() {}
void mocFromH(... | random_line_split | |
installed.py | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... |
QTDIR = os.environ['QTDIR']
PATH = os.environ['PATH']
os.environ['QTDIR']=''
os.environ['PATH']='.'
test.run(stderr=None, arguments="-c bld/test_realqt" + TestSCons._exe)
expect1 = "scons: warning: Could not detect qt, using empty QTDIR"
expect2 = "scons: warning: Could not detect qt, using moc executable as a hint... | sys.stdout.write('test_realqt returned status %s\n' % test.status)
test.fail_test() | conditional_block |
main_raster.py | import time
from PyQt4 import QtGui, QtCore, QtOpenGL
from PyQt4.QtOpenGL import QGLWidget
import OpenGL.GL as gl
import OpenGL.arrays.vbo as glvbo
import numpy as np
import raster
import slider
import draw_texture
import qt_helpers
raster_width = 1024
raster_height = 64
raster_n_neurons = 64
spikes_per_frame = 5
c... | (self):
# program for drawing spikes
self.raster = raster.RasterProgram(raster_width, raster_height,
raster_n_neurons)
self.raster.link()
# program for fading sparkleplot
self.slider = slider.SlideProgram(raster_width, raster_height)
... | initializeGL | identifier_name |
main_raster.py | import time
from PyQt4 import QtGui, QtCore, QtOpenGL
from PyQt4.QtOpenGL import QGLWidget
import OpenGL.GL as gl
import OpenGL.arrays.vbo as glvbo
import numpy as np
import raster
import slider
import draw_texture
import qt_helpers
raster_width = 1024
raster_height = 64
raster_n_neurons = 64
spikes_per_frame = 5
c... | self.setCentralWidget(self.widget)
self.show()
# show the window
win = qt_helpers.create_window(TestWindow) | # put the window at the screen position (100, 100)
self.setGeometry(100, 100, self.widget.width, self.widget.height) | random_line_split |
main_raster.py | import time
from PyQt4 import QtGui, QtCore, QtOpenGL
from PyQt4.QtOpenGL import QGLWidget
import OpenGL.GL as gl
import OpenGL.arrays.vbo as glvbo
import numpy as np
import raster
import slider
import draw_texture
import qt_helpers
raster_width = 1024
raster_height = 64
raster_n_neurons = 64
spikes_per_frame = 5
c... |
self.last_time = now
if self.dt is not None:
self.slider.swap_frame_buffer(int(self.dt/0.001))
self.slider.paint_slid()
#data = self.data
data = np.random.randint(raster_n_neurons,
size=spikes_per_frame).astype('int32')
... | dt = now - self.last_time
if self.dt is None:
self.dt = dt
else:
#self.dt = dt
self.dt = (0.9) * self.dt + (0.1) * dt | conditional_block |
main_raster.py | import time
from PyQt4 import QtGui, QtCore, QtOpenGL
from PyQt4.QtOpenGL import QGLWidget
import OpenGL.GL as gl
import OpenGL.arrays.vbo as glvbo
import numpy as np
import raster
import slider
import draw_texture
import qt_helpers
raster_width = 1024
raster_height = 64
raster_n_neurons = 64
spikes_per_frame = 5
c... |
# show the window
win = qt_helpers.create_window(TestWindow)
| super(TestWindow, self).__init__()
# initialize the GL widget
self.widget = GLPlotWidget()
# put the window at the screen position (100, 100)
self.setGeometry(100, 100, self.widget.width, self.widget.height)
self.setCentralWidget(self.widget)
self.... | identifier_body |
GetXPATH_init.js | /* Save this file content as a bookmark in Internet Explorer
This script helps to get the XPath of an element in IE-similar to Firefox's firebug/firepath
Select any element in a webpage and click on the two bookmarks GetXPATH_init.js,GetXPATH_final.js in the mentioned order to get the XPath of that element.
*/
javascr... | nodeExpr+='['+rank+']';
}
else
{
var ns=node.nextSibling;
while(ns)
{
if(ns.tagName==node.tagName)
{
nodeExpr+='[1]';
break;
}
ns=ns.nextSibling;
}
}
return nodeExpr;
}
| {
var nodeExpr=node.tagName;
if(!nodeExpr)return null;
if(node.id!='')
{
nodeExpr+="[@id='"+node.id+"']";
return "/"+nodeExpr;
}
var rank=1;
var ps=node.previousSibling;
while(ps)
{
if(ps.tagName==node.tagName)
{
rank++;
}
ps=ps.previousSibling;
}
if(rank>1)
{ | identifier_body |
GetXPATH_init.js | /* Save this file content as a bookmark in Internet Explorer
This script helps to get the XPath of an element in IE-similar to Firefox's firebug/firepath
Select any element in a webpage and click on the two bookmarks GetXPATH_init.js,GetXPATH_final.js in the mentioned order to get the XPath of that element.
*/
javascr... | (node)
{
var nodeExpr=node.tagName;
if(!nodeExpr)return null;
if(node.id!='')
{
nodeExpr+="[@id='"+node.id+"']";
return "/"+nodeExpr;
}
var rank=1;
var ps=node.previousSibling;
while(ps)
{
if(ps.tagName==node.tagName)
{
rank++;
}
ps=ps.previousSibling;
}
if(rank>1)
{
nodeExpr+='['+rank+']';
}
else
{
var ns=node.nextSib... | getNode | identifier_name |
GetXPATH_init.js | /* Save this file content as a bookmark in Internet Explorer
This script helps to get the XPath of an element in IE-similar to Firefox's firebug/firepath
Select any element in a webpage and click on the two bookmarks GetXPATH_init.js,GetXPATH_final.js in the mentioned order to get the XPath of that element.
*/
javascr... | if(ps.tagName==node.tagName)
{
rank++;
}
ps=ps.previousSibling;
}
if(rank>1)
{
nodeExpr+='['+rank+']';
}
else
{
var ns=node.nextSibling;
while(ns)
{
if(ns.tagName==node.tagName)
{
nodeExpr+='[1]';
break;
}
ns=ns.nextSibling;
}
}
return nodeExpr;
} | var ps=node.previousSibling;
while(ps)
{ | random_line_split |
GetXPATH_init.js | /* Save this file content as a bookmark in Internet Explorer
This script helps to get the XPath of an element in IE-similar to Firefox's firebug/firepath
Select any element in a webpage and click on the two bookmarks GetXPATH_init.js,GetXPATH_final.js in the mentioned order to get the XPath of that element.
*/
javascr... |
ns=ns.nextSibling;
}
}
return nodeExpr;
}
| {
nodeExpr+='[1]';
break;
} | conditional_block |
views.py | :
return
# First, check that we have all the settings and data we need. Do not bail
# after each error, so that we can report on all the validation problems
# at once.
errors = []
try:
# The reuest has any potentially private data fields.
requested_place = json.loads(reques... | random_line_split | ||
views.py | (self, default=u'null', **kwargs):
uri = make_resource_uri('current', root=self.auth_root)
res = requests.get(uri, headers={'Accept': 'application/json'}, **kwargs)
return (res.text if res.status_code == 200 else default)
@ensure_csrf_cookie
def index(request, place_id=None):
# Load app c... | current_user | identifier_name | |
views.py | = make_resource_uri('current', root=self.auth_root)
res = requests.get(uri, headers={'Accept': 'application/json'}, **kwargs)
return (res.text if res.status_code == 200 else default)
@ensure_csrf_cookie
def index(request, place_id=None):
# Load app config settings
config = get_shareabouts_co... |
# Set optional values
bcc_list = getattr(settings, 'EMAIL_NOTIFICATIONS_BCC', [])
# If we didn't find any errors, then render the email and send.
context_data = RequestContext(request, {
'place': place,
'email': recipient_email,
'config': config,
'site_root': request.b... | return | conditional_block |
views.py | make_resource_uri('current', root=self.auth_root)
res = requests.get(uri, headers={'Accept': 'application/json'}, **kwargs)
return (res.text if res.status_code == 200 else default)
@ensure_csrf_cookie
def index(request, place_id=None):
# Load app config settings
config = get_shareabouts_conf... |
def readonly_file_api(request, path, datafilename='data.json'):
if path.endswith('actions'):
return readonly_response(request, {
'results': [],
'metadata': {
'length': 0,
'next': None,
'previous': None
},
})
... | response_string = json.dumps(data)
content_type = 'application/json'
if 'callback' in request.GET:
response_string = '%s(%s);' % (request.GET['callback'], response_string)
content_type = 'application/javascript'
return HttpResponse(response_string, content_type=content_type) | identifier_body |
graph_creation.py | # Creates graph of restaurant reviews for yelp or trip advisor.
# writes graph to gml file for use in gephi
#
# Rob Churchill
#
# NOTE: I learned to do this in my data science class last semester. If you are looking for plagiarism things, you will almost certainly find similar clustering code.
# I did not copy it, I l... |
else:
G.add_edge(y[13], y[4], weight=float(y[1]))
print nx.number_of_nodes(G)
print nx.number_of_edges(G)
# write graph to gml file.
nx.write_gml(G, 'ta_graph.gml') | G.add_edge(y[13], y[4], weight=float(y[2])) | conditional_block |
graph_creation.py | # Creates graph of restaurant reviews for yelp or trip advisor.
# writes graph to gml file for use in gephi
#
# Rob Churchill
#
# NOTE: I learned to do this in my data science class last semester. If you are looking for plagiarism things, you will almost certainly find similar clustering code.
# I did not copy it, I l... | folder = 'data/'
file_names = ['yelp_data.csv', 'trip_advisor_data.csv']
# EDIT this line to change which website you make the graph for. True=yelp, False=TripAdvisor
yelp = False
yelp_dataset = list()
file_name = file_names[1]
if yelp == True:
file_name = file_names[0]
# reads in appropriate file given yelp boole... | import numpy as np
import scipy as sp
import csv
| random_line_split |
generic.provides.py | #{#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of REDHAWK core.
#
# REDHAWK core is free software: you can redistribute it and/or modify it under | # later version.
#
# REDHAWK core is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesse... | # the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any | random_line_split |
generic.provides.py | #{#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of REDHAWK core.
#
# REDHAWK core is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Fre... |
#{% for operation in portgen.operations() %}
#{% set arglist = ['self'] + operation.args %}
def ${operation.name}(${arglist|join(', ')}):
# TODO:
pass
#{% endfor %}
| self.parent = parent
self.name = name
self.sri = None
self.queue = Queue.Queue()
self.port_lock = threading.Lock() | identifier_body |
generic.provides.py | #{#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of REDHAWK core.
#
# REDHAWK core is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Fre... | (self, parent, name):
self.parent = parent
self.name = name
self.sri = None
self.queue = Queue.Queue()
self.port_lock = threading.Lock()
#{% for operation in portgen.operations() %}
#{% set arglist = ['self'] + operation.args %}
def ${operation.name}(${arglist|join(', ')}):
... | __init__ | identifier_name |
uploadcsv.js | /**
$ node uploadcsv __gradeid _filename
*/
var mysql = require('mysql'),
fs = require('fs'),
colors = require('colors');
var parse = require('csv-parse');
var connection = require('../../lib/mysql').connection; |
var upload = function(gid, uid, score, callback) {
var cmd = 'DELETE FROM exam_scores WHERE eid = ? AND uid = ?';
connection.query(cmd, [gid, uid], function(err, result) {
if (err)
console.log(err);
if (score >= 0) {
var cmd = 'INSERT INTO exam_scores (uid, eid, score) VALUES (?, ?, ?)';
connection.quer... | random_line_split | |
uploadcsv.js | /**
$ node uploadcsv __gradeid _filename
*/
var mysql = require('mysql'),
fs = require('fs'),
colors = require('colors');
var parse = require('csv-parse');
var connection = require('../../lib/mysql').connection;
var upload = function(gid, uid, score, callback) {
var cmd = 'DELETE FROM exam_scores WHERE eid = ? AN... |
var uid = table[i][0], score = table[i][2];
upload(gid, uid, score, function() {
uploadtable(i+1, gid, table);
});
};
var args = process.argv.slice(2);
var gid = parseInt(args[0]), filename = args[1];
parse(fs.readFileSync(filename).toString(), {comment: '#'}, function(err, output) {
var table = output.slice(1... | {
console.log('[' + 'INFO'.green + ']' + ' All informations have been updated.');
process.exit(0);
return ;
} | conditional_block |
index.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.... | <E>(&mut self, value: String) -> Result<Self::Value, E> where E: Error {
self.visit_str(value.as_ref())
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json;
#[test]
fn block_number_deserialization() {
let s = r#"["0xa", "10"]"#;
let deserialized: Vec<Index> = serde_json::from_str(s).unwrap();
asser... | visit_string | identifier_name |
index.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.... |
}
| {
let s = r#"["0xa", "10"]"#;
let deserialized: Vec<Index> = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, vec![Index(10), Index(10)]);
} | identifier_body |
index.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of t... | random_line_split | |
assetmanager.py | # Copyright (c) 2015, Anthony Schmieder
# Use of this source code is governed by the 2-clause BSD license that
# can be found in the LICENSE.txt file.
"""Loads and manages art assets"""
import pyglet
import os
_ASSET_PATHS = ["res"]
_ASSET_FILE_NAMES = [
"black_key_down.png",
"black_key_up.png",
"white_ke... |
pyglet.resource.reindex()
@staticmethod
def get(filename):
if Assets._loadedAssets is None:
raise RuntimeError("You must initialize the asset manager before "
"retrieving assets")
return Assets._loadedAssets[filename]
| pyglet.resource.path.append(os.path.join(os.getcwd(), p)) | conditional_block |
assetmanager.py | # Copyright (c) 2015, Anthony Schmieder
# Use of this source code is governed by the 2-clause BSD license that
# can be found in the LICENSE.txt file.
"""Loads and manages art assets"""
import pyglet
import os
_ASSET_PATHS = ["res"]
_ASSET_FILE_NAMES = [
"black_key_down.png",
"black_key_up.png",
"white_ke... | Assets._loadedAssets = dict()
Assets._updateResourcePath()
for f in _ASSET_FILE_NAMES:
Assets.loadAsset(f)
@staticmethod
def loadAsset(filename):
Assets._loadedAssets[filename] = pyglet.resource.image(filename)
@staticmethod
def _updateResourcePath():
... |
@staticmethod
def loadAssets(): | random_line_split |
assetmanager.py | # Copyright (c) 2015, Anthony Schmieder
# Use of this source code is governed by the 2-clause BSD license that
# can be found in the LICENSE.txt file.
"""Loads and manages art assets"""
import pyglet
import os
_ASSET_PATHS = ["res"]
_ASSET_FILE_NAMES = [
"black_key_down.png",
"black_key_up.png",
"white_ke... | ():
for p in _ASSET_PATHS:
pyglet.resource.path.append(os.path.join(os.getcwd(), p))
pyglet.resource.reindex()
@staticmethod
def get(filename):
if Assets._loadedAssets is None:
raise RuntimeError("You must initialize the asset manager before "
... | _updateResourcePath | identifier_name |
assetmanager.py | # Copyright (c) 2015, Anthony Schmieder
# Use of this source code is governed by the 2-clause BSD license that
# can be found in the LICENSE.txt file.
"""Loads and manages art assets"""
import pyglet
import os
_ASSET_PATHS = ["res"]
_ASSET_FILE_NAMES = [
"black_key_down.png",
"black_key_up.png",
"white_ke... |
@staticmethod
def get(filename):
if Assets._loadedAssets is None:
raise RuntimeError("You must initialize the asset manager before "
"retrieving assets")
return Assets._loadedAssets[filename]
| for p in _ASSET_PATHS:
pyglet.resource.path.append(os.path.join(os.getcwd(), p))
pyglet.resource.reindex() | identifier_body |
swig_tags.js | "use strict";
/**
* Defines swig tags for templates
* @param {Object} swig Swig engine to add tags to
* @param {Object} context Context that all tags have access to
*/
module.exports.init = function(swig, context) {
/**
* Array of tagObjects. A tag object contains the keys
* name, parse, c... | (tagObject) {
if (tagObject.name && tagObject.extension) {
swig.setExtension(tagObject.name, tagObject.extension);
}
swig.setTag(
tagObject.name,
tagObject.parse,
tagObject.compile,
tagObject.ends,
tagObject.blockLevel
);
}
};
};
| setTag | identifier_name |
swig_tags.js | "use strict";
/**
* Defines swig tags for templates
* @param {Object} swig Swig engine to add tags to
* @param {Object} context Context that all tags have access to
*/
module.exports.init = function(swig, context) {
/**
* Array of tagObjects. A tag object contains the keys
* name, parse, c... | else if (typeof setUserTags === "string") {
resolveTag(setUserTags);
} else {
throw new Error(
"Expects input to be an array of strings that represent a file path, object or file path string."
);
}
return this;
function resolveTag(tagInput) {
if (typeof tagInput === "s... | {
resolveTag(setUserTags);
} | conditional_block |
swig_tags.js | "use strict";
/**
* Defines swig tags for templates
* @param {Object} swig Swig engine to add tags to
* @param {Object} context Context that all tags have access to
*/
module.exports.init = function(swig, context) {
/**
* Array of tagObjects. A tag object contains the keys
* name, parse, c... |
};
};
| {
if (tagObject.name && tagObject.extension) {
swig.setExtension(tagObject.name, tagObject.extension);
}
swig.setTag(
tagObject.name,
tagObject.parse,
tagObject.compile,
tagObject.ends,
tagObject.blockLevel
);
} | identifier_body |
swig_tags.js | "use strict";
/**
* Defines swig tags for templates
* @param {Object} swig Swig engine to add tags to
* @param {Object} context Context that all tags have access to
*/
module.exports.init = function(swig, context) {
/**
* Array of tagObjects. A tag object contains the keys
* name, parse, c... | );
}
};
}; | tagObject.blockLevel | random_line_split |
uri.py | # vi: ts=8 sts=4 sw=4 et
#
# uri.py: various URI related utilties
#
# This file is part of Draco2. Draco2 is free software and is made available
# under the MIT license. Consult the file "LICENSE" that is distributed
# together with this file for the exact licensing terms.
#
# Draco2 is copyright (c) 1999-2007 by the D... |
def create_uri(scheme=None, host=None, path=None, query=None):
"""Create an URI from its components."""
uri = ''
if scheme:
uri += '%s:' % scheme
if host:
uri += '//%s' % host
if path:
uri += '/%s' % path
if query:
uri += '?%s' % query
return uri
def parse_p... | return tuple(result) | random_line_split |
uri.py | # vi: ts=8 sts=4 sw=4 et
#
# uri.py: various URI related utilties
#
# This file is part of Draco2. Draco2 is free software and is made available
# under the MIT license. Consult the file "LICENSE" that is distributed
# together with this file for the exact licensing terms.
#
# Draco2 is copyright (c) 1999-2007 by the D... |
s = quote_hex(s, ' ')
s = s.replace(' ', '+')
return s
def unquote_form(s):
"""Decode a form encoded string."""
s = s.replace('+', ' ')
s = unquote_hex(s)
s = s.decode('utf-8')
return s
# URI parsing
re_uri = re.compile('(?:([^:/?]*):)?(?://([^?/]*))?(?:/?([^?]*))(?:\?(.*))?')
def ... | s = s.encode('utf-8') | conditional_block |
uri.py | # vi: ts=8 sts=4 sw=4 et
#
# uri.py: various URI related utilties
#
# This file is part of Draco2. Draco2 is free software and is made available
# under the MIT license. Consult the file "LICENSE" that is distributed
# together with this file for the exact licensing terms.
#
# Draco2 is copyright (c) 1999-2007 by the D... | (Exception):
pass
def resolve_path_uri(path, docroot):
"""Resolves the path part of an URI.
The URI is resolved to the 3-tuple: directory, filename, pathinfo.
The filename component is either empty or a single path component,
and may or may not exist as a physical file. The pathinfo component
... | ResolutionError | identifier_name |
uri.py | # vi: ts=8 sts=4 sw=4 et
#
# uri.py: various URI related utilties
#
# This file is part of Draco2. Draco2 is free software and is made available
# under the MIT license. Consult the file "LICENSE" that is distributed
# together with this file for the exact licensing terms.
#
# Draco2 is copyright (c) 1999-2007 by the D... |
def resolve_path_uri(path, docroot):
"""Resolves the path part of an URI.
The URI is resolved to the 3-tuple: directory, filename, pathinfo.
The filename component is either empty or a single path component,
and may or may not exist as a physical file. The pathinfo component
consists of zero or m... | pass | identifier_body |
permission.service.ts | import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../environments/environment';
import { Observable, Subject } from 'rxjs';
import { Permission } from '../data-models/permission';
import { BehaviorSubject } from 'rxjs';
@Injectable({
p... | selectedPermission(userId: number) {
this.permissionSource.next(userId)
}
clearselectedPermission() {
this.subject.next();
}
} | const url = `${this.configUrl}/role/permission/${id}`;
return this.http.get<Permission>(url);
}
| random_line_split |
permission.service.ts | import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../environments/environment';
import { Observable, Subject } from 'rxjs';
import { Permission } from '../data-models/permission';
import { BehaviorSubject } from 'rxjs';
@Injectable({
p... | () {
this.subject.next();
}
} | clearselectedPermission | identifier_name |
permission.service.ts | import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../environments/environment';
import { Observable, Subject } from 'rxjs';
import { Permission } from '../data-models/permission';
import { BehaviorSubject } from 'rxjs';
@Injectable({
p... |
getPermissionRoleById(id: number): Observable<Permission>{
const url = `${this.configUrl}/role/permission/${id}`;
return this.http.get<Permission>(url);
}
selectedPermission(userId: number) {
this.permissionSource.next(userId)
}
clearselectedPermission() {
this.s... | {
const url = `${this.configUrl}/role/permission/${id}`;
return this.http.put<Permission>(url, role);
} | identifier_body |
searchfilter.js | //Libraries
const React = require("react");
const _ = require("lodash");
const DataActions = require("../actions/data_actions");
const DataStore = require("../stores/data_store");
const FilterStore = require("../stores/filter_store");
const ColumnsStore = require("../stores/columns_store");
//Mixins
const... | (){
this.setState({
keys:ColumnsStore.getSearchable()
});
}
_onChange(e){
if(this.quickSearch){
if(this.loop){
window.clearTimeout(this.loop);
}
this.loop = window.setTimeout((val)=>{
if(val.length > 2 || val === ""){
DataActions.searching(val);
... | _onAdd | identifier_name |
searchfilter.js | //Libraries
const React = require("react");
const _ = require("lodash");
const DataActions = require("../actions/data_actions");
const DataStore = require("../stores/data_store");
const FilterStore = require("../stores/filter_store");
const ColumnsStore = require("../stores/columns_store");
//Mixins
const... | this.dropdown = ["input-group-btn", {"open":false}];
this.state = {
dropdown:this.getClasses(this.dropdown),
expanded:"false",
selectedkey:"all",
searchVal:""
};
}
componentDidMount() {
this.quickSearch = (_.isBoolean(this.props.quickSearch)) ? this.props.quickSearch : ... | class SearchFilters extends React.Component{
constructor(props) {
super(props); | random_line_split |
searchfilter.js | //Libraries
const React = require("react");
const _ = require("lodash");
const DataActions = require("../actions/data_actions");
const DataStore = require("../stores/data_store");
const FilterStore = require("../stores/filter_store");
const ColumnsStore = require("../stores/columns_store");
//Mixins
const... |
// _.defer((val)=>{
// DataActions.searching(val);
// }, e.target.value);
}
// _openDropdown(){
// this.dropdown = this.toggleCss(this.dropdown);
// let expanded = (this.state.expended === "true") ? "false" : "true";
// this.setState({
// dropdown:this.getClasses(this.dropdown),
... | {
if(this.loop){
window.clearTimeout(this.loop);
}
this.loop = window.setTimeout((val)=>{
if(val.length > 2 || val === ""){
DataActions.searching(val);
}
}, 200, e.target.value);
this.setState({searchVal:e.target.value});
} | conditional_block |
test_result.rs | mod checked {
#[derive(Debug)]
pub enum MathError {
DivisionByZero,
NonPositiveLogarithm,
NegativeSquareRoot,
}
pub type MathResult = Result<f64, MathError>;
pub fn div(x: f64, y: f64) -> MathResult {
if y == 0.0 {
Err(MathError::DivisionByZero)
} els... | Ok(sqrt) => sqrt,
},
},
}
}
fn main() {
println!("{}", op(1.0, 10.0));
} | Ok(ln) => match checked::sqrt(ln) {
Err(why) => panic!("{:?}", why), | random_line_split |
test_result.rs | mod checked {
#[derive(Debug)]
pub enum MathError {
DivisionByZero,
NonPositiveLogarithm,
NegativeSquareRoot,
}
pub type MathResult = Result<f64, MathError>;
pub fn div(x: f64, y: f64) -> MathResult |
pub fn sqrt(x: f64) -> MathResult {
if x < 0.0 {
Err(MathError::NegativeSquareRoot)
} else {
Ok(x.sqrt())
}
}
pub fn ln(x: f64) -> MathResult {
if x <= 0.0 {
Err(MathError::NonPositiveLogarithm)
} else {
Ok(x.ln())
... | {
if y == 0.0 {
Err(MathError::DivisionByZero)
} else {
Ok(x / y)
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.