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
color.py
#!/usr/bin/env python3 # # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution # Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io> # # 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 Softwa...
(s): return s def set_vt100(): 'hack to put term into VT100 mode under MSWin' from .globalvars import g if g.platform == 'win': from subprocess import run run([],shell=True) def get_terminfo_colors(term=None): from subprocess import run,PIPE cmd = ['infocmp','-0'] if term: cmd.append(term) try: cmdou...
nocolor
identifier_name
color.py
#!/usr/bin/env python3 # # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution # Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io> # # 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 Softwa...
'magenta': ( 205, (35,1) ), 'cyan': ( 122, (36,1) ), 'pink': ( 218, (35,1) ), 'orange': ( 216, (31,1) ), 'gray': ( 246, (30,1) ), 'purple': ( 141, (35,1) ), 'brown': ( 208, (33,0) ), 'grndim': ( 108, (32,0) ), 'redbg...
'blue': ( 75, (34,1) ),
random_line_split
ORProcess.js
ORProcess = function(_process) { this._process = _process; this.inputState = {}; this.beforeKill = function() { log(this._process.getPid() + ": beforeKill"); }; this.beforeRemoveVertex = function(vertex) { log(this._process.getPid() + ": beforeRemoveVertex"); }; ...
"state": outputValue }) ); } this.inputState = {}; }; return this; };
"type": "state", "from": "" + this._process.getContext().get("_key"),
random_line_split
dataColorPaletteTests.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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 restric...
{ value: '#000003' }, ]; beforeEach(() => { scale = powerbi.visuals.D3ColorScale.createFromColors(colors); }); it('should cover all colors and wrap around',() => { for (var i = 0; i < colors.length; i++) { expect(scale.getColor(i).val...
var colors = [ { value: '#000000' }, { value: '#000001' }, { value: '#000002' },
random_line_split
dataColorPaletteTests.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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 restric...
// Wrap around should occur now, verify we are back to the start expect(scale.getColor('abc series')).toBe(color0); }); // The Sentiment/KPI color API is just temporary until conditional formatting is avaiable, but while the API is active it needs to be tested. // We can...
var nextColor = scale.getColor(i); expect(nextColor).toExist(); expect(nextColor.value).not.toBe(previousColor.value); previousColor = nextColor; }
conditional_block
SinDemo.js
function SinDemo(dim){ var dim=dim; var space= new EucSpace(dim); var stage= new Stage(space); // stage.addAxes(); var res=7; if(dim==4){ res = 5; } if(dim>4){ res=3; } var grid=new SquareGrid(dim-1,400,res); var map=new SinEuc(dim-1,1,0); stage.newRopes(map.toEucLinesList...
// stage.newRopes(map.toEucLinesList(map.fromEucLinesList(sin.edges())),'red'); var camcoord=[]; for(var i=0; i<dim;i++){ camcoord[i]=200; } var camPos=space.newVector(camcoord); var cam= new Camera(stage,camPos,emptyOrientation(dim)); var phase=0; var delta=0.02; this.onFrame=fu...
// var sin= new Sin(2,2,0);
random_line_split
SinDemo.js
function
(dim){ var dim=dim; var space= new EucSpace(dim); var stage= new Stage(space); // stage.addAxes(); var res=7; if(dim==4){ res = 5; } if(dim>4){ res=3; } var grid=new SquareGrid(dim-1,400,res); var map=new SinEuc(dim-1,1,0); stage.newRopes(map.toEucLinesList(grid.edges()),'...
SinDemo
identifier_name
SinDemo.js
function SinDemo(dim){ var dim=dim; var space= new EucSpace(dim); var stage= new Stage(space); // stage.addAxes(); var res=7; if(dim==4)
if(dim>4){ res=3; } var grid=new SquareGrid(dim-1,400,res); var map=new SinEuc(dim-1,1,0); stage.newRopes(map.toEucLinesList(grid.edges()),'#999'); // var sin= new Sin(2,2,0); // stage.newRopes(map.toEucLinesList(map.fromEucLinesList(sin.edges())),'red'); var camcoord=[]; for(var i=0;...
{ res = 5; }
conditional_block
SinDemo.js
function SinDemo(dim)
// stage.newRopes(map.toEucLinesList(map.fromEucLinesList(sin.edges())),'red'); var camcoord=[]; for(var i=0; i<dim;i++){ camcoord[i]=200; } var camPos=space.newVector(camcoord); var cam= new Camera(stage,camPos,emptyOrientation(dim)); var phase=0; var delta=0.02; this.onFrame=fu...
{ var dim=dim; var space= new EucSpace(dim); var stage= new Stage(space); // stage.addAxes(); var res=7; if(dim==4){ res = 5; } if(dim>4){ res=3; } var grid=new SquareGrid(dim-1,400,res); var map=new SinEuc(dim-1,1,0); stage.newRopes(map.toEucLinesList(grid.edges()),'#999'...
identifier_body
facebook.py
from flask import Flask, redirect, url_for, session, request from flask_oauthlib.client import OAuth, OAuthException FACEBOOK_APP_ID = '188477911223606' FACEBOOK_APP_SECRET = '621413ddea2bcc5b2e83d42fc40495de' app = Flask(__name__) app.debug = True app.secret_key = 'development' oauth = OAuth(app) facebook = oauth...
@app.route('/') def index(): return redirect(url_for('login')) @app.route('/login') def login(): callback = url_for( 'facebook_authorized', next=request.args.get('next') or request.referrer or None, _external=True ) return facebook.authorize(callback=callback) @app.route('/lo...
random_line_split
facebook.py
from flask import Flask, redirect, url_for, session, request from flask_oauthlib.client import OAuth, OAuthException FACEBOOK_APP_ID = '188477911223606' FACEBOOK_APP_SECRET = '621413ddea2bcc5b2e83d42fc40495de' app = Flask(__name__) app.debug = True app.secret_key = 'development' oauth = OAuth(app) facebook = oauth...
@app.route('/login') def login(): callback = url_for( 'facebook_authorized', next=request.args.get('next') or request.referrer or None, _external=True ) return facebook.authorize(callback=callback) @app.route('/login/authorized') def facebook_authorized(): resp = facebook.au...
return redirect(url_for('login'))
identifier_body
facebook.py
from flask import Flask, redirect, url_for, session, request from flask_oauthlib.client import OAuth, OAuthException FACEBOOK_APP_ID = '188477911223606' FACEBOOK_APP_SECRET = '621413ddea2bcc5b2e83d42fc40495de' app = Flask(__name__) app.debug = True app.secret_key = 'development' oauth = OAuth(app) facebook = oauth...
(): callback = url_for( 'facebook_authorized', next=request.args.get('next') or request.referrer or None, _external=True ) return facebook.authorize(callback=callback) @app.route('/login/authorized') def facebook_authorized(): resp = facebook.authorized_response() if resp i...
login
identifier_name
facebook.py
from flask import Flask, redirect, url_for, session, request from flask_oauthlib.client import OAuth, OAuthException FACEBOOK_APP_ID = '188477911223606' FACEBOOK_APP_SECRET = '621413ddea2bcc5b2e83d42fc40495de' app = Flask(__name__) app.debug = True app.secret_key = 'development' oauth = OAuth(app) facebook = oauth...
session['oauth_token'] = (resp['access_token'], '') me = facebook.get('/me') return 'Logged in as id=%s name=%s redirect=%s' % \ (me.data['id'], me.data['name'], request.args.get('next')) @facebook.tokengetter def get_facebook_oauth_token(): return session.get('oauth_token') if __name__ ==...
return 'Access denied: %s' % resp.message
conditional_block
associated-const-ambiguity-report.rs
// Copyright 2015 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 ...
{ assert_eq!(1, X); }
identifier_body
associated-const-ambiguity-report.rs
// Copyright 2015 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 ...
() { assert_eq!(1, X); }
main
identifier_name
autoRefresh.tsx
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDI...
clearInterval(this.intervalHandle); this.intervalHandle = null; } } }
if (enable && !this.intervalHandle) { this.intervalHandle = setInterval(this.refreshCallback, this.interval); } else if (this.intervalHandle) {
random_line_split
autoRefresh.tsx
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDI...
} }
{ clearInterval(this.intervalHandle); this.intervalHandle = null; }
conditional_block
autoRefresh.tsx
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDI...
implements IAutoRefresh { private intervalHandle: NodeJS.Timeout | null = null; private readonly refreshCallback: typeof triggerRefresh; private readonly interval: number; constructor(callback: typeof triggerRefresh, interval: number) { this.setAutoRefresh = this.setAutoRefresh.bind(this); this.refres...
AutoRefresh
identifier_name
__init__.py
## # Copyright 2012-2015 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (htt...
# we're not the only ones in this namespace __path__ = extend_path(__path__, __name__) #@ReservedAssignment
@author: Stijn De Weirdt (Ghent University) @author: Kenneth Hoste (Ghent University) """ from pkgutil import extend_path
random_line_split
bootstraphelper.js
//page.js //scripts for bootstrap // enable tooltips // $(function () { // $('[data-toggle="tooltip"]').tooltip(); // }); $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip({ trigger: "hover" }); }); //enable modal focus $('#site-list-modal').on('shown.bs.modal', fun...
});
// time.attr; $(".alert-save-site").alert('close')
random_line_split
bootstraphelper.js
//page.js //scripts for bootstrap // enable tooltips // $(function () { // $('[data-toggle="tooltip"]').tooltip(); // }); $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip({ trigger: "hover" }); }); //enable modal focus $('#site-list-modal').on('shown.bs.modal', fun...
date = new Date(); obsStartDate = dateString(date); obsStartTime = timeString(date); date1 = document.getElementById('obs-start-date'); date1.setAttribute('placeholder', obsStartDate); time1 = document.getElementById('obs-start-time'); time1.setAttribute('placeholder', obsStartTime); ...
var options = { hour: 'numeric', minute: 'numeric' }; return t.toLocaleTimeString("ru-RU",options); }
identifier_body
bootstraphelper.js
//page.js //scripts for bootstrap // enable tooltips // $(function () { // $('[data-toggle="tooltip"]').tooltip(); // }); $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip({ trigger: "hover" }); }); //enable modal focus $('#site-list-modal').on('shown.bs.modal', fun...
(t) { var options = { hour: 'numeric', minute: 'numeric' }; return t.toLocaleTimeString("ru-RU",options); } date = new Date(); obsStartDate = dateString(date); obsStartTime = timeString(date); date1 = document.getElementById('obs-start-date'); date1.setAttribute(...
imeString
identifier_name
fun.rs
use allegro5::*; //~ use std::cmp::{max, min}; use std::num::abs; use world::{World, TILE_SIZE}; use camera::Camera; use util::intersect_rect; use gfx::Gfx; pub struct Demon { pub x: i32, pub y: i32, pub vx: i32, pub vy: i32, pub dead: bool, pub moving_to_center: bool, pub active: bool, pub w: i32, pub h:...
pub fn new(x: i32, y: i32) -> Demon { Demon { x: x - 12, y: y - 12, vx: 0, vy: 0, moving_to_center: false, w: 24, h: 24, dead: false, active: false, } } pub fn update(&mut self, world: &World, player_x: i32, player_y: i32, player_w: i32, player_h: i32) -> bool { if self.dead ...
impl Demon {
random_line_split
fun.rs
use allegro5::*; //~ use std::cmp::{max, min}; use std::num::abs; use world::{World, TILE_SIZE}; use camera::Camera; use util::intersect_rect; use gfx::Gfx; pub struct
{ pub x: i32, pub y: i32, pub vx: i32, pub vy: i32, pub dead: bool, pub moving_to_center: bool, pub active: bool, pub w: i32, pub h: i32, } impl Demon { pub fn new(x: i32, y: i32) -> Demon { Demon { x: x - 12, y: y - 12, vx: 0, vy: 0, moving_to_center: false, w: 24, h: 24, dea...
Demon
identifier_name
fun.rs
use allegro5::*; //~ use std::cmp::{max, min}; use std::num::abs; use world::{World, TILE_SIZE}; use camera::Camera; use util::intersect_rect; use gfx::Gfx; pub struct Demon { pub x: i32, pub y: i32, pub vx: i32, pub vy: i32, pub dead: bool, pub moving_to_center: bool, pub active: bool, pub w: i32, pub h:...
, None => { self.vx = 0; self.vy = 0; } } } } let (nx, ny) = world.checked_move(self.x, self.y, self.w, self.h, self.vx, self.vy, true); if nx == self.x && ny == self.y && (self.vx != 0 || self.vy != 0) { // Stuck, move to tile center and try again self.moving_to_cent...
{ let (sx, sy) = a.get_shift(); self.vx = sx; self.vy = sy; self.active = true; }
conditional_block
constants.js
/** * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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.o...
/* * ANTLR related constants */ constants.antlr = { INDEX: "antlr4-js-runtime/index", ROOT: "antlr/", SYNTAX_ERROR_LISTENER: "SyntaxErrorListener", SIDDHI_DATA_POPULATION_LISTENER: "DataPopulationListener", SIDDHI_TOKEN_TOOL_TIP_UPDATE_LISTENER: "TokenTooltipPoi...
ACE_RANGE: "ace/range", LANG_LIB: "ace/lib/lang", TOKEN_TOOLTIP: "ace/token/tooltips" };
random_line_split
variance-cell-is-invariant.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
use std::cell::Cell; struct Foo<'a> { x: Cell<Option<&'a int>>, } fn use_<'short,'long>(c: Foo<'short>, s: &'short int, l: &'long int, _where:Option<&'short &'long ()>) { let _: Foo<'long> = c; //~ ERROR mismatched types } fn main() { }
random_line_split
variance-cell-is-invariant.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { }
main
identifier_name
cssterm.js
$(document).ready(function() { // Better performance in replacing js in any browsers. http://jsperf.com/encode-html-entities function htmlEscape(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&nbsp'); } function userReplace(str)
// the html that will be inserted to replace the shortened code // the terminal bar and body before the text is placed var termTop = '\ <div id="terminal-window"> \ <div id="terminal-toolbar"> \ <div class="terminal-top"> \ <div class="terminal-menu"> \ </div> \ <div id="terminal-button...
{ return str.replace(/^#/gi, '<root>[root@localhost]# </root>').replace(/^\$/gi, '<user>[loz@localhost]$ </user>'); }
identifier_body
cssterm.js
$(document).ready(function() { // Better performance in replacing js in any browsers. http://jsperf.com/encode-html-entities function htmlEscape(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&nbsp'); } function
(str) { return str.replace(/^#/gi, '<root>[root@localhost]# </root>').replace(/^\$/gi, '<user>[loz@localhost]$ </user>'); } // the html that will be inserted to replace the shortened code // the terminal bar and body before the text is placed var termTop = '\ <div id="terminal-window"> \ <div...
userReplace
identifier_name
cssterm.js
$(document).ready(function() { // Better performance in replacing js in any browsers. http://jsperf.com/encode-html-entities function htmlEscape(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&nbsp'); } function userReplace(str) { re...
}); $(this).replaceWith( termTop + newString + termBot ); }); });
{ // is string a root command if (this.charAt(0) == "#" || this.charAt(0) == "$") { newString += userReplace(this) + "<br>\n"; } else { newString += htmlEscape(this) + "<br>\n"; } }
conditional_block
cssterm.js
$(document).ready(function() { // Better performance in replacing js in any browsers. http://jsperf.com/encode-html-entities function htmlEscape(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&nbsp'); } function userReplace(str) { re...
newString += htmlEscape(this) + "<br>\n"; } } }); $(this).replaceWith( termTop + newString + termBot ); }); });
newString += userReplace(this) + "<br>\n"; } else {
random_line_split
Language.py
# -*- coding: UTF-8 -*- import gettext import locale import os from Tools.Directories import SCOPE_LANGUAGE, resolveFilename class Language: def __init__(self): gettext.install('enigma2', resolveFilename(SCOPE_LANGUAGE, ""), unicode=0, codeset="utf-8") gettext.bindtextdomain("enigma2", resolveFilename(SCOPE_LANG...
nd(callback) language = Language()
xcept: return 'ISO-8859-15' def addCallback(self, callback): self.callbacks.appe
identifier_body
Language.py
# -*- coding: UTF-8 -*- import gettext import locale import os from Tools.Directories import SCOPE_LANGUAGE, resolveFilename class Language: def __init__(self): gettext.install('enigma2', resolveFilename(SCOPE_LANGUAGE, ""), unicode=0, codeset="utf-8") gettext.bindtextdomain("enigma2", resolveFilename(SCOPE_LANG...
" + lang[0] self.catalog = gettext.translation('enigma2', resolveFilename(SCOPE_LANGUAGE, ""), languages=[index]) self.catalog.install(names=("ngettext", "pgettext")) self.activeLanguage = index for x in self.callbacks: x() except: print "Error in activating language!" # NOTE: we do not use LC_A...
n_EN!" % index index = "en_EN" lang = self.lang[index] print "Activating language
conditional_block
Language.py
# -*- coding: UTF-8 -*- import gettext import locale import os from Tools.Directories import SCOPE_LANGUAGE, resolveFilename class Language: def __init__(self): gettext.install('enigma2', resolveFilename(SCOPE_LANGUAGE, ""), unicode=0, codeset="utf-8") gettext.bindtextdomain("enigma2", resolveFilename(SCOPE_LANG...
# FIXME make list dynamically # name, iso-639 language, iso-3166 country. Please don't mix language&country! self.addLanguage("Arabic", "ar", "AE", "ISO-8859-15") self.addLanguage("Български", "bg", "BG", "ISO-8859-15") self.addLanguage("Català", "ca", "AD", "ISO-8859-15") self.addLanguage("Česky", "cs", "C...
self.lang = {} self.langlist = []
random_line_split
Language.py
# -*- coding: UTF-8 -*- import gettext import locale import os from Tools.Directories import SCOPE_LANGUAGE, resolveFilename class Language: def __init__(self): gettext.install('enigma2', resolveFilename(SCOPE_LANGUAGE, ""), unicode=0, codeset="utf-8") gettext.bindtextdomain("enigma2", resolveFilename(SCOPE_LANG...
e][3]) except: return 'ISO-8859-15' def addCallback(self, callback): self.callbacks.append(callback) language = Language()
self.lang[self.activeLanguag
identifier_name
session.service.js
angular.module('ssAuth').factory('SessionService', ['$http', '$cookies', '$q', function($http, $cookies, $q){ var currentUser = {}; var currentFetch; currentUser.isAdmin = function() { return currentUser && currentUser.groups && currentUser.groups['Admins']; }; var getCurrentUser = functi...
if(currentUser.lastUpdated) { var diffMS = (new Date()).getTime() - new Date(currentUser.lastUpdated).getTime(); var diffMin = ((diffMS/60)/60); if(diffMin < 5) { deferred.resolve(currentUser); return deferred.promise; ...
{ return fetchUpdatedUser(); }
conditional_block
session.service.js
angular.module('ssAuth').factory('SessionService', ['$http', '$cookies', '$q', function($http, $cookies, $q){ var currentUser = {}; var currentFetch; currentUser.isAdmin = function() { return currentUser && currentUser.groups && currentUser.groups['Admins'];
var getCurrentUser = function(forceUpdate) { var deferred = $q.defer(); if(forceUpdate) { return fetchUpdatedUser(); } if(currentUser.lastUpdated) { var diffMS = (new Date()).getTime() - new Date(currentUser.lastUpdated).getTime(); ...
};
random_line_split
account.ts
import { getDotComAPIEndpoint, IAPIEmail } from '../lib/api' /** * A GitHub account, representing the user found on GitHub The Website or GitHub Enterprise. * * This contains a token that will be used for operations that require authentication. */ export class Account { /** The access token used to perform opera...
(token: string): Account { return new Account( this.login, this.endpoint, token, this.emails, this.avatarURL, this.id, this.name ) } }
withToken
identifier_name
account.ts
import { getDotComAPIEndpoint, IAPIEmail } from '../lib/api' /** * A GitHub account, representing the user found on GitHub The Website or GitHub Enterprise. * * This contains a token that will be used for operations that require authentication. */ export class Account { /** The access token used to perform opera...
id: number, name: string ) { this.login = login this.endpoint = endpoint this.token = token this.emails = emails this.avatarURL = avatarURL this.id = id this.name = name } public withToken(token: string): Account { return new Account( this.login, this.endpoint,...
random_line_split
account.ts
import { getDotComAPIEndpoint, IAPIEmail } from '../lib/api' /** * A GitHub account, representing the user found on GitHub The Website or GitHub Enterprise. * * This contains a token that will be used for operations that require authentication. */ export class Account { /** The access token used to perform opera...
public constructor( login: string, endpoint: string, token: string, emails: ReadonlyArray<IAPIEmail>, avatarURL: string, id: number, name: string ) { this.login = login this.endpoint = endpoint this.token = token this.emails = emails this.avatarURL = avatarURL t...
{ return new Account('', getDotComAPIEndpoint(), '', [], '', -1, '') }
identifier_body
routing_client.rs
// Copyright 2015 MaidSafe.net limited. // // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // ...
(&self, location: Authority, data: Data) { let _ = self.action_sender.send(Action::ClientSendContent( location, Content::ExternalRequest(ExternalRequest::Delete(data)))); } /// Signal to RoutingNode that it needs to refuse new messages and handle all outstanding /// ...
delete_request
identifier_name
routing_client.rs
// Copyright 2015 MaidSafe.net limited. // // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // ...
let _ = self.action_sender.send(Action::ClientSendContent( location, Content::ExternalRequest(ExternalRequest::Post(data)))); } /// Remove something from the network pub fn delete_request(&self, location: Authority, data: Data) { let _ = self.action_sender.se...
Content::ExternalRequest(ExternalRequest::Put(data)))); } /// Change something already on the network pub fn post_request(&self, location: Authority, data: Data) {
random_line_split
cpu.rs
use anyhow::{anyhow, Result}; use cnx::text::{Attributes, Text}; use cnx::widgets::{Widget, WidgetStream}; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::time::Duration; use tokio::time; use tokio_stream::wrappers::IntervalStream; use tokio_stream::StreamExt; /// Represents CPU widget used t...
_ => return Err(anyhow!("Missing data in /proc/stat")), } Ok(cpu_data) } } impl Widget for Cpu { fn into_stream(mut self: Box<Self>) -> Result<WidgetStream> { let ten_seconds = Duration::from_secs(10); let interval = time::interval(ten_seconds); let stream =...
{ let user_time = user.parse()?; let nice_time = nice.parse()?; let system_time = system.parse()?; let idle_time = idle.parse()?; let iowait_time = iowait.parse()?; cpu_data.user_time = user_time; cpu_data.ni...
conditional_block
cpu.rs
use anyhow::{anyhow, Result}; use cnx::text::{Attributes, Text}; use cnx::widgets::{Widget, WidgetStream}; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::time::Duration; use tokio::time; use tokio_stream::wrappers::IntervalStream; use tokio_stream::StreamExt; /// Represents CPU widget used t...
(mut self: Box<Self>) -> Result<WidgetStream> { let ten_seconds = Duration::from_secs(10); let interval = time::interval(ten_seconds); let stream = IntervalStream::new(interval).map(move |_| self.tick()); Ok(Box::pin(stream)) } }
into_stream
identifier_name
cpu.rs
use anyhow::{anyhow, Result}; use cnx::text::{Attributes, Text}; use cnx::widgets::{Widget, WidgetStream}; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::time::Duration; use tokio::time; use tokio_stream::wrappers::IntervalStream; use tokio_stream::StreamExt; /// Represents CPU widget used t...
cpu_data.user_time = user_time; cpu_data.nice_time = nice_time; cpu_data.system_time = system_time; cpu_data.idle_time = idle_time; cpu_data.iowait_time = iowait_time; cpu_data.total_time = user_time + nice_time + system_tim...
let idle_time = idle.parse()?; let iowait_time = iowait.parse()?;
random_line_split
fieldParser.ts
import { Field, FieldType } from '../types/dataFrame'; import { guessFieldTypeFromValue } from '../dataframe/processDataFrame'; export function
(value: any, field: Field): (value: string) => any { if (!field.type) { if (field.name === 'time' || field.name === 'Time') { field.type = FieldType.time; } else { field.type = guessFieldTypeFromValue(value); } } if (field.type === FieldType.number) { return (value: string) => { ...
makeFieldParser
identifier_name
fieldParser.ts
import { Field, FieldType } from '../types/dataFrame'; import { guessFieldTypeFromValue } from '../dataframe/processDataFrame'; export function makeFieldParser(value: any, field: Field): (value: string) => any
} // Just pass the string back return (value: string) => value; }
{ if (!field.type) { if (field.name === 'time' || field.name === 'Time') { field.type = FieldType.time; } else { field.type = guessFieldTypeFromValue(value); } } if (field.type === FieldType.number) { return (value: string) => { return parseFloat(value); }; } // Will co...
identifier_body
fieldParser.ts
import { Field, FieldType } from '../types/dataFrame'; import { guessFieldTypeFromValue } from '../dataframe/processDataFrame'; export function makeFieldParser(value: any, field: Field): (value: string) => any { if (!field.type) { if (field.name === 'time' || field.name === 'Time') { field.type = FieldType...
return (value: string) => { return parseFloat(value); }; } // Will convert anything that starts with "T" to true if (field.type === FieldType.boolean) { return (value: string) => { return !(value[0] === 'F' || value[0] === 'f' || value[0] === '0'); }; } // Just pass the string ba...
field.type = guessFieldTypeFromValue(value); } } if (field.type === FieldType.number) {
random_line_split
fieldParser.ts
import { Field, FieldType } from '../types/dataFrame'; import { guessFieldTypeFromValue } from '../dataframe/processDataFrame'; export function makeFieldParser(value: any, field: Field): (value: string) => any { if (!field.type)
if (field.type === FieldType.number) { return (value: string) => { return parseFloat(value); }; } // Will convert anything that starts with "T" to true if (field.type === FieldType.boolean) { return (value: string) => { return !(value[0] === 'F' || value[0] === 'f' || value[0] === '0'...
{ if (field.name === 'time' || field.name === 'Time') { field.type = FieldType.time; } else { field.type = guessFieldTypeFromValue(value); } }
conditional_block
diff.py
# -*- coding: utf-8 -*- class DictDiffer(object): """
""" def __init__(self, current_dict, past_dict): self.current_dict = current_dict self.past_dict = past_dict self.set_current = set(current_dict.keys()) self.set_past = set(past_dict.keys()) self.intersect = self.set_current.intersection(self.set_past) def added(self...
Calculate the difference between two dictionaries as: (1) items added (2) items removed (3) keys same in both but changed values (4) keys same in both and unchanged values
random_line_split
diff.py
# -*- coding: utf-8 -*- class DictDiffer(object): """ Calculate the difference between two dictionaries as: (1) items added (2) items removed (3) keys same in both but changed values (4) keys same in both and unchanged values """ def __init__(self, current_dict, pas...
(DictDiffer): """ NmapDiff compares two objects of same type to enable the user to check: - what has changed - what has been added - what has been removed - what was kept unchanged NmapDiff inherit from DictDiffer which makes the actual comparaison. The diff...
NmapDiff
identifier_name
diff.py
# -*- coding: utf-8 -*- class DictDiffer(object): """ Calculate the difference between two dictionaries as: (1) items added (2) items removed (3) keys same in both but changed values (4) keys same in both and unchanged values """ def __init__(self, current_dict, pas...
self.object1 = nmap_obj1.get_dict() self.object2 = nmap_obj2.get_dict() DictDiffer.__init__(self, self.object1, self.object2) def __repr__(self): return ("added: [{0}] -- changed: [{1}] -- " "unchanged: [{2}] -- removed [{3}]".format(self.added(), ...
raise NmapDiffException("Comparing objects with non-matching id")
conditional_block
diff.py
# -*- coding: utf-8 -*- class DictDiffer(object): """ Calculate the difference between two dictionaries as: (1) items added (2) items removed (3) keys same in both but changed values (4) keys same in both and unchanged values """ def __init__(self, current_dict, pas...
self.msg = msg
identifier_body
service.effects.ts
/** * Copyright 2017 The Mifos Initiative. * * 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...
(private actions$: Actions, private customerService: CustomerService) { } }
constructor
identifier_name
service.effects.ts
/** * Copyright 2017 The Mifos Initiative. * * 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...
@Effect() executeTask: Observable<Action> = this.actions$ .ofType(taskActions.EXECUTE_TASK) .map((action: taskActions.ExecuteTaskAction) => action.payload) .mergeMap(payload => this.customerService.markTaskAsExecuted(payload.customerId, payload.taskId) .map(() => new taskActions.ExecuteTas...
.takeUntil(nextSearch$) .map(processSteps => new taskActions.LoadAllCompleteAction(processSteps)) .catch(() => of(new taskActions.LoadAllCompleteAction([]))); });
random_line_split
audioPage.js
/*global define, $, console, window, history, tizen*/ /** * Init page module */ define({ name: 'views/audioPage', def: function viewsAudioPage() { 'use strict'; var appControl = null, appControlReplyCallback = null; function onLaunchSuccess() { console.log('...
if (typeof tizen !== 'undefined' && typeof tizen.ApplicationControl === 'function') { appControl = new tizen.ApplicationControl( "http://tizen.org/appcontrol/operation/create_content", null, "audio/amr", null ...
} function init() {
random_line_split
audioPage.js
/*global define, $, console, window, history, tizen*/ /** * Init page module */ define({ name: 'views/audioPage', def: function viewsAudioPage() { 'use strict'; var appControl = null, appControlReplyCallback = null; function onLaunchSuccess() { console.log('...
appControlReplyCallback = { // callee sent a reply onsuccess: function onsuccess(data) { var i = 0, key = "http://tizen.org/appcontrol/data/selected"; for (i; i < data.length; i += 1) { ...
{ console.warn('tizen.ApplicationControl not available'); }
conditional_block
audioPage.js
/*global define, $, console, window, history, tizen*/ /** * Init page module */ define({ name: 'views/audioPage', def: function viewsAudioPage() { 'use strict'; var appControl = null, appControlReplyCallback = null; function
() { console.log('launchAppControl', 'onLaunchSuccess'); } function onLaunchError() { console.error('launchAppControl', 'onLaunchError'); } function launch() { if (typeof tizen !== 'undefined') { return; } tiz...
onLaunchSuccess
identifier_name
audioPage.js
/*global define, $, console, window, history, tizen*/ /** * Init page module */ define({ name: 'views/audioPage', def: function viewsAudioPage() { 'use strict'; var appControl = null, appControlReplyCallback = null; function onLaunchSuccess()
function onLaunchError() { console.error('launchAppControl', 'onLaunchError'); } function launch() { if (typeof tizen !== 'undefined') { return; } tizen.application.launchAppControl( appControl, "...
{ console.log('launchAppControl', 'onLaunchSuccess'); }
identifier_body
geometry.rs
, Rem}; use rustc_serialize::{Encoder, Encodable}; // Units for use with euclid::length and euclid::scale_factor. /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-i...
{} /// One CSS "px" in the coordinate system of the "initial viewport": /// http://www.w3.org/TR/css-device-adapt/#initial-viewport /// /// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layo...
ScreenPx
identifier_name
geometry.rs
Div, Rem}; use rustc_serialize::{Encoder, Encodable}; // Units for use with euclid::length and euclid::scale_factor. /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a devi...
#[inline] pub fn from_px(px: i32) -> Au { Au((px * 60) as i32) } #[inline] pub fn from_page_px(px: Length<PagePx, f32>) -> Au { Au((px.get() * 60f32) as i32) } /// Rounds this app unit down to the pixel towards zero and returns it. #[inline] pub fn to_px(self) -> i3...
pub fn scale_by(self, factor: f32) -> Au { Au(((self.0 as f32) * factor) as i32) }
random_line_split
geometry.rs
, Rem}; use rustc_serialize::{Encoder, Encodable}; // Units for use with euclid::length and euclid::scale_factor. /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-i...
} impl ToCss for Au { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}px", self.to_f64_px()) } } impl Add for Au { type Output = Au; #[inline] fn add(self, other: Au) -> Au { Au(self.0.wrapping_add(other.0)) } } impl Sub for Au { ty...
{ write!(f, "{}px", self.to_f64_px()) }
identifier_body
geometry.rs
, Rem}; use rustc_serialize::{Encoder, Encodable}; // Units for use with euclid::length and euclid::scale_factor. /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-i...
; } #[inline] pub fn from_f32_px(px: f32) -> Au { Au((px * 60f32) as i32) } #[inline] pub fn from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } #[inline] pub fn from_f64_px(px: f64) -> Au { Au((px * 60.) as i32) } } // assumes 72 points per inch,...
{ return Au(self.0 - res) }
conditional_block
editorPicker.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
}); } return TPromise.as(new QuickOpenModel(entries)); } public onClose(canceled: boolean): void { this.scorerCache = Object.create(null); } protected abstract getEditorEntries(): EditorPickerEntry[]; } export abstract class EditorGroupPicker extends BaseEditorPicker { protected getEditorEntries(): ...
{ e.setGroupLabel(nls.localize('groupLabel', "Group: {0}", e.group.label)); e.setShowBorder(!!lastGroup); lastGroup = e.group; }
conditional_block
editorPicker.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
constructor( private editor: EditorInput, private _group: IEditorGroup, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IModeService private modeService: IModeService, @IModelService private modelService: IModelService, @IEditorGroupService editorGroupService: IEditorGroupService ...
random_line_split
editorPicker.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(): EditorPickerEntry[] { const entries: EditorPickerEntry[] = []; const stacks = this.editorGroupService.getStacksModel(); stacks.groups.forEach((group, position) => { group.getEditors().forEach((editor, index) => { entries.push(this.instantiationService.createInstance(EditorPickerEntry, editor, group));...
getEditorEntries
identifier_name
comparator.rs
// rust way of ord use std::cmp::Ordering; pub trait Comparator<T> { fn compare(&self, v: &T, w: &T) -> Ordering; fn less(&self, v: &T, w: &T) -> bool { self.compare(v, w) == Ordering::Less } } impl<T, F> Comparator<T> for F where F: Send + Sync + Fn(&T, &T) -> Ordering { fn compare(&self, v...
{ use rand::{thread_rng, Rng}; fn is_reverse_sorted<T: PartialOrd>(a: &[T]) -> bool { for i in 1 .. a.len() { if a[i] > a[i-1] { return false; } } true } let mut array = thread_rng().gen_iter().take(10).collect::<Vec<u32>>(); // FIXME...
identifier_body
comparator.rs
// rust way of ord use std::cmp::Ordering; pub trait Comparator<T> { fn compare(&self, v: &T, w: &T) -> Ordering; fn less(&self, v: &T, w: &T) -> bool { self.compare(v, w) == Ordering::Less } } impl<T, F> Comparator<T> for F where F: Send + Sync + Fn(&T, &T) -> Ordering { fn compare(&self, v...
use rand::{thread_rng, Rng}; fn is_reverse_sorted<T: PartialOrd>(a: &[T]) -> bool { for i in 1 .. a.len() { if a[i] > a[i-1] { return false; } } true } let mut array = thread_rng().gen_iter().take(10).collect::<Vec<u32>>(); // FIXME: ...
#[test] fn test_insertion_sort_using_a_comparator() {
random_line_split
comparator.rs
// rust way of ord use std::cmp::Ordering; pub trait Comparator<T> { fn compare(&self, v: &T, w: &T) -> Ordering; fn less(&self, v: &T, w: &T) -> bool { self.compare(v, w) == Ordering::Less } } impl<T, F> Comparator<T> for F where F: Send + Sync + Fn(&T, &T) -> Ordering { fn compare(&self, v...
} true } let mut array = thread_rng().gen_iter().take(10).collect::<Vec<u32>>(); // FIXME: due to https://github.com/rust-lang/rust/issues/24680 // the Comparator closure's type can't be inferred! insertion_sort(&mut array, |v: &u32, w: &u32| w.cmp(v) ); assert!(is_reverse_sort...
{ return false; }
conditional_block
comparator.rs
// rust way of ord use std::cmp::Ordering; pub trait Comparator<T> { fn compare(&self, v: &T, w: &T) -> Ordering; fn less(&self, v: &T, w: &T) -> bool { self.compare(v, w) == Ordering::Less } } impl<T, F> Comparator<T> for F where F: Send + Sync + Fn(&T, &T) -> Ordering { fn compare(&self, v...
<T: PartialOrd, C: Comparator<T>>(a: &mut [T], comparator: C) { let n = a.len(); for i in 0 .. n { for j in (1 .. i + 1).rev() { if comparator.less(&a[j], &a[j-1]) { a.swap(j, j-1); } } } } #[test] fn test_insertion_sort_using_a_comparator() { us...
insertion_sort
identifier_name
flags.rs
mat!(match_flag_case, "(?i)abc", "ABC", Some((0, 3))); mat!(match_flag_weird_case, "(?i)a(?-i)bc", "Abc", Some((0, 3))); mat!(match_flag_weird_case_not, "(?i)a(?-i)bc", "ABC", None); mat!(match_flag_case_dotnl, "(?is)a.", "A\n", Some((0, 2))); mat!(match_flag_case_dotnl_toggle, "(?is)a.(?-is)a.", "A\nab", Some((0, 4)))...
mat!(match_flag_ungreedy, "(?U)a+", "aa", Some((0, 1))); mat!(match_flag_ungreedy_greedy, "(?U)a+?", "aa", Some((0, 2))); mat!(match_flag_ungreedy_noop, "(?U)(?-U)a+", "aa", Some((0, 2)));
mat!(match_flag_multi, "(?m)(?:^\\d+$\n?)+", "123\n456\n789", Some((0, 11)));
random_line_split
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, ExecutableDefinition, Program}; use graphql_sy...
.map_err(|errors| { errors .into_iter() .map(|error| format!("{:?}", error)) .collect::<Vec<_>>() .join("\n\n") }) }
{ let source_location = SourceLocationKey::standalone(fixture.file_name); let ast = parse_executable(fixture.content, source_location).unwrap(); let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap(); let program = Program::from_definitions(Arc::clone(&TEST_SCHEMA), ir); build(&TEST_SCHEMA, &ast.d...
identifier_body
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, ExecutableDefinition, Program}; use graphql_sy...
(fixture: &Fixture<'_>) -> Result<String, String> { let source_location = SourceLocationKey::standalone(fixture.file_name); let ast = parse_executable(fixture.content, source_location).unwrap(); let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap(); let program = Program::from_definitions(Arc::clone(&...
transform_fixture
identifier_name
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, ExecutableDefinition, Program}; use graphql_sy...
.join("\n\n\n\n") }) .map_err(|errors| { errors .into_iter() .map(|error| format!("{:?}", error)) .collect::<Vec<_>>() .join("\n\n") }) }
} }) .collect::<Vec<String>>()
random_line_split
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, ExecutableDefinition, Program}; use graphql_sy...
}) .collect::<Vec<String>>() .join("\n\n\n\n") }) .map_err(|errors| { errors .into_iter() .map(|error| format!("{:?}", error)) .collect::<Vec<_>>() .join("\n\n") }) }
{ None }
conditional_block
treeDnd.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
public update(event: Mouse.DragMouseEvent): void { // no-op } public getData(): any { return this.elements; } } export class DesktopDragAndDropData implements _.IDragAndDropData { private types: any[]; private files: any[]; constructor() { this.types = []; this.files = []; } public update(event: ...
private elements: any[]; constructor(elements: any[]) { this.elements = elements; }
random_line_split
treeDnd.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(event: Mouse.DragMouseEvent): void { // no-op } public getData(): any { return this.elements; } } export class DesktopDragAndDropData implements _.IDragAndDropData { private types: any[]; private files: any[]; constructor() { this.types = []; this.files = []; } public update(event: Mouse.DragMouse...
update
identifier_name
treeDnd.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
}
{ return { types: this.types, files: this.files }; }
identifier_body
treeDnd.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
if (event.dataTransfer.files) { this.files = []; Array.prototype.push.apply(this.files, event.dataTransfer.files); this.files = this.files.filter(f => f.size || f.type); } } public getData(): any { return { types: this.types, files: this.files }; } }
{ this.types = []; Array.prototype.push.apply(this.types, event.dataTransfer.types); }
conditional_block
AccuracyMeasure.py
#!/usr/bin/env python import csv, sys mapping = {} totalTruth, totalTesting, hit, miss, errors = (0, 0, 0, 0, 0) with open(sys.argv[1], 'rb') as groundtruth: reader = csv.reader(groundtruth) for row in reader:
with open(sys.argv[2], 'rb') as testing: reader = csv.reader(testing) for row in reader: totalTesting += 1 try: if (mapping[(row[1], row[2])] == row[0]): hit += 1 else: miss += 1 except KeyError: errors += 1 print "T...
totalTruth += 1 mapping[(row[1], row[2])] = row[0]
conditional_block
AccuracyMeasure.py
#!/usr/bin/env python import csv, sys mapping = {} totalTruth, totalTesting, hit, miss, errors = (0, 0, 0, 0, 0) with open(sys.argv[1], 'rb') as groundtruth: reader = csv.reader(groundtruth) for row in reader: totalTruth += 1 mapping[(row[1], row[2])] = row[0] with open(sys.argv[2], 'rb') ...
errors += 1 print "Total size: ", totalTruth, " and testing size: ", totalTesting print "Correct assignments: ", hit, " and failed assigments: ", miss print "Errors: ", errors print "Accuracy: ", float(hit) / float(totalTruth)
else: miss += 1 except KeyError:
random_line_split
event.js
win || window; return e || win.event; }, getWheel: function(e) { return e.wheelDelta? e.wheelDelta / 120 : -(e.detail || 0) / 3; }, getKey: function(e) { var code = e.which || e.keyCode; var key = keyOf(code); //onkeydown var fKey = code - 111; if (fKey > 0 && ...
this.pos = getPos(domElem); this.opt = this.callbacks = opt; this.size = { width: domElem.width || domElem.offsetWidth, height: domElem.height || domElem.offsetHeight }; this.attachEvents(); }; EventsProxy.prototype = { hovered: false, pressed: false, touched: false,...
this.scene = app.scene; this.domElem = domElem;
random_line_split
event.js
]; } var page = { x: e.pageX || (e.clientX + doc.scrollLeft), y: e.pageY || (e.clientY + doc.scrollTop) }; return page; }, stop: function(e) { if (e.stopPropagation) e.stopPropagation(); e.cancelBubble = true; if (e.preventDefault) e.preventDefault(); ...
{ return name; }
conditional_block
event.js
(n) { return n !== true ? n : false; } //Returns an element position var getPos = function(elem) { var bbox = elem.getBoundingClientRect(); return { x: bbox.left, y: bbox.top, bbox: bbox }; }; //event object wrapper var event = { get: function(e, win) { win = ...
toO3D
identifier_name
event.js
var page = { x: e.pageX || (e.clientX + doc.scrollLeft), y: e.pageY || (e.clientY + doc.scrollTop) }; return page; }, stop: function(e) { if (e.stopPropagation) e.stopPropagation(); e.cancelBubble = true; if (e.preventDefault) e.preventDefault(); else e.retur...
{ var keyMap = Events.Keys; for (var name in keyMap) { if (keyMap[name] == code) { return name; } } }
identifier_body
lib.rs
// Copyright 2015 juggle-tux // This file is part of srttool. // // srttool 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. // // sr...
; let mut content = String::with_capacity(128); while let Some(text) = self.buf.next() { self.line += 1; match text { Ok(text) => { if text == "" { break; } content = content + &t...
{ return Some(Err(ParseError::InvalidTimeString)); }
conditional_block
lib.rs
// Copyright 2015 juggle-tux // This file is part of srttool. // // srttool 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. // // sr...
} }
random_line_split
lib.rs
// Copyright 2015 juggle-tux // This file is part of srttool. // // srttool 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. // // sr...
(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}\n{}\n", self.start_end, self.content) } } /// a BlockReader pub struct BlockReader<B> { buf: Lines<B>, /// last line read line: u64, } impl<B> BlockReader<B> { /// returns the line number of the last line readed ...
fmt
identifier_name
lib.rs
// Copyright 2015 juggle-tux // This file is part of srttool. // // srttool 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. // // sr...
return Some(Err(ParseError::InvalidTimeString)); }; let mut content = String::with_capacity(128); while let Some(text) = self.buf.next() { self.line += 1; match text { Ok(text) => { if text == "" { b...
{ // idx if let Some(Ok(idx)) = self.buf.next() { self.line += 1; if idx == "" { return None; //File ends with final new line } else if !is_idx(&idx) { return Some(Err(ParseError::InvalidIndex)); } } else { ...
identifier_body
generateDIPFromAIPGenerateDIP.py
#!/usr/bin/env python2 # This file is part of Archivematica. # # Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com> # # Archivematica is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, ...
dst = os.path.join(unitPath, "DIP", os.path.basename(METSPath)) shutil.move(src, dst) # Move DIP src = os.path.join(unitPath, "DIP") dst = os.path.join("/var/archivematica/sharedDirectory/watchedDirectories/uploadDIP/", originalSIPName + "-" + originalSIPUUID) shutil.move(src, dst) try: ...
logger = get_script_logger("archivematica.mcp.client.generateDIPFromAIPGenerateDIP") # COPY THE METS FILE # Move the DIP Directory fauxUUID = sys.argv[1] unitPath = sys.argv[2] date = sys.argv[3] basename = os.path.basename(unitPath[:-1]) uuidLen = 36 originalSIPName = basename[:-(uui...
conditional_block
generateDIPFromAIPGenerateDIP.py
#!/usr/bin/env python2
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com> # # Archivematica is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later...
# This file is part of Archivematica. #
random_line_split
ik_solver.py
import argparse import sys import rospy from geometry_msgs.msg import ( PoseStamped, Pose, Point, Quaternion, ) from std_msgs.msg import Header from baxter_core_msgs.srv import ( SolvePositionIK, SolvePositionIKRequest, ) def ik_solve(limb, pos, orient): #~ rospy.init_node("rsdk_ik_serv...
if (resp.isValid[0]): print("SUCCESS - Valid Joint Solution Found:") # Format solution into Limb API-compatible dictionary limb_joints = dict(zip(resp.joints[0].name, resp.joints[0].position)) print limb_joints return limb_joints else: print("INVALID POSE - No Val...
rospy.logerr("Service call failed: %s" % (e,)) return 1
random_line_split
ik_solver.py
import argparse import sys import rospy from geometry_msgs.msg import ( PoseStamped, Pose, Point, Quaternion, ) from std_msgs.msg import Header from baxter_core_msgs.srv import ( SolvePositionIK, SolvePositionIKRequest, ) def ik_solve(limb, pos, orient): #~ rospy.init_node("rsdk_ik_serv...
limb_joints = dict(zip(resp.joints[0].name, resp.joints[0].position)) print limb_joints return limb_joints else: print("INVALID POSE - No Valid Joint Solution Found.") return -1
ns = "ExternalTools/" + limb + "/PositionKinematicsNode/IKService" iksvc = rospy.ServiceProxy(ns, SolvePositionIK) ikreq = SolvePositionIKRequest() print "iksvc: ", iksvc print "ikreq: ", ikreq hdr = Header(stamp=rospy.Time.now(), frame_id='base') poses = { str(limb): PoseStamped(header=...
identifier_body
ik_solver.py
import argparse import sys import rospy from geometry_msgs.msg import ( PoseStamped, Pose, Point, Quaternion, ) from std_msgs.msg import Header from baxter_core_msgs.srv import ( SolvePositionIK, SolvePositionIKRequest, ) def ik_solve(limb, pos, orient): #~ rospy.init_node("rsdk_ik_serv...
return -1
print("INVALID POSE - No Valid Joint Solution Found.")
conditional_block
ik_solver.py
import argparse import sys import rospy from geometry_msgs.msg import ( PoseStamped, Pose, Point, Quaternion, ) from std_msgs.msg import Header from baxter_core_msgs.srv import ( SolvePositionIK, SolvePositionIKRequest, ) def
(limb, pos, orient): #~ rospy.init_node("rsdk_ik_service_client") ns = "ExternalTools/" + limb + "/PositionKinematicsNode/IKService" iksvc = rospy.ServiceProxy(ns, SolvePositionIK) ikreq = SolvePositionIKRequest() print "iksvc: ", iksvc print "ikreq: ", ikreq hdr = Header(stamp=rospy.Time.no...
ik_solve
identifier_name
mock.ts
import { Collection, Snowflake } from "discord.js"; import { handleMessage } from "../src/message-handler"; import { Message, Channel, TextChannel, DMChannel, User, Guild, GuildMember, Role } from "../src/discord-mock"; import { roleNames } from "../src/permissions"; class MockUser implements User { bot: false; id:...
teahouse.reset(); battlefield.reset(); admin.dmChannel.reset(); storyteller.dmChannel.reset(); player.dmChannel.reset(); }
]) }; export function reset() {
random_line_split
mock.ts
import { Collection, Snowflake } from "discord.js"; import { handleMessage } from "../src/message-handler"; import { Message, Channel, TextChannel, DMChannel, User, Guild, GuildMember, Role } from "../src/discord-mock"; import { roleNames } from "../src/permissions"; class MockUser implements User { bot: false; id:...
{ teahouse.reset(); battlefield.reset(); admin.dmChannel.reset(); storyteller.dmChannel.reset(); player.dmChannel.reset(); }
identifier_body
mock.ts
import { Collection, Snowflake } from "discord.js"; import { handleMessage } from "../src/message-handler"; import { Message, Channel, TextChannel, DMChannel, User, Guild, GuildMember, Role } from "../src/discord-mock"; import { roleNames } from "../src/permissions"; class MockUser implements User { bot: false; id:...
(user: User) { this.id = user.id + "_dm"; this.type = "dm"; } async send(content: string) { this.responses.push(content); } reset() { this.responses = []; } } export const teahouse = new MockTextChannel("public1", "Teahouse"); export const battlefield = new MockTextChannel("public2", "Battlefield"); ex...
constructor
identifier_name
fixsessions.server.controller.js
'use strict'; /** * Module dependencies. */ var errorHandler = require('./errors.server.controller'), db = require('../models/fixsession.server.model'), _ = require('lodash'), bluebird = require('bluebird'); /** * Create a Fixsession */ exports.create = function(req, res) { db.FixSession.create(...
username: req.body.username, password: req.body.password, defaultRoute: req.body.defaultRoute, assignedOOBProcessor: req.body.assignedOOBProcessor }).complete(function(err, results){ res.sendStatus(201); }); }; /** * List of Fixsessions */ exports.list = function(req, res) { db.FixSessio...
assignedFixManager: req.body.assignedFixManager, assignedTcpManager: req.body.assignedTcpManager, initiator : req.body.initiator, host: req.body.host, port: req.body.port,
random_line_split