file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
kbo.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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 ver...
(precedence: &Precedence, weight: &Weight, only_unary_func: &Option<i64>, s: &Term, t: &Term) -> bool { assert_eq!(s.get_id(), t.get_id()); assert_eq!(s.get_arity(), t.get_arity()); for i in 0..s.get_arity()...
lexical_ordering
identifier_name
CollectionArtworksFilter.jest.tsx
import { MockBoot } from "v2/DevTools" import { CollectionArtworksFilterRefetchContainer as CollectionArtworksFilter } from "../CollectionArtworksFilter" import { graphql } from "react-relay" import { CollectionArtworksFilter_Query } from "v2/__generated__/CollectionArtworksFilter_Query.graphql" import { useTracking } ...
expect(filterWrappers.at(filterIndex).prop("label")).toEqual(label) expect(filterWrappers.at(filterIndex).prop("expanded")).toEqual(expanded) }) }) })
random_line_split
Sortable.js
/** * A mixin which allows a data component to be sorted. This is used by e.g. {@link Ext.data.Store} and {@link Ext.data.TreeStore}. * * **NOTE**: This mixin is mainly for internal use and most users should not need to use it directly. It * is more likely you will want to use one of the component classes that impo...
return sortersCollection; }, /** * Updates the sorters collection and triggers sorting of this Sortable. Example usage: * * //sort by a single field * myStore.sort('myField', 'DESC'); * * //sorting by multiple fields * myStore.sort([{ * p...
{ sortersCollection.addAll(me.decodeSorters(sorters)); }
conditional_block
Sortable.js
/** * A mixin which allows a data component to be sorted. This is used by e.g. {@link Ext.data.Store} and {@link Ext.data.TreeStore}. * * **NOTE**: This mixin is mainly for internal use and most users should not need to use it directly. It * is more likely you will want to use one of the component classes that impo...
isSortable: true, $configPrefixed: false, $configStrict: false, config: { /** * @cfg {Ext.util.Sorter[]/Object[]} sorters * The initial set of {@link Ext.util.Sorter Sorters}. * * sorters: [{ * property: 'age', * directi...
random_line_split
normalize.ts
import { Abi as SchemaAbi } from "@truffle/contract-schema/spec"; import { Abi, Entry, StateMutability } from "./types"; export const normalize = (looseAbi: SchemaAbi | Abi): Abi => (looseAbi as SchemaAbi).map(normalizeEntry); type Item<A> = A extends (infer I)[] ? I : never; export const normalizeEntry = (looseEn...
delete (entry as any).payable; delete (entry as any).constant; return entry; }; interface LooseStateMutabilityFields { stateMutability?: StateMutability; payable?: boolean; constant?: boolean; } const normalizeStateMutability = ({ stateMutability, payable, constant }: LooseStateMutabilityFields):...
{ entry.outputs = entry.outputs || []; }
conditional_block
normalize.ts
import { Abi as SchemaAbi } from "@truffle/contract-schema/spec"; import { Abi, Entry, StateMutability } from "./types"; export const normalize = (looseAbi: SchemaAbi | Abi): Abi => (looseAbi as SchemaAbi).map(normalizeEntry); type Item<A> = A extends (infer I)[] ? I : never; export const normalizeEntry = (looseEn...
payable?: boolean; constant?: boolean; } const normalizeStateMutability = ({ stateMutability, payable, constant }: LooseStateMutabilityFields): { stateMutability: StateMutability } => { if (stateMutability) { return { stateMutability }; } return { stateMutability: payable ? "payable" : constan...
random_line_split
lib.rs
/// Generate a secret key for signing and verifying JSON Web Tokens and HMACs. /// /// Returns a secret comprised of 64 URL and command line compatible characters /// (e.g. so that it can easily be entered on the CLI e.g. for a `--key` option ). /// /// Uses 64 bytes because this is the maximum size possible for JWT si...
use rand::Rng; const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ 0123456789"; let mut rng = rand::thread_rng(); (0..64) .map(|_| { let idx = rng.gen_range(0..CHARSET.len()); CHARSET[idx...
/// See <https://auth0.com/blog/brute-forcing-hs256-is-possible-the-importance-of-using-strong-keys-to-sign-jwts/>. pub fn generate() -> String {
random_line_split
lib.rs
/// Generate a secret key for signing and verifying JSON Web Tokens and HMACs. /// /// Returns a secret comprised of 64 URL and command line compatible characters /// (e.g. so that it can easily be entered on the CLI e.g. for a `--key` option ). /// /// Uses 64 bytes because this is the maximum size possible for JWT si...
() -> String { use rand::Rng; const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ 0123456789"; let mut rng = rand::thread_rng(); (0..64) .map(|_| { let idx = rng.gen_range(0..CHARSET.len()); ...
generate
identifier_name
lib.rs
/// Generate a secret key for signing and verifying JSON Web Tokens and HMACs. /// /// Returns a secret comprised of 64 URL and command line compatible characters /// (e.g. so that it can easily be entered on the CLI e.g. for a `--key` option ). /// /// Uses 64 bytes because this is the maximum size possible for JWT si...
{ use rand::Rng; const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ 0123456789"; let mut rng = rand::thread_rng(); (0..64) .map(|_| { let idx = rng.gen_range(0..CHARSET.len()); CHARSET[i...
identifier_body
constants.py
### EXESOFT PYIGNITION ### # Copyright David Barker 2010 # # Global constants module
# Which version is this? PYIGNITION_VERSION = 1.0 # Drawtype constants DRAWTYPE_POINT = 100 DRAWTYPE_CIRCLE = 101 DRAWTYPE_LINE = 102 DRAWTYPE_SCALELINE = 103 DRAWTYPE_BUBBLE = 104 DRAWTYPE_IMAGE = 105 # Interpolation type constants INTERPOLATIONTYPE_LINEAR = 200 INTERPOLATIONTYPE_COSINE = 201 # G...
random_line_split
BrowseFiles.ts
/* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file ...
}); Icons.getIcon('spinner-circle', Icons.sizes.small, null, null, Icons.markupIdentifiers.inline).then((icon: string): void => { targetEl.classList.add('disabled'); targetEl.innerHTML = icon; }); NProgress.configure({parent: '.element-browser-main-content', showSpinner: false}); NProg...
{ selectedItems.unshift({uid: item.dataset.fileUid, fileName: item.dataset.fileName}); }
conditional_block
BrowseFiles.ts
/* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file ...
Number(targetEl.dataset.fileUid), parseInt(targetEl.dataset.close || '0', 10) === 1, ); }).delegateTo(document, '[data-close]'); // Handle import selection event, dispatched from MultiRecordSelection new RegularEvent('multiRecordSelection:action:import', this.importSelection).bindTo(d...
new RegularEvent('click', (evt: MouseEvent, targetEl: HTMLElement): void => { evt.preventDefault(); BrowseFiles.insertElement( targetEl.dataset.fileName,
random_line_split
BrowseFiles.ts
/* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file ...
{ public static insertElement(fileName: string, fileUid: number, close?: boolean): boolean { return ElementBrowser.insertElement( 'sys_file', String(fileUid), fileName, String(fileUid), close, ); } private static handleNext(items: LinkElement[]): void { if (items.length...
BrowseFiles
identifier_name
BrowseFiles.ts
/* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file ...
private static handleNext(items: LinkElement[]): void { if (items.length > 0) { const item = items.pop(); BrowseFiles.insertElement(item.fileName, Number(item.uid)); } } constructor() { new RegularEvent('click', (evt: MouseEvent, targetEl: HTMLElement): void => { evt.preventDefaul...
{ return ElementBrowser.insertElement( 'sys_file', String(fileUid), fileName, String(fileUid), close, ); }
identifier_body
index.js
var parse = require('../parse/index.js') /** * @category Quarter Helpers * @summary Return the last day of a year quarter for the given date. * * @description * Return the last day of a year quarter for the given date. * The result will be in the local timezone. * * @param {Date|String|Number} date - the origi...
date.setMonth(month, 0) date.setHours(0, 0, 0, 0) return date } module.exports = lastDayOfQuarter
*/ function lastDayOfQuarter (dirtyDate) { var date = parse(dirtyDate) var currentMonth = date.getMonth() var month = currentMonth - currentMonth % 3 + 3
random_line_split
index.js
var parse = require('../parse/index.js') /** * @category Quarter Helpers * @summary Return the last day of a year quarter for the given date. * * @description * Return the last day of a year quarter for the given date. * The result will be in the local timezone. * * @param {Date|String|Number} date - the origi...
module.exports = lastDayOfQuarter
{ var date = parse(dirtyDate) var currentMonth = date.getMonth() var month = currentMonth - currentMonth % 3 + 3 date.setMonth(month, 0) date.setHours(0, 0, 0, 0) return date }
identifier_body
index.js
var parse = require('../parse/index.js') /** * @category Quarter Helpers * @summary Return the last day of a year quarter for the given date. * * @description * Return the last day of a year quarter for the given date. * The result will be in the local timezone. * * @param {Date|String|Number} date - the origi...
(dirtyDate) { var date = parse(dirtyDate) var currentMonth = date.getMonth() var month = currentMonth - currentMonth % 3 + 3 date.setMonth(month, 0) date.setHours(0, 0, 0, 0) return date } module.exports = lastDayOfQuarter
lastDayOfQuarter
identifier_name
ee-TG.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js function
(n: number): number { if (n === 1) return 1; return 5; } export default [ 'ee-TG', [ ['ŋ', 'ɣ'], ['ŋdi', 'ɣetrɔ'], ], , [ ['k', 'd', 'b', 'k', 'y', 'f', 'm'], ['kɔs', 'dzo', 'bla', 'kuɖ', 'yaw', 'fiɖ', 'mem'], ['kɔsiɖa', 'dzoɖa', 'blaɖa', 'kuɖa', 'yawoɖa', 'fiɖa', 'memleɖa'], ['kɔs', ...
plural
identifier_name
ee-TG.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js function plural(n: number...
export default [ 'ee-TG', [ ['ŋ', 'ɣ'], ['ŋdi', 'ɣetrɔ'], ], , [ ['k', 'd', 'b', 'k', 'y', 'f', 'm'], ['kɔs', 'dzo', 'bla', 'kuɖ', 'yaw', 'fiɖ', 'mem'], ['kɔsiɖa', 'dzoɖa', 'blaɖa', 'kuɖa', 'yawoɖa', 'fiɖa', 'memleɖa'], ['kɔs', 'dzo', 'bla', 'kuɖ', 'yaw', 'fiɖ', 'mem'] ], , [ [...
{ if (n === 1) return 1; return 5; }
identifier_body
ee-TG.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js function plural(n: number...
], , [ ['d', 'd', 't', 'a', 'd', 'm', 's', 'd', 'a', 'k', 'a', 'd'], ['dzv', 'dzd', 'ted', 'afɔ', 'dam', 'mas', 'sia', 'dea', 'any', 'kel', 'ade', 'dzm'], [ 'dzove', 'dzodze', 'tedoxe', 'afɔfĩe', 'dama', 'masa', 'siamlɔm', 'deasiamime', 'anyɔnyɔ', 'kele', 'adeɛmekpɔxe', 'dzome' ] ], ...
['kɔsiɖa', 'dzoɖa', 'blaɖa', 'kuɖa', 'yawoɖa', 'fiɖa', 'memleɖa'], ['kɔs', 'dzo', 'bla', 'kuɖ', 'yaw', 'fiɖ', 'mem']
random_line_split
bokeh_events.ts
import {logger} from "./logging" import {clone} from "./util/object" const event_classes: {[key: string]: typeof BokehEvent} = {} export function register_event_class(event_name: string) { return function(event_cls: typeof BokehEvent) { event_cls.prototype.event_name = event_name event_classes[event_name] =...
} set_model_id(id: string): this { this._options.model_id = id this.model_id = id return this } is_applicable_to(obj: any): boolean { return this.applicable_models.some((model) => obj instanceof model) } static event_class(e: any): any { // Given an event with a type attribute matchi...
{ this.model_id = options.model_id }
conditional_block
bokeh_events.ts
import {logger} from "./logging" import {clone} from "./util/object" const event_classes: {[key: string]: typeof BokehEvent} = {} export function register_event_class(event_name: string) { return function(event_cls: typeof BokehEvent) { event_cls.prototype.event_name = event_name event_classes[event_name] =...
} _customize_event(plot: any) { const xscale = plot.plot_canvas.frame.xscales['default'] const yscale = plot.plot_canvas.frame.yscales['default'] this.x = xscale.invert(plot.plot_canvas.canvas.sx_to_vx(this.sx)) this.y = yscale.invert(plot.plot_canvas.canvas.sy_to_vy(this.sy)) this._options['x'...
this.y = null } static from_event(e: any, model_id: string | null = null) { return new this({ sx: e.bokeh['sx'], sy: e.bokeh['sy'], model_id: model_id })
random_line_split
bokeh_events.ts
import {logger} from "./logging" import {clone} from "./util/object" const event_classes: {[key: string]: typeof BokehEvent} = {} export function register_event_class(event_name: string) { return function(event_cls: typeof BokehEvent) { event_cls.prototype.event_name = event_name event_classes[event_name] =...
(e: any): any { // Given an event with a type attribute matching the event_name, // return the appropriate BokehEvent class if (e.type) { return event_classes[e.type] } else { logger.warn('BokehEvent.event_class required events with a string type attribute') } } toJSON(): object { ...
event_class
identifier_name
AndroidGenerateDynamicMacros.ts
import { Command } from '@expo/commander'; import path from 'path'; import { generateDynamicMacrosAsync } from '../dynamic-macros/generateDynamicMacros'; import { Directories } from '../expotools'; const EXPO_DIR = Directories.getExpoRepositoryRootDir(); const ANDROID_DIR = Directories.getAndroidDir(); const GENERATE...
(options): Promise<void> { const buildConstantsPath = options.buildConstantsPath || path.join(GENERATED_DIR, 'ExponentBuildConstants.java'); const configuration = options.configuration || process.env.CONFIGURATION || 'release'; await generateDynamicMacrosAsync({ buildConstantsPath, platform: 'android...
generateAction
identifier_name
AndroidGenerateDynamicMacros.ts
import { Command } from '@expo/commander'; import path from 'path'; import { generateDynamicMacrosAsync } from '../dynamic-macros/generateDynamicMacros'; import { Directories } from '../expotools'; const EXPO_DIR = Directories.getExpoRepositoryRootDir(); const ANDROID_DIR = Directories.getAndroidDir(); const GENERATE...
.command('android-generate-dynamic-macros') .option( '--buildConstantsPath [string]', 'Path to ExponentBuildConstants.java relative to `android` folder. Optional.' ) .option( '--configuration [string]', 'Build configuration. Defaults to `process.env.CONFIGURATION` or "debug".' ...
program
random_line_split
AndroidGenerateDynamicMacros.ts
import { Command } from '@expo/commander'; import path from 'path'; import { generateDynamicMacrosAsync } from '../dynamic-macros/generateDynamicMacros'; import { Directories } from '../expotools'; const EXPO_DIR = Directories.getExpoRepositoryRootDir(); const ANDROID_DIR = Directories.getAndroidDir(); const GENERATE...
export default (program: Command) => { program .command('android-generate-dynamic-macros') .option( '--buildConstantsPath [string]', 'Path to ExponentBuildConstants.java relative to `android` folder. Optional.' ) .option( '--configuration [string]', 'Build configuration. Defa...
{ const buildConstantsPath = options.buildConstantsPath || path.join(GENERATED_DIR, 'ExponentBuildConstants.java'); const configuration = options.configuration || process.env.CONFIGURATION || 'release'; await generateDynamicMacrosAsync({ buildConstantsPath, platform: 'android', expoKitPath: EXPO_...
identifier_body
util.ts
/** * Compare if two objects are same * @param o1 * @param o2 * @returns {boolean} */ export function equals(o1: any, o2: any): boolean { if (o1 === o2) { return true; } if (o1 === null || o2 === null) { return false; } if(o1 !== o1 && o2 !== o2) { return true; // NaN === NaN } let t1 = t...
} } } return true; } } return false; }
random_line_split
util.ts
/** * Compare if two objects are same * @param o1 * @param o2 * @returns {boolean} */ export function equals(o1: any, o2: any): boolean { if (o1 === o2) { return true; } if (o1 === null || o2 === null) { return false; } if(o1 !== o1 && o2 !== o2)
let t1 = typeof o1, t2 = typeof o2, length: number, key: any, keySet: any; if(t1 === t2 && t1 === 'object') { if(Array.isArray(o1)) { if (!Array.isArray(o2)) { return false; } if((length = o1.length) === o2.length) { for(key = 0; key < length; key++) { ...
{ return true; // NaN === NaN }
conditional_block
util.ts
/** * Compare if two objects are same * @param o1 * @param o2 * @returns {boolean} */ export function
(o1: any, o2: any): boolean { if (o1 === o2) { return true; } if (o1 === null || o2 === null) { return false; } if(o1 !== o1 && o2 !== o2) { return true; // NaN === NaN } let t1 = typeof o1, t2 = typeof o2, length: number, key: any, keySet: any; if(t1 === t2 && t1 === 'objec...
equals
identifier_name
util.ts
/** * Compare if two objects are same * @param o1 * @param o2 * @returns {boolean} */ export function equals(o1: any, o2: any): boolean
{ if (o1 === o2) { return true; } if (o1 === null || o2 === null) { return false; } if(o1 !== o1 && o2 !== o2) { return true; // NaN === NaN } let t1 = typeof o1, t2 = typeof o2, length: number, key: any, keySet: any; if(t1 === t2 && t1 === 'object') { if(Array.isArray(o...
identifier_body
Box2.js
import { Vector2 } from './Vector2'; /** * @author bhouston / http://clara.io */ function Box2( min, max ) { this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); } Box2.prototype = { constructor: Box2, ...
return this; }, setFromCenterAndSize: function () { var v1 = new Vector2(); return function setFromCenterAndSize( center, size ) { var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); this.min.copy( center ).sub( halfSize ); this.max.copy( center ).add( halfSize ); return this; }; }(),...
{ this.expandByPoint( points[ i ] ); }
conditional_block
Box2.js
import { Vector2 } from './Vector2'; /** * @author bhouston / http://clara.io */ function Box2( min, max ) { this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); } Box2.prototype = { constructor: Box2, ...
this.min.addScalar( - scalar ); this.max.addScalar( scalar ); return this; }, containsPoint: function ( point ) { return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true; }, containsBox: function ( box ) { return this.min.x <= box.min.x ...
}, expandByScalar: function ( scalar ) {
random_line_split
Box2.js
import { Vector2 } from './Vector2'; /** * @author bhouston / http://clara.io */ function Box2( min, max )
Box2.prototype = { constructor: Box2, set: function ( min, max ) { this.min.copy( min ); this.max.copy( max ); return this; }, setFromPoints: function ( points ) { this.makeEmpty(); for ( var i = 0, il = points.length; i < il; i ++ ) { this.expandByPoint( points[ i ] ); } return this; ...
{ this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); }
identifier_body
Box2.js
import { Vector2 } from './Vector2'; /** * @author bhouston / http://clara.io */ function
( min, max ) { this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); } Box2.prototype = { constructor: Box2, set: function ( min, max ) { this.min.copy( min ); this.max.copy( max ); return this; ...
Box2
identifier_name
rooms.js
'use strict'; const assert = require('assert'); const {User} = require('../users-utils'); describe('Rooms features', function () { describe('Rooms', function () { describe('Rooms.get', function () { it('should be a function', function () { assert.strictEqual(typeof Rooms.get, 'function'); }); }); de...
}}]; for (let option of options) { room = Rooms.createBattle('customgame', Object.assign({ p1, p2, p1team: packedTeam, p2team: packedTeam, }, option)); assert.ok(room.battle.p1 && room.battle.p2); // Automatically joined } }); it('should copy auth from tournament', function ()...
{}
identifier_body
rooms.js
'use strict'; const assert = require('assert'); const {User} = require('../users-utils'); describe('Rooms features', function () { describe('Rooms', function () { describe('Rooms.get', function () { it('should be a function', function () { assert.strictEqual(typeof Rooms.get, 'function'); }); }); de...
() {}}}]; for (let option of options) { room = Rooms.createBattle('customgame', Object.assign({ p1, p2, p1team: packedTeam, p2team: packedTeam, }, option)); assert.ok(room.battle.p1 && room.battle.p2); // Automatically joined } }); it('should copy auth from tournament', functi...
onBattleWin
identifier_name
rooms.js
'use strict'; const assert = require('assert'); const {User} = require('../users-utils'); describe('Rooms features', function () { describe('Rooms', function () { describe('Rooms.get', function () { it('should be a function', function () { assert.strictEqual(typeof Rooms.get, 'function'); }); }); de...
parent = Rooms.createChatRoom('parentroom2', '', {}); parent.getAuth = () => '%'; const p1 = new User(); const p2 = new User(); const roomStaff = new User(); roomStaff.forceRename("Room auth", true); const administrator = new User(); administrator.forceRename("Admin", true); administrator.gro...
random_line_split
hamming.rs
pub fn hamming_dist(a: &[u8], b:&[u8]) -> Option<u32> { use std::iter::{IteratorExt, AdditiveIterator}; if a.len()!=b.len() { return None; } let result = a.iter().zip(b.iter()).map(|(x,y)| {n_ones(x^y) as u32}).sum(); Some(result) } pub fn avg_hamming_dist(entries: &[&[u8]]) -> Option<f32> ...
+ hamming_dist(b,c).unwrap() + hamming_dist(a,c).unwrap()) as f32/3f32)); assert_eq!(avg_hamming_dist(&[a,b,c,d]), None); } }
random_line_split
hamming.rs
pub fn hamming_dist(a: &[u8], b:&[u8]) -> Option<u32> { use std::iter::{IteratorExt, AdditiveIterator}; if a.len()!=b.len()
let result = a.iter().zip(b.iter()).map(|(x,y)| {n_ones(x^y) as u32}).sum(); Some(result) } pub fn avg_hamming_dist(entries: &[&[u8]]) -> Option<f32> { let n = entries.len(); if n==0 {return None}; let mut sum = 0f32; for idx_a in 0..n { for idx_b in (idx_a+1)..n { let a = ...
{ return None; }
conditional_block
hamming.rs
pub fn hamming_dist(a: &[u8], b:&[u8]) -> Option<u32> { use std::iter::{IteratorExt, AdditiveIterator}; if a.len()!=b.len() { return None; } let result = a.iter().zip(b.iter()).map(|(x,y)| {n_ones(x^y) as u32}).sum(); Some(result) } pub fn avg_hamming_dist(entries: &[&[u8]]) -> Option<f32> ...
fn avg_hamming_dist_test() { let a = "this is a test".as_bytes(); let b = "wokka wokka!!!".as_bytes(); let c = "onyonghasayo!!".as_bytes(); let d = "this is not a test".as_bytes(); assert_eq!(avg_hamming_dist(&[a,b,c]), Some((hamming_dist(a,b).unwrap() ...
{ let a = "this is a test".as_bytes(); let b = "wokka wokka!!!".as_bytes(); let c = "this is not a test".as_bytes(); assert_eq!(Some(37), hamming_dist(a,b)); assert_eq!(None, hamming_dist(a,c)); }
identifier_body
hamming.rs
pub fn hamming_dist(a: &[u8], b:&[u8]) -> Option<u32> { use std::iter::{IteratorExt, AdditiveIterator}; if a.len()!=b.len() { return None; } let result = a.iter().zip(b.iter()).map(|(x,y)| {n_ones(x^y) as u32}).sum(); Some(result) } pub fn avg_hamming_dist(entries: &[&[u8]]) -> Option<f32> ...
() { assert_eq!(n_ones(5), 2); } #[cfg(test)] mod tests { use super::*; #[test] fn hamming_dist_test() { let a = "this is a test".as_bytes(); let b = "wokka wokka!!!".as_bytes(); let c = "this is not a test".as_bytes(); assert_eq!(Some(37), hamming_dist(a,b)); a...
n_ones_test
identifier_name
app.js
// set up events //------------------------------------- var events = require('events'); var ee = new events.EventEmitter(); // configuration file //------------------------------------- var nconf = require('nconf'); nconf.file({file: 'config.json'}); // pizza //------------------------------------- var Dominos = req...
dominos.order(); } else { console.log('dominos is not enabled, nothing will be ordered'); } } else if (data.data === 'OFF') { console.log('the button is off!'); } }); s.initialize(nconf.get('spark_access_token'));
random_line_split
app.js
// set up events //------------------------------------- var events = require('events'); var ee = new events.EventEmitter(); // configuration file //------------------------------------- var nconf = require('nconf'); nconf.file({file: 'config.json'}); // pizza //------------------------------------- var Dominos = req...
else if (data.data === 'OFF') { console.log('the button is off!'); } }); s.initialize(nconf.get('spark_access_token'));
{ console.log('the button is on!'); if (dominos.enabled) { console.log('dominos is enabled, ordering now'); dominos.order(); } else { console.log('dominos is not enabled, nothing will be ordered'); } }
conditional_block
refcounts.py
"""Support functions for loading the reference count data file.""" __version__ = '$Revision: 1.2 $' import os import string import sys # Determine the expected location of the reference count file: try: p = os.path.dirname(__file__) except NameError: p = sys.path[0] p = os.path.normpath(os.path.join(os.getcw...
def loadfile(fp): d = {} while 1: line = fp.readline() if not line: break line = string.strip(line) if line[:1] in ("", "#"): # blank lines and comments continue parts = string.split(line, ":", 4) function, type, arg, refcoun...
return loadfile(open(path))
identifier_body
refcounts.py
"""Support functions for loading the reference count data file.""" __version__ = '$Revision: 1.2 $' import os import string import sys # Determine the expected location of the reference count file: try: p = os.path.dirname(__file__) except NameError: p = sys.path[0] p = os.path.normpath(os.path.join(os.getcw...
else: print s = entry.name + ":%s:%s:%s:" if entry.result_refs is None: r = "" else: r = entry.result_refs print s % (entry.result_type, "", r) for t, n, r in entry.args: if r is None: r = "" pri...
first = 0
conditional_block
refcounts.py
"""Support functions for loading the reference count data file.""" __version__ = '$Revision: 1.2 $' import os import string import sys # Determine the expected location of the reference count file: try: p = os.path.dirname(__file__) except NameError: p = sys.path[0] p = os.path.normpath(os.path.join(os.getcw...
if refcount == "null": refcount = None elif refcount: refcount = int(refcount) else: refcount = None # # Get the entry, creating it if needed: # try: entry = d[function] except KeyError: entry = d...
random_line_split
refcounts.py
"""Support functions for loading the reference count data file.""" __version__ = '$Revision: 1.2 $' import os import string import sys # Determine the expected location of the reference count file: try: p = os.path.dirname(__file__) except NameError: p = sys.path[0] p = os.path.normpath(os.path.join(os.getcw...
(): d = load() dump(d) if __name__ == "__main__": main()
main
identifier_name
mod.rs
#![cfg(target_os = "emscripten")] use std::ffi::CString; use libc; use {Event, BuilderAttribs, CreationError, MouseCursor}; use Api; use PixelFormat; use GlContext; use std::collections::VecDeque; mod ffi; pub struct Window { context: ffi::EMSCRIPTEN_WEBGL_CONTEXT_HANDLE, } pub struct PollEventsIterator<'a> { ...
(code: ffi::EMSCRIPTEN_RESULT) -> &'static str { match code { ffi::EMSCRIPTEN_RESULT_SUCCESS | ffi::EMSCRIPTEN_RESULT_DEFERRED => "Internal error in the library (success detected as failure)", ffi::EMSCRIPTEN_RESULT_NOT_SUPPORTED => "Not supported", ffi::EMSCRIPTEN_RESULT_FAILED...
error_to_str
identifier_name
mod.rs
#![cfg(target_os = "emscripten")] use std::ffi::CString; use libc; use {Event, BuilderAttribs, CreationError, MouseCursor}; use Api; use PixelFormat; use GlContext; use std::collections::VecDeque; mod ffi; pub struct Window { context: ffi::EMSCRIPTEN_WEBGL_CONTEXT_HANDLE, } pub struct PollEventsIterator<'a> { ...
// TODO: emscripten_set_webglcontextrestored_callback Ok(Window { context: context }) } pub fn is_closed(&self) -> bool { use std::ptr; unsafe { ffi::emscripten_is_webgl_context_lost(ptr::null()) != 0 } } pub fn set_title(&self, _title: &str) { ...
random_line_split
mod.rs
#![cfg(target_os = "emscripten")] use std::ffi::CString; use libc; use {Event, BuilderAttribs, CreationError, MouseCursor}; use Api; use PixelFormat; use GlContext; use std::collections::VecDeque; mod ffi; pub struct Window { context: ffi::EMSCRIPTEN_WEBGL_CONTEXT_HANDLE, } pub struct PollEventsIterator<'a> { ...
pub fn get_position(&self) -> Option<(i32, i32)> { Some((0, 0)) } pub fn set_position(&self, _: i32, _: i32) { } pub fn get_inner_size(&self) -> Option<(u32, u32)> { unsafe { use std::{mem, ptr}; let mut width = mem::uninitialized(); let mut he...
{ }
identifier_body
fs.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 ...
#[test] fn directory_junctions_are_directories() { use ffi::OsStr; use env; use rand::{self, StdRng, Rng}; macro_rules! t { ($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{} failed with: {}", stringify!($e), e), }) } let d = DirBuilder::new(); ...
{ unsafe extern "system" fn callback( _TotalFileSize: libc::LARGE_INTEGER, TotalBytesTransferred: libc::LARGE_INTEGER, _StreamSize: libc::LARGE_INTEGER, _StreamBytesTransferred: libc::LARGE_INTEGER, _dwStreamNumber: libc::DWORD, _dwCallbackReason: libc::DWORD, ...
identifier_body
fs.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 ...
Ok(attr) } } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.handle.read(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.handle.write(buf) } pub fn flush(&self) -> io::Result<()> { Ok(()) } pub fn seek(&self, pos: See...
{ let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE]; if let Ok((_, buf)) = self.reparse_point(&mut b) { attr.reparse_tag = buf.ReparseTag; } }
conditional_block
fs.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 ...
try!(cvt(c::LookupPrivilegeValueW(0 as *const _, name.as_ptr(), &mut tp.Privileges[0].Luid))); tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = c::SE_PRIVILEGE_ENABLED; let siz...
} else { "SeBackupPrivilege".as_ref() }; let name = name.encode_wide().chain(Some(0)).collect::<Vec<_>>();
random_line_split
fs.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 ...
(&self) -> u64 { ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64) } pub fn perm(&self) -> FilePermissions { FilePermissions { attrs: self.data.dwFileAttributes } } pub fn attrs(&self) -> u32 { self.data.dwFileAttributes as u32 } pub fn file_type(&self) ->...
size
identifier_name
config.py
# -*- coding: utf-8 -*- # Copyright (C) 2015 Luis López <luis@cuarentaydos.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any late...
nittest.main()
conditional_block
config.py
# -*- coding: utf-8 -*- # Copyright (C) 2015 Luis López <luis@cuarentaydos.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any late...
self): s = config.Record() s.set('foo', 1) s.set('bar', 'x') s.set('x.y', []) self.assertEqual(s.get('foo'), 1) self.assertEqual(s.get('bar'), 'x') self.assertEqual(s.get('x.y'), []) def test_nonexistent_key(self): s = config.Record() with se...
est_setget(
identifier_name
config.py
# -*- coding: utf-8 -*- # Copyright (C) 2015 Luis López <luis@cuarentaydos.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any late...
pass def test_init_with_args(self): a = config.Record({'foo': 1, 'bar': 'x'}) self.assertEqual(a.get('foo'), 1) b = config.Record() b.set('foo', 1) b.set('bar', 'x') self.assertEqual(a, b) def test_setget(self): s = config.Record() s.se...
from ldotcommons import config class TestRecord(unittest.TestCase): def setUp(self):
random_line_split
config.py
# -*- coding: utf-8 -*- # Copyright (C) 2015 Luis López <luis@cuarentaydos.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any late...
def test_children(self): x = config.Record({ 'foo': 1, 'bar.x': 'x', 'bar.y': 'y', }) self.assertEqual(set(x.children('bar')), set(['x', 'y'])) class TestRecordAttr(unittest.TestCase): def test_getset(self): x = config.RecordAttr({'foo':...
= config.Record({ 'foo': 1, 'bar.x': 'x', 'bar.y': 'y', }) y = config.Record({ 'x': 'x', 'y': 'y', }) self.assertEqual(x.sub('bar'), y)
identifier_body
currencies.py
# -*- coding: utf-8 -*- # vim:fenc=utf-8 ''' Insights Forex live source -------------------------- :copyright (c) 2014 Xavier Bruhiere :license: Apache 2.0, see LICENSE for more details. ''' import time import pandas as pd import dna.logging import intuition.data.forex as forex log = dna.logging.logger(__n...
self.forex.connect() def get_data(self, sids): while True: rates = self.forex.query_rates() if len(rates.keys()) >= len(sids): log.debug('Data available for {}'.format(rates.keys())) break log.debug('Incomplete data ({}/{}), retryi...
self._wait_retry = properties.get('retry', 10) self.forex = forex.TrueFX(pairs=pairs)
random_line_split
currencies.py
# -*- coding: utf-8 -*- # vim:fenc=utf-8 ''' Insights Forex live source -------------------------- :copyright (c) 2014 Xavier Bruhiere :license: Apache 2.0, see LICENSE for more details. ''' import time import pandas as pd import dna.logging import intuition.data.forex as forex log = dna.logging.logger(__n...
return { 'dt': (lambda x: x, 'dt'), #TODO Here conversion (weird result for now) # Or: (lambda x: pd.tslib.i8_to_pydt(x + '000000'), 'trade_time'), 'trade_time': (lambda x: pd.datetime.utcfromtimestamp( float(x[:-3])), 'timeStamp'), 'sid': (lam...
identifier_body
currencies.py
# -*- coding: utf-8 -*- # vim:fenc=utf-8 ''' Insights Forex live source -------------------------- :copyright (c) 2014 Xavier Bruhiere :license: Apache 2.0, see LICENSE for more details. ''' import time import pandas as pd import dna.logging import intuition.data.forex as forex log = dna.logging.logger(__n...
(self, pairs, properties): self._wait_retry = properties.get('retry', 10) self.forex = forex.TrueFX(pairs=pairs) self.forex.connect() def get_data(self, sids): while True: rates = self.forex.query_rates() if len(rates.keys()) >= len(sids): log...
__init__
identifier_name
currencies.py
# -*- coding: utf-8 -*- # vim:fenc=utf-8 ''' Insights Forex live source -------------------------- :copyright (c) 2014 Xavier Bruhiere :license: Apache 2.0, see LICENSE for more details. ''' import time import pandas as pd import dna.logging import intuition.data.forex as forex log = dna.logging.logger(__n...
return rates @property def mapping(self): return { 'dt': (lambda x: x, 'dt'), #TODO Here conversion (weird result for now) # Or: (lambda x: pd.tslib.i8_to_pydt(x + '000000'), 'trade_time'), 'trade_time': (lambda x: pd.datetime.utcfromtimestamp( ...
rates = self.forex.query_rates() if len(rates.keys()) >= len(sids): log.debug('Data available for {}'.format(rates.keys())) break log.debug('Incomplete data ({}/{}), retrying in {}s'.format( len(rates.keys()), len(sids), self._wait_retry)) ...
conditional_block
reflector.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 syntax::ast::{ItemKind, MetaItem}; use syntax::codemap::Span; use syntax::ext::base::{Annotatable, ExtCtxt}; u...
{ if let &Annotatable::Item(ref item) = annotatable { if let ItemKind::Struct(ref def, _) = item.node { let struct_name = item.ident; // This path has to be hardcoded, unfortunately, since we can't resolve paths at expansion time match def.fields().iter().find( ...
identifier_body
reflector.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 syntax::ast::{ItemKind, MetaItem}; use syntax::codemap::Span; use syntax::ext::base::{Annotatable, ExtCtxt}; u...
(cx: &mut ExtCtxt, span: Span, _: &MetaItem, annotatable: &Annotatable, push: &mut FnMut(Annotatable)) { if let &Annotatable::Item(ref item) = annotatable { if let ItemKind::Struct(ref def, _) = item.node { let struct_name = item.ident; // This path has to be ...
expand_reflector
identifier_name
reflector.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 syntax::ast::{ItemKind, MetaItem}; use syntax::codemap::Span; use syntax::ext::base::{Annotatable, ExtCtxt}; u...
}
{ if let ItemKind::Struct(ref def, _) = item.node { let struct_name = item.ident; // This path has to be hardcoded, unfortunately, since we can't resolve paths at expansion time match def.fields().iter().find( |f| match_ty_unwrap(&*f.ty, &["dom", "bindings...
conditional_block
reflector.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 syntax::ast::{ItemKind, MetaItem}; use syntax::codemap::Span; use syntax::ext::base::{Annotatable, ExtCtxt}; u...
} } }
} else { cx.span_err(span, "#[dom_struct] seems to have been applied to a non-struct");
random_line_split
terminal.rs
//! Support for terminal symbols use crate::status::Result; use crate::status::Status;
pub enum Terminal { /// Literal string Literal(String), ///// Character matches a list of chars or a list of ranges //Match(MatchRules), ///// Indicates an error. ///// It will propagate an error while processing //Expected(String), /// Any char Dot, /// End Of File Eof, } p...
/// This is a simple expression with no dependencies with other rules #[derive(Debug, PartialEq, Clone)]
random_line_split
terminal.rs
//! Support for terminal symbols use crate::status::Result; use crate::status::Status; /// This is a simple expression with no dependencies with other rules #[derive(Debug, PartialEq, Clone)] pub enum Terminal { /// Literal string Literal(String), ///// Character matches a list of chars or a list of ranges...
fn parse_eof<'a>(status: Status<'a>) -> Result<'a> { match status.get_char() { Ok((st, _ch)) => Err(st.to_error("not end of file :-(")), Err(st) => Ok(st), } } fn parse_literal<'a>(mut status: Status<'a>, literal: &str) -> Result<'a> { for ch in literal.chars() { status = parse_ch...
{ match terminal { Terminal::Eof => parse_eof(status), Terminal::Literal(l) => parse_literal(status, l), Terminal::Dot => parse_dot(status), } }
identifier_body
terminal.rs
//! Support for terminal symbols use crate::status::Result; use crate::status::Status; /// This is a simple expression with no dependencies with other rules #[derive(Debug, PartialEq, Clone)] pub enum Terminal { /// Literal string Literal(String), ///// Character matches a list of chars or a list of ranges...
<'a>(mut status: Status<'a>, literal: &str) -> Result<'a> { for ch in literal.chars() { status = parse_char(status, ch).map_err(|st| st.to_error(&format!("'{}'", literal)))?; } Ok(status) } fn parse_dot<'a>(status: Status<'a>) -> Result<'a> { let (status, _ch) = status.get_char().map_err(|st| s...
parse_literal
identifier_name
mvp.rs
// taken from vecmath & cam (MIT) // https://github.com/PistonDevelopers/vecmath // https://github.com/PistonDevelopers/cam pub type Vector4 = [f32; 4]; pub type Matrix4 = [[f32; 4]; 4]; pub fn model_view_projection(model: Matrix4, view: Matrix4, projection: Matrix4) -> Matrix4 { col_mat4_mul(col_mat4_mul(project...
fn row_mat4_col(a: Matrix4, i: usize) -> Vector4 { [a[0][i], a[1][i], a[2][i], a[3][i]] }
{ row_mat4_col(a, i) }
identifier_body
mvp.rs
// taken from vecmath & cam (MIT) // https://github.com/PistonDevelopers/vecmath // https://github.com/PistonDevelopers/cam pub type Vector4 = [f32; 4]; pub type Matrix4 = [[f32; 4]; 4]; pub fn model_view_projection(model: Matrix4, view: Matrix4, projection: Matrix4) -> Matrix4 { col_mat4_mul(col_mat4_mul(project...
(a: Matrix4, b: Matrix4, i: usize) -> Vector4 { [ vec4_dot(col_mat4_row(a, 0), b[i]), vec4_dot(col_mat4_row(a, 1), b[i]), vec4_dot(col_mat4_row(a, 2), b[i]), vec4_dot(col_mat4_row(a, 3), b[i]), ] } fn vec4_dot(a: Vector4, b: Vector4) -> f32 { a[0] * b[0] + a[1] * b[1] + a[2]...
col_mat4_mul_col
identifier_name
mvp.rs
// taken from vecmath & cam (MIT) // https://github.com/PistonDevelopers/vecmath // https://github.com/PistonDevelopers/cam pub type Vector4 = [f32; 4]; pub type Matrix4 = [[f32; 4]; 4]; pub fn model_view_projection(model: Matrix4, view: Matrix4, projection: Matrix4) -> Matrix4 { col_mat4_mul(col_mat4_mul(project...
fn vec4_dot(a: Vector4, b: Vector4) -> f32 { a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3] } fn col_mat4_row(a: Matrix4, i: usize) -> Vector4 { row_mat4_col(a, i) } fn row_mat4_col(a: Matrix4, i: usize) -> Vector4 { [a[0][i], a[1][i], a[2][i], a[3][i]] }
] }
random_line_split
conf_manager.py
import sys import yaml import collections Conf = collections.namedtuple( 'Conf', 'links audio_formats show_download_progress overrride_audios' ) class ConfManager(object): DEFAULT_AUDIO_FORMATS = ['mp4', 'mp3', 'webm', 'm4a', 'ogg', 'wma'] @classmethod def get_conf(cls, file_path): with...
return Conf( links=links, audio_formats=audio_formats, show_download_progress=show_download_progress, overrride_audios=overrride_audios )
show_download_progress = conf.get('show-download-progress', True) overrride_audios = conf.get('overrride-audios', False)
random_line_split
conf_manager.py
import sys import yaml import collections Conf = collections.namedtuple( 'Conf', 'links audio_formats show_download_progress overrride_audios' ) class
(object): DEFAULT_AUDIO_FORMATS = ['mp4', 'mp3', 'webm', 'm4a', 'ogg', 'wma'] @classmethod def get_conf(cls, file_path): with open(file_path, 'r') as stream: try: conf = yaml.load(stream) except yaml.YAMLError as exc: sys.exit(exc) l...
ConfManager
identifier_name
conf_manager.py
import sys import yaml import collections Conf = collections.namedtuple( 'Conf', 'links audio_formats show_download_progress overrride_audios' ) class ConfManager(object):
DEFAULT_AUDIO_FORMATS = ['mp4', 'mp3', 'webm', 'm4a', 'ogg', 'wma'] @classmethod def get_conf(cls, file_path): with open(file_path, 'r') as stream: try: conf = yaml.load(stream) except yaml.YAMLError as exc: sys.exit(exc) links = conf.get...
identifier_body
htmltablerowelement.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 cssparser::RGBA; use dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTMLTableElementMethods; use d...
htmlelement: HTMLElement::new_inherited(local_name, prefix, document), cells: Default::default(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> Root<HTMLTableRowElement> { Node::re...
impl HTMLTableRowElement { fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLTableRowElement { HTMLTableRowElement {
random_line_split
htmltablerowelement.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 cssparser::RGBA; use dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTMLTableElementMethods; use d...
#[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> Root<HTMLTableRowElement> { Node::reflect_node(box HTMLTableRowElement::new_inherited(local_name, prefix, document), document, ...
{ HTMLTableRowElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), cells: Default::default(), } }
identifier_body
htmltablerowelement.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 cssparser::RGBA; use dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTMLTableElementMethods; use d...
; self.row_index(collection) } } pub trait HTMLTableRowElementLayoutHelpers { fn get_background_color(&self) -> Option<RGBA>; } #[allow(unsafe_code)] impl HTMLTableRowElementLayoutHelpers for LayoutJS<HTMLTableRowElement> { fn get_background_color(&self) -> Option<RGBA> { unsafe { ...
{ return -1; }
conditional_block
htmltablerowelement.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 cssparser::RGBA; use dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTMLTableElementMethods; use d...
(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLTableRowElement { HTMLTableRowElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), cells: Default::default(), } } #[allow(unrooted_must_root)] ...
new_inherited
identifier_name
NodeSerializationCodes.py
from Node import error SYNTAX_NODE_SERIALIZATION_CODES = { # 0 is 'Token'. Needs to be defined manually # 1 is 'Unknown'. Needs to be defined manually 'UnknownDecl': 2, 'TypealiasDecl': 3, 'AssociatedtypeDecl': 4, 'IfConfigDecl': 5, 'PoundErrorDecl': 6, 'PoundWarningDecl': 7, 'Poun...
def get_serialization_code(syntax_kind): return SYNTAX_NODE_SERIALIZATION_CODES[syntax_kind]
for node in nodes: if not node.is_base() and node.syntax_kind not in serialization_codes: error('Node %s has no serialization code' % node.syntax_kind) # Verify that no serialization code is used twice used_codes = set() for serialization_code in serialization_codes.values(): if...
identifier_body
NodeSerializationCodes.py
from Node import error SYNTAX_NODE_SERIALIZATION_CODES = { # 0 is 'Token'. Needs to be defined manually # 1 is 'Unknown'. Needs to be defined manually 'UnknownDecl': 2, 'TypealiasDecl': 3, 'AssociatedtypeDecl': 4, 'IfConfigDecl': 5, 'PoundErrorDecl': 6, 'PoundWarningDecl': 7, 'Poun...
used_codes.add(serialization_code) def get_serialization_code(syntax_kind): return SYNTAX_NODE_SERIALIZATION_CODES[syntax_kind]
error("Serialization code %d used twice" % serialization_code)
conditional_block
NodeSerializationCodes.py
from Node import error SYNTAX_NODE_SERIALIZATION_CODES = { # 0 is 'Token'. Needs to be defined manually # 1 is 'Unknown'. Needs to be defined manually 'UnknownDecl': 2, 'TypealiasDecl': 3, 'AssociatedtypeDecl': 4, 'IfConfigDecl': 5, 'PoundErrorDecl': 6, 'PoundWarningDecl': 7, 'Poun...
(nodes, serialization_codes): # Verify that all nodes have serialization codes for node in nodes: if not node.is_base() and node.syntax_kind not in serialization_codes: error('Node %s has no serialization code' % node.syntax_kind) # Verify that no serialization code is used twice us...
verify_syntax_node_serialization_codes
identifier_name
NodeSerializationCodes.py
from Node import error SYNTAX_NODE_SERIALIZATION_CODES = { # 0 is 'Token'. Needs to be defined manually # 1 is 'Unknown'. Needs to be defined manually 'UnknownDecl': 2, 'TypealiasDecl': 3, 'AssociatedtypeDecl': 4, 'IfConfigDecl': 5, 'PoundErrorDecl': 6, 'PoundWarningDecl': 7, 'Poun...
'PoundFunctionExpr': 36, 'PoundDsohandleExpr': 37, 'SymbolicReferenceExpr': 38, 'PrefixOperatorExpr': 39, 'BinaryOperatorExpr': 40, 'ArrowExpr': 41, 'FloatLiteralExpr': 42, 'TupleExpr': 43, 'ArrayExpr': 44, 'DictionaryExpr': 45, 'ImplicitMemberExpr': 46, 'IntegerLiteralEx...
'DiscardAssignmentExpr': 31, 'AssignmentExpr': 32, 'SequenceExpr': 33, 'PoundLineExpr': 34, 'PoundFileExpr': 35,
random_line_split
zoomdata-chart-add.ts
#!/usr/bin/env node import * as program from 'commander'; import { add } from './commands/add'; import { getConfig } from './commands/config'; import { parseCredentials, parseUrl } from './utilities';
'-a, --app [URL]', 'Specify the Zoomdata application server URL (e.g. https://myserver/zoomdata)', parseUrl, ) .option( '-t, --type [chart|library]', 'Set the type of object to add. Valid options: "chart (default)", "library"', value => { const valueLower = value.toLowerCase(); i...
program .description('Add a custom chart or library to the Zoomdata server') .arguments('<name> <filepath>') .option(
random_line_split
zoomdata-chart-add.ts
#!/usr/bin/env node import * as program from 'commander'; import { add } from './commands/add'; import { getConfig } from './commands/config'; import { parseCredentials, parseUrl } from './utilities'; program .description('Add a custom chart or library to the Zoomdata server') .arguments('<name> <filepath>') .o...
if (program.args.length < 2) { console.log( 'Invalid number of arguments. Please provide the name and filepath of the chart or library you want to add', ); program.help(); process.exit(1); } else { const objectName = program.args[0]; const filepath = program.args[1]; add(objectName, filepath, config...
{ program.help(); process.exit(1); }
conditional_block
custom-typings.d.ts
/* * Custom Type Definitions * When including 3rd party modules you also need to include the type definition for the module * if they don't provide one within the module. You can try to install it with @types npm install @types/node npm install @types/lodash * If you can't find the type definition in the registry...
} * If you are using a CommonJS module that is using module.exports then you will have to write your * types using export = yourObjectOrFunction with a namespace above it * notice how we have to create a namespace that is equal to the function we're assigning the export to declare module "jwt-decode" { function ...
random_line_split
should-tests.ts
/// <reference path="should.d.ts" /> import should = require('should'); should.fail('actual', 'expected', 'msg', 'operator'); should.assert('value', 'msg'); should.ok('value'); should.equal('actual', 'expected'); should.notEqual('actual', 'expected'); should.deepEqual('actual', 'expected'); should.notDeepEqual('actua...
{ name: string; pets: string[]; age: number; } var user = { name: 'tj', pets: ['tobi', 'loki', 'jane', 'bandit'], age: 17 }; user.should.have.property('name', 'tj'); user.should.have.property('pets').with.lengthOf(4); should.exist('hello'); should.exist([]); should.exist(null); should.not.exist(false);...
User
identifier_name
should-tests.ts
/// <reference path="should.d.ts" /> import should = require('should'); should.fail('actual', 'expected', 'msg', 'operator'); should.assert('value', 'msg'); should.ok('value'); should.equal('actual', 'expected'); should.notEqual('actual', 'expected'); should.deepEqual('actual', 'expected'); should.notDeepEqual('actua...
should.exist({}); should.exist([]); should.exist(''); should.exist(0); should.exist(null); should.exist(undefined); should.not.exist(undefined); should.not.exist(null); should.not.exist(''); should.not.exist({}); true.should.be.ok; 'yay'.should.be.ok; (1).should.be.ok; false.should.not.be.ok; ''.should.not.be.ok; (...
user.should.be.a('object').and.have.property('name', 'tj'); 'foo'.should.equal('bar');
random_line_split
dependency-compare.component.ts
import {AfterViewInit, Component, OnInit, ViewChild, ViewEncapsulation} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import {UserService} from '../../service/user.service'; import {ProjectService} from '../../service/project.service'; import {FORBIDDEN} from 'http-status-codes'; import ...
ngAfterViewInit(): void { this.getData(); } getData(): void { this.projectService.getCompareTree(this.projectId, this.commitName, this.commitName2).then(response => { this.node = response.body; this.checkChanged = false; this.svg = document.getElementById('3svg'); this.checkDown =...
random_line_split
dependency-compare.component.ts
import {AfterViewInit, Component, OnInit, ViewChild, ViewEncapsulation} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import {UserService} from '../../service/user.service'; import {ProjectService} from '../../service/project.service'; import {FORBIDDEN} from 'http-status-codes'; import ...
}); } public onShowChangedChanged(): void { this.checkChanged = !this.checkChanged; this.draw(() => this.loadDependencies(this.node, this.checkChanged)); } }
{ this.userService.refresh(() => this.getData()); }
conditional_block
dependency-compare.component.ts
import {AfterViewInit, Component, OnInit, ViewChild, ViewEncapsulation} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import {UserService} from '../../service/user.service'; import {ProjectService} from '../../service/project.service'; import {FORBIDDEN} from 'http-status-codes'; import ...
ngOnInit(): void { this.route.params.subscribe(params => { this.projectId = params.projectId; this.commitName = params.commitName1; this.commitName2 = params.commitName2; this.getProject(); }); } ngAfterViewInit(): void { this.getData(); } getData(): void { this.pro...
{ super(); this.projectService = projectService; this.userService = userService; this.router = router; }
identifier_body
dependency-compare.component.ts
import {AfterViewInit, Component, OnInit, ViewChild, ViewEncapsulation} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import {UserService} from '../../service/user.service'; import {ProjectService} from '../../service/project.service'; import {FORBIDDEN} from 'http-status-codes'; import ...
(): void { this.getData(); } getData(): void { this.projectService.getCompareTree(this.projectId, this.commitName, this.commitName2).then(response => { this.node = response.body; this.checkChanged = false; this.svg = document.getElementById('3svg'); this.checkDown = this.checkUp = t...
ngAfterViewInit
identifier_name
trace.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/. */ //! Utilities for tracing JS-managed values. //! //! The lifetime of DOM objects is managed by the SpiderMonkey Ga...
pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: *mut JSObject) { unsafe { let name = CString::new(description).unwrap(); (*tracer).debugPrinter = None; (*tracer).debugPrintIndex = !0; (*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void; debug!("t...
trace_object(tracer, description, reflector.get_jsobject()) } /// Trace a `JSObject`.
random_line_split
trace.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/. */ //! Utilities for tracing JS-managed values. //! //! The lifetime of DOM objects is managed by the SpiderMonkey Ga...
} enum Void {} impl VecRootableType for Void { fn tag(_a: Option<Void>) -> CollectionType { unreachable!() } } impl Reflectable for Void { fn reflector<'a>(&'a self) -> &'a Reflector { unreachable!() } } /// A vector of items that are rooted for the lifetime /// of this struct #[allow(unrooted_must_root)] ...
{ CollectionType::JSObjects }
identifier_body
trace.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/. */ //! Utilities for tracing JS-managed values. //! //! The lifetime of DOM objects is managed by the SpiderMonkey Ga...
(&self, trc: *mut JSTracer) { if !self.is_null() { unsafe { (**self).trace(trc) } } } } impl<T: JSTraceable> JSTraceable for *mut T { fn trace(&self, trc: *mut JSTracer) { if !self.is_null() { unsafe { (**self).trace(tr...
trace
identifier_name
trace.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/. */ //! Utilities for tracing JS-managed values. //! //! The lifetime of DOM objects is managed by the SpiderMonkey Ga...
unsafe { let name = CString::new(description).unwrap(); (*tracer).debugPrinter = None; (*tracer).debugPrintIndex = !0; (*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void; debug!("tracing value {}", description); JS_CallTracer(tracer, val.to_gcthing(), va...
{ return; }
conditional_block
main.rs
#![cfg_attr(all(test, feature = "nightly"), feature(test))] // we only need test feature when testing #[macro_use] extern crate log; extern crate syntex_syntax; extern crate toml; extern crate env_logger; extern crate racer; #[cfg(not(test))] use racer::core; #[cfg(not(test))] use racer::util; #[cfg(not(test))] use...
(args: Vec<String>, linenum: usize, print_type: CompletePrinter) { // input: linenum, colnum, fname let tb = std::thread::Builder::new().name("searcher".to_string()); // PD: this probably sucks for performance, but lots of plugins // end up failin...
complete_by_line_coords
identifier_name
main.rs
#![cfg_attr(all(test, feature = "nightly"), feature(test))] // we only need test feature when testing #[macro_use] extern crate log; extern crate syntex_syntax; extern crate toml; extern crate env_logger; extern crate racer; #[cfg(not(test))] use racer::core; #[cfg(not(test))] use racer::util; #[cfg(not(test))] use...
match res.join() { Ok(_) => {}, Err(e) => { error!("Search thread paniced: {:?}", e); } } println!("END"); } #[cfg(not(test))] enum CompletePrinter { Normal, WithSnippets } #[cfg(not(test))] fn run_the_complete_fn(args: Vec<String>, linenum: usize, print_type:...
// end up failing and leaving tmp files around if racer crashes, // so catch the crash. let res = tb.spawn(move || { run_the_complete_fn(args, linenum, print_type); }).unwrap();
random_line_split
main.rs
#![cfg_attr(all(test, feature = "nightly"), feature(test))] // we only need test feature when testing #[macro_use] extern crate log; extern crate syntex_syntax; extern crate toml; extern crate env_logger; extern crate racer; #[cfg(not(test))] use racer::core; #[cfg(not(test))] use racer::util; #[cfg(not(test))] use...
#[cfg(not(test))] fn daemon() { use std::io; let mut input = String::new(); while let Ok(n) = io::stdin().read_line(&mut input) { if n == 0 { break; } let args: Vec<String> = input.split(" ").map(|s| s.trim().to_string()).collect(); run(args); i...
{ if let Ok(srcpaths) = std::env::var("RUST_SRC_PATH") { let v = srcpaths.split(PATH_SEP).collect::<Vec<_>>(); if !v.is_empty() { let f = Path::new(v[0]); if !path_exists(f) { println!("racer can't find the directory pointed to by the RUST_SRC_PATH variable \"...
identifier_body
ExtractSpecificVertices.py
# -*- coding: utf-8 -*- """ *************************************************************************** ExtractSpecificVertices.py -------------------- Date : October 2016 Copyright : (C) 2016 by Nyall Dawson Email : nyall dot dawson at gmail dot com ******...
def displayName(self): return self.tr('Extract specific vertices') def tags(self): return self.tr('points,vertex,nodes').split(',') def processAlgorithm(self, parameters, context, feedback): source = self.parameterAsSource(parameters, self.INPUT, context) if source is Non...
return 'extractspecificvertices'
identifier_body