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
kepmsg.py
#!/usr/bin/env python import sys, time, string # ----------------------------------------------------------- # write message to log file and shell def log(file,message,verbose): if (verbose): # print to shell print (message) # print to log file if (file): output = open(file,'a') output.write(mes...
(message,file,verbose): clock('Abort time is: ',file,verbose) if verbose: log(file,message,True) else: print message sys.exit(2) # ----------------------------------------------------------- # write error message to shell and exit def exit(message): sys.exit(message) # -----...
abort
identifier_name
kepmsg.py
#!/usr/bin/env python import sys, time, string # ----------------------------------------------------------- # write message to log file and shell def log(file,message,verbose): if (verbose): # print to shell print (message) # print to log file if (file): output = open(file,'a') output.write(mes...
# ----------------------------------------------------------- # test the logfile name is good def test(file): newlog = string.join(file.split(),"") if (len(newlog) == 0): newlog = 'kepler.log' if (newlog != file): file = newlog message = 'WARNING: logfile renamed to '+file+'\n\n' log(False,message,Tr...
if (file and verbose): output = open(file,'a') output.write(message+'\n') output.close()
identifier_body
echo.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
use hyper::{server, Decoder, Encoder, Next}; use hyper::net::HttpStream; use super::ContentHandler; #[derive(Default)] pub struct EchoHandler { content: String, handler: Option<ContentHandler>, } impl server::Handler<HttpStream> for EchoHandler { fn on_request(&mut self, _: server::Request<HttpStream>) -> Next { ...
//! Echo Handler use std::io::Read;
random_line_split
echo.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(&mut self, _: server::Request<HttpStream>) -> Next { Next::read() } fn on_request_readable(&mut self, decoder: &mut Decoder<HttpStream>) -> Next { match decoder.read_to_string(&mut self.content) { Ok(0) => { self.handler = Some(ContentHandler::ok(self.content.clone(), mime!(Application/Json))); Next:...
on_request
identifier_name
problem20.rs
extern crate num; use num::bigint::BigUint; fn to_biguint(num_str: &str) -> BigUint { return num_str.parse::<BigUint>().unwrap(); } fn factorial(num: BigUint) -> BigUint { if num == to_biguint("1")
let num2 = num.clone(); // TODO: avoid this ugly line return num * factorial(num2 - to_biguint("1")); } fn sum_of_digits(num: BigUint) -> u64 { let mut sum = 0u64; for ch in num.to_string().chars() { sum += ch.to_digit(10).unwrap() as u64; } return sum } pub fn main() { let answer...
{ return to_biguint("1") }
conditional_block
problem20.rs
extern crate num; use num::bigint::BigUint; fn to_biguint(num_str: &str) -> BigUint { return num_str.parse::<BigUint>().unwrap(); } fn factorial(num: BigUint) -> BigUint { if num == to_biguint("1") { return to_biguint("1") } let num2 = num.clone(); // TODO: avoid this ugly line return num...
}
{ assert_eq!(factorial(to_biguint("10")), to_biguint("3628800")); assert_eq!(sum_of_digits(factorial(to_biguint("10"))), 27); }
identifier_body
problem20.rs
extern crate num; use num::bigint::BigUint; fn to_biguint(num_str: &str) -> BigUint { return num_str.parse::<BigUint>().unwrap(); }
fn factorial(num: BigUint) -> BigUint { if num == to_biguint("1") { return to_biguint("1") } let num2 = num.clone(); // TODO: avoid this ugly line return num * factorial(num2 - to_biguint("1")); } fn sum_of_digits(num: BigUint) -> u64 { let mut sum = 0u64; for ch in num.to_string().char...
random_line_split
problem20.rs
extern crate num; use num::bigint::BigUint; fn to_biguint(num_str: &str) -> BigUint { return num_str.parse::<BigUint>().unwrap(); } fn factorial(num: BigUint) -> BigUint { if num == to_biguint("1") { return to_biguint("1") } let num2 = num.clone(); // TODO: avoid this ugly line return num...
(num: BigUint) -> u64 { let mut sum = 0u64; for ch in num.to_string().chars() { sum += ch.to_digit(10).unwrap() as u64; } return sum } pub fn main() { let answer = sum_of_digits(factorial(to_biguint("100"))); println!("answer = {}", answer); } #[cfg(test)] mod test { use super::{f...
sum_of_digits
identifier_name
erase.js
/* GCompris - erase.js * * Copyright (C) 2014 Bruno Coudoin * * Authors: * Bruno Coudoin <bruno.coudoin@gcompris.net> (GTK+ version) * Bruno Coudoin <bruno.coudoin@gcompris.net> (Qt Quick port) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Gene...
function nextSubLevel() { if( ++items.currentSubLevel >= items.nbSubLevel) { items.currentSubLevel = 0 nextLevel() } initLevel(); } function previousLevel() { if(--currentLevel < 0) { currentLevel = nbLevel - 1 } items.currentSubLevel = 0; initLevel(); } function ...
{ if( ++currentLevel >= nbLevel ) { currentLevel = 0 } items.currentSubLevel = 0; initLevel(); }
identifier_body
erase.js
/* GCompris - erase.js * * Copyright (C) 2014 Bruno Coudoin * * Authors: * Bruno Coudoin <bruno.coudoin@gcompris.net> (GTK+ version) * Bruno Coudoin <bruno.coudoin@gcompris.net> (Qt Quick port) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Gene...
() { } var nbx = (currentLevel % 2 * 3) + 5; var nby = (currentLevel % 2 * 3) + 5; function initLevel() { items.blocks.clear() imgIndex++ items.bar.level = currentLevel + 1 items.background.source = url + backgroundImages[currentImage++] if(currentImage >= backgroundImages.length) { currentI...
stop
identifier_name
erase.js
/* GCompris - erase.js * * Copyright (C) 2014 Bruno Coudoin * * Authors: * Bruno Coudoin <bruno.coudoin@gcompris.net> (GTK+ version) * Bruno Coudoin <bruno.coudoin@gcompris.net> (Qt Quick port) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Gene...
"maki3.jpg", "maki4.jpg", "maki5.jpg", "maki6.jpg", "malaybear002.jpg", "papilio_demodocus.jpg", "polabear011.jpg", "polarbear001.jpg", "poolbears001.jpg", "Pteroglossus-torquatus-001.jpg", "rhinogc.jpg", "sheep_irish2.jpg", "sheep_irish.jpg", "singegc.jpg", "...
"maki1.jpg", "maki2.jpg",
random_line_split
erase.js
/* GCompris - erase.js * * Copyright (C) 2014 Bruno Coudoin * * Authors: * Bruno Coudoin <bruno.coudoin@gcompris.net> (GTK+ version) * Bruno Coudoin <bruno.coudoin@gcompris.net> (Qt Quick port) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Gene...
initLevel(); } function previousLevel() { if(--currentLevel < 0) { currentLevel = nbLevel - 1 } items.currentSubLevel = 0; initLevel(); } function blockKilled() { if(++killedBlocks === createdBlocks) { items.bonus.good("flower") } } function getFirstImage() { backgrou...
{ items.currentSubLevel = 0 nextLevel() }
conditional_block
scroll-1467920963555.js
(function(window, undefined) { /*********************** START STATIC ACCESS METHODS ************************/ jQuery.extend(jimMobile, { "loadScrollBars": function() { jQuery(".s-724d6129-a5ed-4b21-a1a7-3ef200a06710 .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); ...
jQuery(".s-8a638ee1-d936-47c6-b4d7-1fa17ca84294 .ui-page").overscroll({ showThumbs:true, direction:'multi' }); jQuery(".s-95adc887-3e85-4566-95d6-d7b6077c8c85 .ui-page").overscroll({ showThumbs:true, direction:'multi' }); jQuery(".s-7198b126-8045-4499-9acf-878838131f88 .ui-page").ove...
jQuery(".s-ed74f470-4343-4380-a864-f8dbad599122 .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); jQuery(".s-a55013df-bea6-4693-86cc-1c4c6e922cbe .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); jQuery(".s-825d8d4d-d97b-4a27-8c53-9894f5e6cd0b .ui-page...
random_line_split
issue.js
'https://git.popcorntime.io/popcorntime/desktop/issues/', //Url of 'issues' of the above project token; var Issue = Backbone.Marionette.ItemView.extend({ template: '#issue-tpl', className: 'issue', ui: { success_alert: '.success_alert' }, events: { ...
}); Mousetrap.bind(['esc', 'backspace'], function (e) { App.vent.trigger('issue:close'); }); Mousetrap(document.getElementById('issue-pw')).bind(['enter'], function (e, combo) { $('.login-issue').click(); }); Mouse...
{ $('#issue-length').show().text('(' + userInput + '/200)'); }
conditional_block
issue.js
var Issue = Backbone.Marionette.ItemView.extend({ template: '#issue-tpl', className: 'issue', ui: { success_alert: '.success_alert' }, events: { 'click .close-icon': 'closeIssue', 'click .submit-issue': 'submitIssue', 'click ...
PT_url = 'https://git.popcorntime.io/popcorntime/desktop/issues/', //Url of 'issues' of the above project token;
random_line_split
ext-foreignobject.js
/* * ext-foreignobject.js * * Licensed under the Apache License, Version 2 * * Copyright(c) 2010 Jacques Distler * Copyright(c) 2010 Alexis Deveria * */ methodDraw.addExtension("foreignObject", function(S) { var svgcontent = S.svgcontent, addElem = S.addSvgElementFromJson, selElems, svgns = "http:...
function toggleSourceButtons(on) { $('#tool_source_save, #tool_source_cancel').toggle(!on); $('#foreign_save, #foreign_cancel').toggle(on); } // Function: setForeignString(xmlString, elt) // This function sets the content of element elt to the input XML. // // Parameters: // xmlString - The...
{ var fc_rules = $('#fc_rules'); if(!fc_rules.length) { fc_rules = $('<style id="fc_rules"><\/style>').appendTo('head'); } fc_rules.text(!on?"":" #tool_topath { display: none !important; }"); $('#foreignObject_panel').toggle(on); }
identifier_body
ext-foreignobject.js
/* * ext-foreignobject.js * * Licensed under the Apache License, Version 2 * * Copyright(c) 2010 Jacques Distler * Copyright(c) 2010 Alexis Deveria * */ methodDraw.addExtension("foreignObject", function(S) { var svgcontent = S.svgcontent, addElem = S.addSvgElementFromJson, selElems, svgns = "http:...
(xmlString) { var elt = selElems[0]; try { // convert string into XML document var newDoc = Utils.text2xml('<svg xmlns="'+svgns+'" xmlns:xlink="'+xlinkns+'">'+xmlString+'</svg>'); // run it through our sanitizer to remove anything we do not support S.sanitizeSvg(newDoc.documentElement); elt.pa...
setForeignString
identifier_name
ext-foreignobject.js
/* * ext-foreignobject.js * * Licensed under the Apache License, Version 2 * * Copyright(c) 2010 Jacques Distler * Copyright(c) 2010 Alexis Deveria * */ methodDraw.addExtension("foreignObject", function(S) { var svgcontent = S.svgcontent, addElem = S.addSvgElementFromJson, selElems, svgns = "http:...
},{ id: "edit_foreign", type: "context", panel: "foreignObject_panel", title: "Edit ForeignObject Content", events: { 'click': function() { showForeignEditor(); } } }], context_tools: [{ type: "input", panel: "foreignObject_panel", title: "Change foreignO...
} }
random_line_split
index.ts
/** * @license * Copyright Google LLC 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 */ import {Component, NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {p...
(event: HammerInput): void { this.rotateAngle = event.rotation; } } @NgModule({declarations: [GesturesCmp], bootstrap: [GesturesCmp], imports: [BrowserModule]}) class ExampleModule { } platformBrowserDynamic().bootstrapModule(ExampleModule);
onRotate
identifier_name
index.ts
/** * @license * Copyright Google LLC 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 */ import {Component, NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {p...
} } @NgModule({declarations: [GesturesCmp], bootstrap: [GesturesCmp], imports: [BrowserModule]}) class ExampleModule { } platformBrowserDynamic().bootstrapModule(ExampleModule);
onRotate(event: HammerInput): void { this.rotateAngle = event.rotation;
random_line_split
main.js
() { //set locations var location = new google.maps.LatLng(39.90658,-105.09859); var stylesArray = [ { "stylers": [ { "saturation": -100 } ] },{ "featureType": "road", "elementType": "geometry", "stylers": [ { "visibility": "simplified" } ] },{ ...
showMap
identifier_name
main.js
": "geometry", "stylers": [ { "visibility": "simplified" } ] },{ "elementType": "labels.text.stroke", "stylers": [ { "visibility": "off" } ] },{ "elementType": "labels.text.fill", "stylers": [ { "lightness": 3 } ] },{ "featureType...
//update url + title var href = $that.attr('href') History.pushState(null, title, href) //load post if($that.parent().hasClass('beer')) { loadPost(href) //scroll to section } else { $('#beer').fadeOut(400, function() { $('body').removeClass('beer') }).empty()...
{ title = $that.text() + title }
conditional_block
main.js
elementType": "geometry", "stylers": [ { "visibility": "simplified" } ] },{ "elementType": "labels.text.stroke", "stylers": [ { "visibility": "off" } ] },{ "elementType": "labels.text.fill", "stylers": [ { "lightness": 3 } ] },{ "...
slidesToShow: 2, slidesToScroll: 1 } }, { breakpoint: 480, settings: { slidesToShow: 1, slidesToScroll: 1, arrows: false, dots: true } } ] }) //truck hover text // $('.truck').on('hover', function ()...
random_line_split
main.js
": "geometry", "stylers": [ { "visibility": "simplified" } ] },{ "elementType": "labels.text.stroke", "stylers": [ { "visibility": "off" } ] },{ "elementType": "labels.text.fill", "stylers": [ { "lightness": 3 } ] },{ "featureType...
loadPost(href) //scroll to section } else { $('#beer').fadeOut(400, function() { $('body').removeClass('beer') }).empty() $('html, body').stop().animate({ scrollTop: ($('#' + href.replace('/', '')).offset().top-88) }, 2000,'easeInOutExpo') } } })(); //on pa...
{ ev.preventDefault() var $that = $(this) var separator = ' | ' var title = $(document).find('title').text() title = title.substring(title.indexOf(separator), title.length) //set title if($('h3', this).length) { title = $('h3', this).text() + title } else { title = $that...
identifier_body
strutral_controllability.py
""" structral controllability measure, driver nodes """ # Copyright (C) 2014 by # Xin-Feng Li <silfer.lee@gmail.com> # All rights reserved # BSD license import networkx as nx import matplotlib.pyplot as plt __author__ = """Xin-Feng Li (silfer.lee@gmail.com)""" def get_driver_nodes(DG): '''Return the dri...
def controllability(G): return len(control_nodes(G))/float(len(G)) # test this function if __name__ == "__main__": DG = nx.DiGraph() DG_edges = [(0,2), (0,3), (0,4), (0,5), (1,4), (1,5)] DG.add_edges_from(DG_edges) #n, nodes = get_driver_nodes(DG) nodes = control_nodes(DG) n = len(node...
H = to_bipartite(G) M = nx.max_weight_matching(H,True) matched = set(v for (v,sign) in M.values() if sign == '-') | \ set(u for (u,sign) in M.keys() if sign == '-') n_D = set(G) - matched if len(n_D) == 0: return [G.nodes_iter().next()] else: return list(n_D)
identifier_body
strutral_controllability.py
""" structral controllability measure, driver nodes """ # Copyright (C) 2014 by # Xin-Feng Li <silfer.lee@gmail.com> # All rights reserved # BSD license import networkx as nx import matplotlib.pyplot as plt
def get_driver_nodes(DG): '''Return the driver nodes number and driver nodes from a DiGraph DG Basic Idea: Given a graph DG, create a new undirected bipartite graph, BG suppose DG has n nodes, the the BG has 2*n nodes, the first n nodes [0, n) form the left parts of BG, the [n, 2*n) nodes form the ...
__author__ = """Xin-Feng Li (silfer.lee@gmail.com)"""
random_line_split
strutral_controllability.py
""" structral controllability measure, driver nodes """ # Copyright (C) 2014 by # Xin-Feng Li <silfer.lee@gmail.com> # All rights reserved # BSD license import networkx as nx import matplotlib.pyplot as plt __author__ = """Xin-Feng Li (silfer.lee@gmail.com)""" def get_driver_nodes(DG): '''Return the dri...
else: H = nx.Graph() for n in G: H.add_node((n,'+')) H.add_node((n,'-')) for (u,v) in G.edges_iter(): H.add_edge((u,'+'),(v,'-')) return H def control_nodes(G): H = to_bipartite(G) M = nx.max_weight_matching(H,True) matched = set(v for (v,sign) in M.values(...
H = nx.MultiGraph()
conditional_block
strutral_controllability.py
""" structral controllability measure, driver nodes """ # Copyright (C) 2014 by # Xin-Feng Li <silfer.lee@gmail.com> # All rights reserved # BSD license import networkx as nx import matplotlib.pyplot as plt __author__ = """Xin-Feng Li (silfer.lee@gmail.com)""" def get_driver_nodes(DG): '''Return the dri...
(G): H = to_bipartite(G) M = nx.max_weight_matching(H,True) matched = set(v for (v,sign) in M.values() if sign == '-') | \ set(u for (u,sign) in M.keys() if sign == '-') n_D = set(G) - matched if len(n_D) == 0: return [G.nodes_iter().next()] else: return list(n_D) ...
control_nodes
identifier_name
index-test.ts
import Container from "@extension-kid/core/dist/src/Container"; const mockRequest = jest.fn(); jest.mock("@dcos/http-service", () => ({ request: mockRequest, })); import DataLayer, { DataLayerType } from "@extension-kid/data-layer/dataLayer"; import dataLayerContainerModuleFactory from "@extension-kid/data-layer"; ...
describe("Cosmos data-layer", () => { let container: Container | null = null; let dl: DataLayer | null = null; beforeEach(() => { jest.clearAllMocks(); container = createTestContainer(); dl = container.get<DataLayer>(DataLayerType); }); afterEach(() => { dl = null; container = null; }...
{ const container = new Container(); container.load(dataLayerContainerModuleFactory()); const uiUpdateModule = extensionFactory(); if (uiUpdateModule) { container.load(uiUpdateModule); } else { throw new Error("Failed to get ui data-layer extension module"); } return container; }
identifier_body
index-test.ts
import Container from "@extension-kid/core/dist/src/Container"; const mockRequest = jest.fn(); jest.mock("@dcos/http-service", () => ({ request: mockRequest, })); import DataLayer, { DataLayerType } from "@extension-kid/data-layer/dataLayer"; import dataLayerContainerModuleFactory from "@extension-kid/data-layer"; ...
() { const container = new Container(); container.load(dataLayerContainerModuleFactory()); const uiUpdateModule = extensionFactory(); if (uiUpdateModule) { container.load(uiUpdateModule); } else { throw new Error("Failed to get ui data-layer extension module"); } return container; } describe("Cos...
createTestContainer
identifier_name
index-test.ts
import Container from "@extension-kid/core/dist/src/Container"; const mockRequest = jest.fn(); jest.mock("@dcos/http-service", () => ({ request: mockRequest, })); import DataLayer, { DataLayerType } from "@extension-kid/data-layer/dataLayer"; import dataLayerContainerModuleFactory from "@extension-kid/data-layer"; ...
throw new Error(); } const queryResult$ = dl.query(query, { packageName: "dcos-ui", }); const result$ = queryResult$.pipe(take(1)); const expected$ = m.cold("------#", undefined, { message: "Internal Server Error", name: "Error", ...
if (dl === null) {
random_line_split
index-test.ts
import Container from "@extension-kid/core/dist/src/Container"; const mockRequest = jest.fn(); jest.mock("@dcos/http-service", () => ({ request: mockRequest, })); import DataLayer, { DataLayerType } from "@extension-kid/data-layer/dataLayer"; import dataLayerContainerModuleFactory from "@extension-kid/data-layer"; ...
const queryResult$ = dl.query(query, { packageName: "dcos-ui", }); const result$ = queryResult$.pipe(take(1)); const expected$ = m.cold("--(j|)", { j: { data: { package: { name: "dcos-ui", versions: [ ...
{ throw new Error(); }
conditional_block
post_listfield_item_listfield.py
import unittest import json from datetime import datetime from pymongo import MongoClient from apps.basic_resource import server from apps.basic_resource.documents import Article, Comment, Vote class ResourcePostListFieldItemListField(unittest.TestCase): """ Test if a HTTP POST that adds entries to a listfiel...
def test_content_type(self): """ Test if the content-type header is 'application/json'. """ self.assertEqual( self.response.headers['content-type'], 'application/json' ) def test_json(self): """ Test if the response data is valid...
""" Test if the response status code is 201. """ self.assertEqual(self.response.status_code, 201)
identifier_body
post_listfield_item_listfield.py
import unittest import json from datetime import datetime from pymongo import MongoClient from apps.basic_resource import server from apps.basic_resource.documents import Article, Comment, Vote class ResourcePostListFieldItemListField(unittest.TestCase): """ Test if a HTTP POST that adds entries to a listfiel...
upvotes=[ Vote( ip_address="1.4.1.2", date=datetime(2012, 5, 2, 9, 1, 3), name="Jzorz" ), Vote( ip_address="2.4.5.2"...
Comment( id=comment_id, text="Test comment old", email="test@example.com",
random_line_split
post_listfield_item_listfield.py
import unittest import json from datetime import datetime from pymongo import MongoClient from apps.basic_resource import server from apps.basic_resource.documents import Article, Comment, Vote class ResourcePostListFieldItemListField(unittest.TestCase): """ Test if a HTTP POST that adds entries to a listfiel...
(cls): cls.mongo_client.unittest_monkful.article.remove() def test_status_code(self): """ Test if the response status code is 201. """ self.assertEqual(self.response.status_code, 201) def test_content_type(self): """ Test if the content-type header is 'a...
tearDownClass
identifier_name
meetapiservice.js
MeetApiService.$inject = ['$q','$http']; function MeetApiService($q, $http) { var AppSettings = {}; AppSettings.defaultApiVersion = 'v1'; AppSettings.apiUrl = '/_ah/api'; AppSettings.projectName = 'movieranking';
version = version || AppSettings.defaultApiVersion; endpoint = endpoint.replace('.', '/'); return [ AppSettings.apiUrl, AppSettings.projectName, version, endpoint ].join('/'); }; service.get = function(endpoint, args, version) { var deferred = $q.defer(); $http...
var service = {}; var createEndpointUrl = function(endpoint, version) {
random_line_split
meetapiservice.js
MeetApiService.$inject = ['$q','$http']; function
($q, $http) { var AppSettings = {}; AppSettings.defaultApiVersion = 'v1'; AppSettings.apiUrl = '/_ah/api'; AppSettings.projectName = 'movieranking'; var service = {}; var createEndpointUrl = function(endpoint, version) { version = version || AppSettings.defaultApiVersion; endpoin...
MeetApiService
identifier_name
meetapiservice.js
MeetApiService.$inject = ['$q','$http']; function MeetApiService($q, $http)
var deferred = $q.defer(); $http({url: createEndpointUrl(endpoint, version), method: "GET", params: args}).success(function(data) { deferred.resolve(data); }).error(function(err, status) { deferred.reject(err, status); }); return deferred.promise; }; service.post = ...
{ var AppSettings = {}; AppSettings.defaultApiVersion = 'v1'; AppSettings.apiUrl = '/_ah/api'; AppSettings.projectName = 'movieranking'; var service = {}; var createEndpointUrl = function(endpoint, version) { version = version || AppSettings.defaultApiVersion; endpoint = endpoint...
identifier_body
constants.ts
interface RegexConstants { ibizan: RegExp; modes: RegExp; days: RegExp; rel_time: RegExp; time: RegExp; months: RegExp; date: RegExp; numdate: RegExp; } export const REGEX: RegexConstants = { ibizan: /^(?:@)?ibizan(?::)? ?/i, modes: /\b(in|out|vacation|sick|unpaid)\b/i, days:...
export const REGEX_STR = Object.keys(REGEX) .reduce((acc, key) => ({ ...acc, [key]: REGEX[key].toString().substring(1, REGEX[key].toString().indexOf('/i')) }), {} as { [key in keyof RegexConstants]: string; }); export const MODES = ['in', 'out', 'vacation', '...
date: /(\b(?:Jan(?:uary)?|Mar(?:ch)?|May|Jul(?:y)?|Aug(?:ust)?|Oct(?:ober)?|Dec(?:ember)?) (?:3[01]|[0-2]*[0-9])(?: ?- ?(3[01]|[0-2]*[0-9]))?\b)|(\b(?:Sep(?:tember)?|Apr(?:il)?|Jun(?:e)?|Nov(?:ember)?) (?:30|[0-2]*[0-9])(?: ?- ?(30|[0-2]*[0-9]))?\b)|(\b(?:Feb(?:ruary)?) (?:29|[0-2]*[0-8])(?: ?- ?(29|[0-2]*[0-8]))?\...
random_line_split
output.rs
use std::io; use std::io::{BufRead, BufReader, Write, Seek}; use std::io::SeekFrom::{Start, Current}; use std::fs::File; use std::path::Path; use self::PadSide::*; use self::Content::*; use definitions::Definition; use interpreter::extract_line; #[derive(PartialEq)] pub enum PadSide { Left, Right } #[derive(P...
t_eq!(" pâté", "pâté".pad(' ', 8, Left, Chars)) } }
_wide_l() { asser
identifier_name
output.rs
use std::io; use std::io::{BufRead, BufReader, Write, Seek}; use std::io::SeekFrom::{Start, Current}; use std::fs::File; use std::path::Path; use self::PadSide::*; use self::Content::*; use definitions::Definition; use interpreter::extract_line; #[derive(PartialEq)] pub enum PadSide { Left, Right } #[derive(P...
t] fn char_padding_wide_r() { assert_eq!("pâté ", "pâté".pad(' ', 8, Right, Chars)) } #[test] fn char_padding_wide_l() { assert_eq!(" pâté", "pâté".pad(' ', 8, Left, Chars)) } }
assert_eq!(" pâté", "pâté".pad(' ', 8, Left, Bytes)) } #[tes
identifier_body
output.rs
use std::io; use std::io::{BufRead, BufReader, Write, Seek}; use std::io::SeekFrom::{Start, Current}; use std::fs::File; use std::path::Path; use self::PadSide::*; use self::Content::*; use definitions::Definition; use interpreter::extract_line; #[derive(PartialEq)] pub enum PadSide { Left, Right } #[derive(P...
pub fn display_extract(input_file_name: &str, definition: &Definition) -> io::Result<()> { let input_file = try!(File::open(Path::new(input_file_name))); let max_name_len = definition.fields.iter().map(|field| field.len()).max().unwrap(); let max_value_len = definition.lengths.iter().max().unwrap(); let mut index...
if side == Left { padded_str.push_str(self) } padded_str } }
random_line_split
worker.js
var AWS = require('aws-sdk'); var Policy = require("./s3post").Policy; var helpers = require("./helpers"); var POLICY_FILE = "policy.json"; var schedule = require('node-schedule'); var Worker = function(sqsCommnad, s3Object, simpleData){ var queue = sqsCommnad; var s3 = s3Object; var simpleDataAuth = simpleData;...
console.log({Body : data.Body, MD5OfBody : data.MD5OfBody}); params = { Bucket: bucket_name, Key: data.Body } s3.getObject(params, function(err, data) { if (err) { console.log(err, err.stack); } else { var request = require('request'); ...
{ console.log(err); return; }
conditional_block
worker.js
var AWS = require('aws-sdk'); var Policy = require("./s3post").Policy; var helpers = require("./helpers"); var POLICY_FILE = "policy.json"; var schedule = require('node-schedule'); var Worker = function(sqsCommnad, s3Object, simpleData){ var queue = sqsCommnad; var s3 = s3Object; var simpleDataAuth = simpleData;...
var gm = require('gm').subClass({ imageMagick: true }); var src = 'http://s3-us-west-2.amazonaws.com/'+params.Bucket+'/'+params.Key; gm(request(src, params.Key)) .rotate('black', 15) .stream(function(err, stdout, stderr) { var buf...
var mime = require('mime');
random_line_split
ia64-linux.py
cwd", ""], 1185 : [ "capget", ""], 1186 : [ "capset", ""], 1187 : [ "sendfile", ""], 1188 : [ "getpmsg", ""], 1189 : [ "putpmsg", ""], 1190 : [ "socket", "ddd:d"], 1191 : [ "bind", ""], 1192 : [ "connect", ""], 1193 : [ "listen", ""], 1194 : [ "accept", ...
break_instruction
identifier_name
ia64-linux.py
"d:v"], 1026 : [ "read", "dxd:d"], 1027 : [ "write", (["d", format_stringbuf, "d"], "d")], 1028 : [ "open", "sd:d"], 1029 : [ "close", "d:d"], 1030 : [ "creat", "sd:d"], 1031 : [ "link", "ss:d"], 1032 : [ "unlink", "s:d"], 1033 : [ "execve", "sxx:v"], 1034 : ...
1143 : [ "setfsgid", ""], 1144 : [ "getdents", ""], 1145 : [ "flock", ""], 1146 : [ "readv", ""], 1147 : [ "writev", ""], 1148 : [ "pread", ""], 114
1140 : [ "personality", ""], 1141 : [ "afs_syscall", ""], 1142 : [ "setfsuid", ""],
random_line_split
ia64-linux.py
except: s += " status: <not in tlb>" return s except: traceback.print_exc() def fmt_uname_ret(ignored_regno): try: cpu = SIM_current_processor() lutsp = SIM_read_register(cpu, r0 + 32) s = "%d" % SIM_read_register(cpu, r0 + 8) try:...
s += " signal(%d)" % (status & 0xf7)
conditional_block
ia64-linux.py
linux_syscalls = { 1024 : [ "ni_syscall", ""], 1025 : [ "exit", "d:v"], 1026 : [ "read", "dxd:d"], 1027 : [ "write", (["d", format_stringbuf, "d"], "d")], 1028 : [ "open", "sd:d"], 1029 : [ "close", "d:d"], 1030 : [ "creat", "sd:d"], 1031 : [ "link", "ss:d"...
cpu = SIM_current_processor() swapflags = SIM_read_register(cpu, regno) s = "%d" % (swapflags & 0x7fff) if swapflags & 0x8000: s += "|PREFER" return s
identifier_body
alerts.tsx
import * as React from "react"; import { sortBy, isNumber } from "lodash"; import { ProblemTag, FirmwareAlertsProps, AlertsProps } from "./interfaces"; import { AlertCard } from "./cards"; import { Alert } from "farmbot"; export const splitProblemTag = (problemTag: string): ProblemTag => { const parts = problemTag.s...
alert={x} dispatch={props.dispatch} apiFirmwareValue={props.apiFirmwareValue} timeSettings={props.timeSettings} findApiAlertById={props.findApiAlertById} />)} </div> </div>;
.map(x => <AlertCard key={x.slug + x.created_at}
random_line_split
pt.js
/* flatpickr v4.0.2, @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.pt = {}))); }(this, (function (exports) { 'use strict'; var fp = typeof wi...
weekdays: { shorthand: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"], longhand: [ "Domingo", "Segunda-feira", "Terça-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira", "Sábado", ], }, ...
var Portuguese = {
random_line_split
style.js
import { StyleSheet } from 'aphrodite'; import * as fonts from '../../style/fonts'; import * as colors from '../../style/colors'; export default StyleSheet.create({ quiz: { marginTop: '3em' }, flower: { marginTop: '1rem', }, img: { maxWidth: '100%', height: 'auto', marginBottom: '20px' }, rsvpBu...
score: { marginBottom: '2em' }, retake: { marginBottom: '2em', fontSize: '2em', }, retakeLink: { textDecoration: 'underline', cursor: 'pointer', color: colors.blue, ':hover': { color: colors.aquaMarine } } });
rsvpButtonText: { fontSize: fonts.smallerer, fontWeight: 200 },
random_line_split
HardwareInfo.py
from boxbranding import getBoxType, getBrandOEM from Components.About import about class HardwareInfo: device_name = None device_version = None def __init__(self): if HardwareInfo.device_name is not None: # print "using cached result" return HardwareInfo.device_name = "unknown" try: file = open("/pr...
def has_deepstandby(self): return getBoxType() != 'dm800' def is_nextgen(self): if about.getCPUString() in ('BCM7346B2', 'BCM7425B2', 'BCM7429B0'): return True return False
return getBrandOEM() in ('xtrend', 'gigablue', 'dags', 'ixuss', 'odin', 'vuplus', 'ini', 'ebox', 'ceryon') or (getBoxType() in ('dm7020hd', 'dm800se', 'dm500hd', 'dm8000') and HardwareInfo.device_version is not None)
identifier_body
HardwareInfo.py
from boxbranding import getBoxType, getBrandOEM from Components.About import about class HardwareInfo: device_name = None device_version = None def __init__(self): if HardwareInfo.device_name is not None: # print "using cached result" return HardwareInfo.device_name = "unknown" try: file = open("/pr...
except: pass def get_device_name(self): return HardwareInfo.device_name def get_device_version(self): return HardwareInfo.device_version def has_hdmi(self): return getBrandOEM() in ('xtrend', 'gigablue', 'dags', 'ixuss', 'odin', 'vuplus', 'ini', 'ebox', 'ceryon') or (getBoxType() in ('dm7020hd', 'dm...
HardwareInfo.device_name = "dm7025" print "dm7025 detected!"
conditional_block
HardwareInfo.py
from boxbranding import getBoxType, getBrandOEM from Components.About import about class HardwareInfo: device_name = None device_version = None def __init__(self): if HardwareInfo.device_name is not None: # print "using cached result" return HardwareInfo.device_name = "unknown"
HardwareInfo.device_name = file.readline().strip() file.close() try: file = open("/proc/stb/info/version", "r") HardwareInfo.device_version = file.readline().strip() file.close() except: pass except: print "----------------" print "you should upgrade to new drivers for the hardware d...
try: file = open("/proc/stb/info/model", "r")
random_line_split
HardwareInfo.py
from boxbranding import getBoxType, getBrandOEM from Components.About import about class
: device_name = None device_version = None def __init__(self): if HardwareInfo.device_name is not None: # print "using cached result" return HardwareInfo.device_name = "unknown" try: file = open("/proc/stb/info/model", "r") HardwareInfo.device_name = file.readline().strip() file.close() try:...
HardwareInfo
identifier_name
tests.rs
use crate::nailgun::{CommandRunner, ARGS_TO_START_NAILGUN, NAILGUN_MAIN_CLASS}; use crate::{PlatformConstraint, Process, ProcessMetadata}; use futures::compat::Future01CompatExt; use hashing::EMPTY_DIGEST; use std::fs::read_link; use std::os::unix::fs::symlink; use std::path::PathBuf; use store::Store; use tempfile::Te...
(base_dir: PathBuf, prefix: Option<String>) -> TempDir { tempfile::Builder::new() .prefix(&(prefix.unwrap_or("".to_string()))) .tempdir_in(&base_dir) .expect("Error making tempdir for local process execution: {:?}") } fn mock_nailgunnable_request(jdk_home: Option<PathBuf>) -> Process { Process { ar...
unique_temp_dir
identifier_name
tests.rs
use crate::nailgun::{CommandRunner, ARGS_TO_START_NAILGUN, NAILGUN_MAIN_CLASS}; use crate::{PlatformConstraint, Process, ProcessMetadata}; use futures::compat::Future01CompatExt; use hashing::EMPTY_DIGEST; use std::fs::read_link; use std::os::unix::fs::symlink; use std::path::PathBuf; use store::Store; use tempfile::Te...
// Trigger materialization of the nailgun server workdir let materialization_result = materialize_with_jdk(&runner, workdir_for_server, requested_mock_jdk_path.clone()).await; assert!(materialization_result.is_ok()); // Assert that the symlink points to the requested jdk, and not the original one let ma...
{ let workdir_base_tempdir = unique_temp_dir(std::env::temp_dir(), None); let workdir_base = workdir_base_tempdir.path().to_owned(); let runner = mock_nailgun_runner(Some(workdir_base)); let nailgun_name = "mock_server".to_string(); let original_mock_jdk_dir = unique_temp_dir(std::env::temp_dir(), None); ...
identifier_body
tests.rs
use crate::nailgun::{CommandRunner, ARGS_TO_START_NAILGUN, NAILGUN_MAIN_CLASS}; use crate::{PlatformConstraint, Process, ProcessMetadata}; use futures::compat::Future01CompatExt; use hashing::EMPTY_DIGEST; use std::fs::read_link; use std::os::unix::fs::symlink; use std::path::PathBuf; use store::Store; use tempfile::Te...
fn mock_nailgunnable_request(jdk_home: Option<PathBuf>) -> Process { Process { argv: vec![], env: Default::default(), working_directory: None, input_files: EMPTY_DIGEST, output_files: Default::default(), output_directories: Default::default(), timeout: Default::default(), description: ...
.tempdir_in(&base_dir) .expect("Error making tempdir for local process execution: {:?}") }
random_line_split
service.py
# Copyright 2011 OpenStack Foundation # All Rights Reserved. # # 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 requ...
"""Controller for storage device functionality.""" @admin_context def index(self, req, tenant_id): """Return all storage devices.""" LOG.info(_("req : '%s'\n\n") % req) LOG.info(_("Indexing storage info for tenant '%s'") % tenant_id) context = req.environ[wsgi.CONTEXT_KEY] ...
identifier_body
service.py
# Copyright 2011 OpenStack Foundation # All Rights Reserved. # # 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 requ...
(wsgi.Controller): """Controller for storage device functionality.""" @admin_context def index(self, req, tenant_id): """Return all storage devices.""" LOG.info(_("req : '%s'\n\n") % req) LOG.info(_("Indexing storage info for tenant '%s'") % tenant_id) context = req.environ[...
StorageController
identifier_name
service.py
# Copyright 2011 OpenStack Foundation
# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # ...
# All Rights Reserved. # # 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
random_line_split
storage.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. define_error_codes!( "KV:Storage:", TIMEOUT => ("Timeout", "", ""), EMPTY_REQUEST => ("EmptyRequest", "", ""), CLOSED => ("Closed", "", ""), IO => ("Io", "", ""), SCHED_TOO_BUSY => ("SchedTooBusy", "", ""), GC_WORKER_TOO_BU...
UNKNOWN => ("Unknown", "", "") );
COMMIT_TS_EXPIRED => ("CommitTsExpired", "", ""), KEY_VERSION => ("KeyVersion", "",""), PESSIMISTIC_LOCK_NOT_FOUND => ("PessimisticLockNotFound", "", ""), COMMIT_TS_TOO_LARGE => ("CommitTsTooLarge", "", ""),
random_line_split
mysqlconnector.py
# mysql/mysqlconnector.py # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: mysql+mysqlconnector :name: MySQL Connector/Python ...
class MySQLDialect_mysqlconnector(MySQLDialect): driver = 'mysqlconnector' supports_unicode_binds = True supports_sane_rowcount = True supports_sane_multi_rowcount = True supports_native_decimal = True default_paramstyle = 'format' execution_ctx_cls = MySQLExecutionContext_mysqlconnec...
"""MySQL-connector already converts mysql bits, so.""" return None
identifier_body
mysqlconnector.py
# mysql/mysqlconnector.py # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: mysql+mysqlconnector :name: MySQL Connector/Python ...
(self, text): if self.dialect._mysqlconnector_double_percents: return text.replace('%', '%%') else: return text class MySQLIdentifierPreparer_mysqlconnector(MySQLIdentifierPreparer): def _escape_identifier(self, value): value = value.replace(self.escape_quote, self...
escape_literal_column
identifier_name
mysqlconnector.py
# mysql/mysqlconnector.py # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: mysql+mysqlconnector :name: MySQL Connector/Python ...
else: return False def _compat_fetchall(self, rp, charset=None): return rp.fetchall() def _compat_fetchone(self, rp, charset=None): return rp.fetchone() dialect = MySQLDialect_mysqlconnector
return e.errno in errnos or \ "MySQL Connection not available." in str(e)
conditional_block
mysqlconnector.py
# mysql/mysqlconnector.py # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: mysql+mysqlconnector :name: MySQL Connector/Python ...
if self.dbapi and hasattr(self.dbapi, '__version__'): m = re.match(r'(\d+)\.(\d+)(?:\.(\d+))?', self.dbapi.__version__) if m: return tuple( int(x) for x in m.group(1, 2, 3) if x is not No...
def _mysqlconnector_version_info(self):
random_line_split
chartProxy.d.ts
import { AgChartThemeOverrides, CaptionOptions, ChartOptions, ChartType, ColumnApi, DropShadowOptions, EventService, FontOptions, GridApi, PaddingOptions, ProcessChartOptionsParams, SeriesOptions } from "@ag-grid-community/core"; import { AgChartTheme, AgChartThemePalette, Chart, ChartTheme } from "ag-charts-community"...
}
protected destroyChart(): void;
random_line_split
base.js
if(!Hummingbird) { var Hummingbird = {}; } Hummingbird.Base = function() {}; Hummingbird.Base.prototype = { validMessageCount: 0, messageRate: 20, initialize: function() { this.averageLog = []; this.setFilter(); this.registerHandler(); }, registerHandler: function() { this.socket.registe...
if((!this.options.every) || (this.validMessageCount % this.options.every == 0)) { this.onMessage(message, this.average()); } } }, extract: function(data) { if(typeof(data) == "undefined") { return; } var obj = data; for(var i = 0, len = this.filter.length; i < len; i++) { ...
{ average = this.addToAverage(message); }
conditional_block
base.js
if(!Hummingbird) { var Hummingbird = {}; } Hummingbird.Base = function() {}; Hummingbird.Base.prototype = { validMessageCount: 0, messageRate: 20, initialize: function() { this.averageLog = []; this.setFilter(); this.registerHandler(); },
registerHandler: function() { this.socket.registerHandler(this.onData, this); }, onMessage: function(message) { console.log("Base class says: " + JSON.stringify(message)); }, onData: function(fullData) { var average; var message = this.extract(fullData); if(typeof(message) != "undefined"...
random_line_split
UsersDetailContainer.tsx
/* 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/. */ import * as React from 'react'; import * as _ from 'lodash'; import { User, UserRole } from '../../types/items'; imp...
constructor(props: UsersDisplayContainerProps) { super(props); this.deleteUser = this.deleteUser.bind(this); this.editUser = this.editUser.bind(this); this.fetchUsers = this.fetchUsers.bind(this); this.submitUserEdits = this.submitUserEdits.bind(this); } state: UsersDisplayContainerState = { users: [], ...
} export default class UsersDetailContainer extends React.Component<UsersDisplayContainerProps, UsersDisplayContainerState> {
random_line_split
UsersDetailContainer.tsx
/* 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/. */ import * as React from 'react'; import * as _ from 'lodash'; import { User, UserRole } from '../../types/items'; imp...
public render() { return ( <div> <HeaderContainer /> <UserDetailComponent deleteUser={this.deleteUser} edited={!_.isEqual(this.state.users, this.state.history[0])} editUser={this.editUser} users={this.state.users} submitUserEdits={this.submitUserEdits} /> <FooterContaine...
{ try { await usersApi.deleteUser(email); const users = await this.fetchUsers(); this.setState({ users }); showSuccessNotification(translate('users.successfully.delete.user')); } catch (error) { showErrorNotification(translate('users.failed.to.delete.user')); } }
identifier_body
UsersDetailContainer.tsx
/* 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/. */ import * as React from 'react'; import * as _ from 'lodash'; import { User, UserRole } from '../../types/items'; imp...
() { return ( <div> <HeaderContainer /> <UserDetailComponent deleteUser={this.deleteUser} edited={!_.isEqual(this.state.users, this.state.history[0])} editUser={this.editUser} users={this.state.users} submitUserEdits={this.submitUserEdits} /> <FooterContainer /> </div> ...
render
identifier_name
UsersDetailContainer.tsx
/* 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/. */ import * as React from 'react'; import * as _ from 'lodash'; import { User, UserRole } from '../../types/items'; imp...
} private async submitUserEdits() { try { await usersApi.editUsers(this.state.users); showSuccessNotification(translate('users.successfully.edit.users')); this.setState(currentState => ({ history: [_.cloneDeep<User[]>(currentState.users)] })); } catch (error) { showErrorNotification(translate...
{ targetUser.role = newRole; this.setState(prevState => ({ users: newUsers, history: [...prevState.history, newUsers] })); }
conditional_block
expand-path-test.js
import expandPath from 'fireplace/utils/expand-path'; import {module, test} from 'qunit'; module('Utils - expandPath'); test('replaces placeholders from the provided context', function(assert) { assert.equal(expandPath("/foo/{{bar}}/baz", {bar: 123}), "/foo/123/baz"); }); test('replaces nested placeholders from t...
});
test('ignores strings with no placeholders', function(assert) { assert.equal(expandPath("/foo/bar/baz"), "/foo/bar/baz");
random_line_split
tables.py
# import json # import pandas as pd import numpy as np import os from core.lda_engine import model_files from pandas import DataFrame from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from core.keyword_db import keyword_dbs def db_connect(base, model_name='dss'): try: path = 'sq...
else: return Author, Document, KA, DA, Keyword def get_top_keywords(model_name, author_id, n): engine = db_connect("databases", model_name=model_name) Session = sessionmaker(bind=engine) session = Session() Key_Auth_ID = ''' select keyword, count(*) as frequency from (select autho...
return Author, Document, KA, DA
conditional_block
tables.py
# import json # import pandas as pd import numpy as np import os from core.lda_engine import model_files from pandas import DataFrame from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from core.keyword_db import keyword_dbs def
(base, model_name='dss'): try: path = 'sqlite:///' + os.path.join(os.getcwd(), base, keyword_dbs[model_name] + '.sqlite') except KeyError: path = 'sqlite:///' + os.path.join(os.getcwd(), base, model_files[model_name].split(".")[0] + '.sqlite') print("Connecting to: ", path) return create...
db_connect
identifier_name
tables.py
# import json # import pandas as pd import numpy as np import os from core.lda_engine import model_files from pandas import DataFrame from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from core.keyword_db import keyword_dbs
try: path = 'sqlite:///' + os.path.join(os.getcwd(), base, keyword_dbs[model_name] + '.sqlite') except KeyError: path = 'sqlite:///' + os.path.join(os.getcwd(), base, model_files[model_name].split(".")[0] + '.sqlite') print("Connecting to: ", path) return create_engine(path) def toData...
def db_connect(base, model_name='dss'):
random_line_split
tables.py
# import json # import pandas as pd import numpy as np import os from core.lda_engine import model_files from pandas import DataFrame from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from core.keyword_db import keyword_dbs def db_connect(base, model_name='dss'): try: path = 'sq...
def get_database(model_name, return_keyword=False): engine = db_connect("databases", model_name=model_name) Session = sessionmaker(bind=engine) session = Session() doc = "select * from documents" auth = "select * from authors" Author = toDataFrame(auth, session) Author.index = Author.id ...
tmpt = session.execute(sql) return DataFrame(tmpt.fetchall(), columns=tmpt.keys())
identifier_body
gravatar_tags.py
import re import urllib import hashlib from django import template from django.conf import settings URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?', re.IGNORECASE) EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$', re.IGNORECASE) GRAVATAR_URL_PREFIX = 'http...
# treat as a variable else: email = template.Variable(self.email).resolve(context) except template.VariableDoesNotExist: return '' # now, we generate the gravatar url return _build_gravatar_url(email, params) @register.tag(name="gravatar_ur...
email = email_literal
conditional_block
gravatar_tags.py
import re import urllib import hashlib from django import template from django.conf import settings URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?', re.IGNORECASE) EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$', re.IGNORECASE) GRAVATAR_URL_PREFIX = 'http...
if not EMAIL_RE.match(email): return '' email_hash = hashlib.md5(email).hexdigest() # step 2a: build a canonized parameters dictionary if not type(params).__name__ == 'dict': params = params.__dict__ actual_params = {} default_keys = DEFAULT_PARAMS.keys() for key, value in...
""" # step 1: get a hex hash of the email address email = email.strip().lower().encode('utf-8')
random_line_split
gravatar_tags.py
import re import urllib import hashlib from django import template from django.conf import settings URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?', re.IGNORECASE) EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$', re.IGNORECASE) GRAVATAR_URL_PREFIX = 'http...
(email, params): """Generate a Gravatar URL. """ # step 1: get a hex hash of the email address email = email.strip().lower().encode('utf-8') if not EMAIL_RE.match(email): return '' email_hash = hashlib.md5(email).hexdigest() # step 2a: build a canonized parameters dictionary ...
_build_gravatar_url
identifier_name
gravatar_tags.py
import re import urllib import hashlib from django import template from django.conf import settings URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?', re.IGNORECASE) EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$', re.IGNORECASE) GRAVATAR_URL_PREFIX = 'http...
# now, we generate the gravatar url return _build_gravatar_url(email, params) @register.tag(name="gravatar_url") def get_gravatar_url(parser, token): """For template tag: {% gravatar_url <email> <params> %} Where <params> is an object or a dictionary (variable), and <email> is a string ...
def __init__(self, email, params): self.email = email self.params = params def render(self, context): try: if self.params: params = template.Variable(self.params).resolve(context) else: params = {} # try matching an addres...
identifier_body
google.js
import { postToServer } from "../app/utils"; import { wait } from "../app/utils"; /** * Google Authentication and linking module * @returns {{link: function:object, login: function}} */ const googleProvider = new firebase.auth.GoogleAuthProvider(); function callIfFunction(func, arg1, arg2)
export function login() { return firebase.auth().signInWithPopup(googleProvider) .then(function (result) { const userLoggedIn = result && result.user; if (userLoggedIn) return result.user.getIdToken(false); else throw Error('Could not au...
{ if ($.isFunction(func)) func(arg1, arg2); }
identifier_body
google.js
import { postToServer } from "../app/utils"; import { wait } from "../app/utils"; /** * Google Authentication and linking module * @returns {{link: function:object, login: function}} */ const googleProvider = new firebase.auth.GoogleAuthProvider(); function callIfFunction(func, arg1, arg2) { if ($.isFunction(...
}).catch(function(error) { callIfFunction(linkCallback, false, error); }); } else { callIfFunction(linkCallback, false, error); } }); }, unlinkGoogle: function (unlinkCall...
accountLinked(linkCallback, user);
random_line_split
google.js
import { postToServer } from "../app/utils"; import { wait } from "../app/utils"; /** * Google Authentication and linking module * @returns {{link: function:object, login: function}} */ const googleProvider = new firebase.auth.GoogleAuthProvider(); function callIfFunction(func, arg1, arg2) { if ($.isFunction(...
() { function getProviderData(providerDataArray, providerId) { if (!providerDataArray) return null; for (var i = 0; i < providerDataArray.length; i++) if (providerDataArray[i].providerId === providerId) return providerDataArray[i]; return null; ...
link
identifier_name
operator-assignment.js
/** * @fileoverview Rule to replace assignment expressions with operator assignment * @author Brandon Mills * @copyright 2014 Brandon Mills. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Helpers //------------------------------------------...
} /** * Warns if an assignment expression uses operator assignment shorthand. * @param {ASTNode} node An AssignmentExpression node. * @returns {void} */ function prohibit(node) { if (node.operator !== "=") { context.report(node, "Unexpected operator assignment sho...
{ if (same(left, expr.left)) { context.report(node, "Assignment can be replaced with operator assignment."); } }
conditional_block
operator-assignment.js
/** * @fileoverview Rule to replace assignment expressions with operator assignment * @author Brandon Mills * @copyright 2014 Brandon Mills. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Helpers //------------------------------------------...
* Checks whether an operator is not commuatative and has an operator assignment * shorthand form. * @param {string} operator Operator to check. * @returns {boolean} True if the operator is not commuatative and has * a shorthand form. */ function isNonCommutativeOperatorWithShorthand(operator) { ...
/**
random_line_split
operator-assignment.js
/** * @fileoverview Rule to replace assignment expressions with operator assignment * @author Brandon Mills * @copyright 2014 Brandon Mills. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Helpers //------------------------------------------...
(operator) { return ["+", "-", "/", "%", "<<", ">>", ">>>"].indexOf(operator) >= 0; } //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ /** * Checks whether two expressions reference...
isNonCommutativeOperatorWithShorthand
identifier_name
operator-assignment.js
/** * @fileoverview Rule to replace assignment expressions with operator assignment * @author Brandon Mills * @copyright 2014 Brandon Mills. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Helpers //------------------------------------------...
/** * Checks whether an operator is not commuatative and has an operator assignment * shorthand form. * @param {string} operator Operator to check. * @returns {boolean} True if the operator is not commuatative and has * a shorthand form. */ function isNonCommutativeOperatorWithShorthand(operator...
{ return ["*", "&", "^", "|"].indexOf(operator) >= 0; }
identifier_body
Trip.ts
import { computed } from 'mobx'; import DataStore from './DataStore';
readonly endAt: number; readonly distance: number; readonly duration: number; } export function isTripData(value: any): value is ITripData { return ( value.from != null && value.to != null && value.startAt != null && value.endAt != null && value.distance != null && value.duration != nul...
export interface ITripData { readonly from: number; readonly to: number; readonly startAt: number;
random_line_split
Trip.ts
import { computed } from 'mobx'; import DataStore from './DataStore'; export interface ITripData { readonly from: number; readonly to: number; readonly startAt: number; readonly endAt: number; readonly distance: number; readonly duration: number; } export function isTripData(value: any): value is ITripDa...
(store: DataStore, data: ITripData) { this.store = store; this.fromPlaceId = data.from; this.toPlaceId = data.to; this.startAt = data.startAt; this.endAt = data.endAt; this.distance = data.distance; this.duration = data.duration; } @computed get from() { const from = this.store.p...
constructor
identifier_name
Trip.ts
import { computed } from 'mobx'; import DataStore from './DataStore'; export interface ITripData { readonly from: number; readonly to: number; readonly startAt: number; readonly endAt: number; readonly distance: number; readonly duration: number; } export function isTripData(value: any): value is ITripDa...
@computed get to() { const to = this.store.places.find(place => place.id === this.toPlaceId); if (to == null) { throw new Error('Missing place.'); } return to; } @computed get visible() { const { timeSpan } = this.store.ui; if (timeSpan == null) { return true; } ...
{ const from = this.store.places.find(place => place.id === this.fromPlaceId); if (from == null) { throw new Error('Missing place.'); } return from; }
identifier_body
Trip.ts
import { computed } from 'mobx'; import DataStore from './DataStore'; export interface ITripData { readonly from: number; readonly to: number; readonly startAt: number; readonly endAt: number; readonly distance: number; readonly duration: number; } export function isTripData(value: any): value is ITripDa...
return from; } @computed get to() { const to = this.store.places.find(place => place.id === this.toPlaceId); if (to == null) { throw new Error('Missing place.'); } return to; } @computed get visible() { const { timeSpan } = this.store.ui; if (timeSpan == null) { ...
{ throw new Error('Missing place.'); }
conditional_block
slide-gesture.d.ts
import { PanGesture } from './pan-gesture'; import { Platform } from '../platform/platform'; /** * @hidden */ export declare class SlideGesture extends PanGesture { slide: SlideData; constructor(plt: Platform, element: HTMLElement, opts?: {}); getSlideBoundaries(slide: SlideData, ev: any): { min: ...
onDragMove(ev: any): void; onDragEnd(ev: any): void; onSlideBeforeStart(ev?: any): void; onSlideStart(slide?: SlideData, ev?: any): void; onSlide(slide?: SlideData, ev?: any): void; onSlideEnd(slide?: SlideData, ev?: any): void; } /** * @hidden */ export interface SlideData { min: number; ...
max: number; }; getElementStartPos(slide: SlideData, ev: any): number; onDragStart(ev: any): void;
random_line_split
slide-gesture.d.ts
import { PanGesture } from './pan-gesture'; import { Platform } from '../platform/platform'; /** * @hidden */ export declare class
extends PanGesture { slide: SlideData; constructor(plt: Platform, element: HTMLElement, opts?: {}); getSlideBoundaries(slide: SlideData, ev: any): { min: number; max: number; }; getElementStartPos(slide: SlideData, ev: any): number; onDragStart(ev: any): void; onDragMove(ev:...
SlideGesture
identifier_name
lib.rs
//! Library to interface MPD // Developers: keep handy: http://www.musicpd.org/doc/protocol/command_reference.html #![deny(missing_docs)] #![deny(warnings)] extern crate bufstream; use std::borrow::Cow; use std::io::{self, BufRead, Write}; use std::net::{TcpStream, ToSocketAddrs}; use bufstream::BufStream; pub mo...
<A>(addr: A) -> io::Result<Connection> where A: ToSocketAddrs { fn new(stream: TcpStream) -> io::Result<Connection> { let mut stream = BufStream::new(stream); let mut buffer = String::new(); try!(stream.read_line(&mut buffer)); if !buffer.starts_with("OK MPD ") { //...
connect
identifier_name
lib.rs
//! Library to interface MPD // Developers: keep handy: http://www.musicpd.org/doc/protocol/command_reference.html #![deny(missing_docs)] #![deny(warnings)] extern crate bufstream; use std::borrow::Cow; use std::io::{self, BufRead, Write}; use std::net::{TcpStream, ToSocketAddrs}; use bufstream::BufStream; pub mo...
} /// A MPD command pub enum Command<'a> { /// Adds the file `uri` to the playlist (directories are added recursively) Add { /// If `None`, adds the whole database uri: &'a str, }, /// Clears the current playlist Clear, /// Displays the song info of the current song Current...
{ use self::Mode::*; match *self { Consume => "consume", Random => "random", Repeat => "repeat", Single => "single", } }
identifier_body
lib.rs
//! Library to interface MPD // Developers: keep handy: http://www.musicpd.org/doc/protocol/command_reference.html #![deny(missing_docs)] #![deny(warnings)] extern crate bufstream; use std::borrow::Cow; use std::io::{self, BufRead, Write}; use std::net::{TcpStream, ToSocketAddrs}; use bufstream::BufStream; pub mo...
Status => "status", Stop => "stop", Update { uri: None } => "update", Update { uri: Some(uri) } => return format!("update \"{}\"", uri).into(), Volume { level } => return format!("setvol {}", level).into(), }) } } /// A connection to MPD pub stru...
{ return format!("{} {}", mode.str(), if state { "1" } else { "0" }) .into() ...
conditional_block
lib.rs
//! Library to interface MPD // Developers: keep handy: http://www.musicpd.org/doc/protocol/command_reference.html #![deny(missing_docs)] #![deny(warnings)] extern crate bufstream; use std::borrow::Cow; use std::io::{self, BufRead, Write}; use std::net::{TcpStream, ToSocketAddrs}; use bufstream::BufStream; pub mo...
Stop => "stop", Update { uri: None } => "update", Update { uri: Some(uri) } => return format!("update \"{}\"", uri).into(), Volume { level } => return format!("setvol {}", level).into(), }) } } /// A connection to MPD pub struct Connection { buffer: Strin...
Status => "status",
random_line_split
findBreaksVCF.py
#!/usr/bin/python import re import sys import os import getopt import vcf def main(): params = parseArgs() vfh = vcf.Reader(open(params.vcf, 'r')) #grab contig sizes contigs = dict() for c,s in vfh.contigs.items(): contigs[s.id] = s.length regions = list() this_chrom = None start = int() stop = int() ...
(f, r): with open(f, 'w') as fh: try: for reg in r: ol = str(reg[0]) + ":" + str(reg[1]) + "-" + str(reg[2]) + "\n" fh.write(ol) except IOError as e: print("Could not read file %s: %s"%(f,e)) sys.exit(1) except Exception as e: print("Unexpected error reading file %s: %s"%(f,e)) sys.exit(1...
write_regions
identifier_name