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 |
|---|---|---|---|---|
tap4nodeunit.js | /*
* Copyright 2012 Mark Cavage. All rights reserved.
*
* Help nodeunit API feel like node-tap's.
*
* Usage:
* if (require.cache[__dirname + '/tap4nodeunit.js'])
* delete require.cache[__dirname + '/tap4nodeunit.js'];
* var tap4nodeunit = require('./tap4nodeunit.js');
* var after = tap... |
};
t.notOk = function notOk(ok, message) {
return (t.ok(!ok, message));
};
tester.call(this, t);
};
}
};
| {
_done = true;
t.done();
} | conditional_block |
component.ts | // Copyright 2017 The Kubernetes Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... | (): void {
this.storageClassSubscription_.unsubscribe();
}
getParameterNames(): string[] {
return !!this.storageClass.parameters
? Object.keys(this.storageClass.parameters)
: [];
}
}
| ngOnDestroy | identifier_name |
component.ts | // Copyright 2017 The Kubernetes Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... | ActionbarService,
ResourceMeta,
} from '../../../../common/services/global/actionbar';
import { NotificationsService } from '../../../../common/services/global/notifications';
import {
EndpointManager,
Resource,
} from '../../../../common/services/resource/endpoint';
import { ResourceService } from '../../../..... | import { Subscription } from 'rxjs/Subscription';
import { | random_line_split |
styled-select.directive.ts | import { Directive, ElementRef, Renderer2, AfterViewInit, Input } from '@angular/core';
@Directive({
selector: '[appStyledSelect]'
})
export class StyledSelectDirective implements AfterViewInit {
@Input()
width: string;
constructor(private el: ElementRef, private renderer: Renderer2) {}
| () {
this.applyStyles();
}
applyStyles() {
this.setParentDivStyles(this.el.nativeElement);
this.setDropdownArrow();
this.setSelectStyles(this.el.nativeElement.getElementsByTagName('select')[0]);
}
setParentDivStyles(parentDiv: ElementRef) {
this.renderer.setStyle(parentDiv, 'position', 're... | ngAfterViewInit | identifier_name |
styled-select.directive.ts | import { Directive, ElementRef, Renderer2, AfterViewInit, Input } from '@angular/core';
@Directive({
selector: '[appStyledSelect]'
})
export class StyledSelectDirective implements AfterViewInit {
@Input()
width: string;
constructor(private el: ElementRef, private renderer: Renderer2) {}
ngAfterViewInit() {... |
setDropdownArrow() {
const newSpan = this.renderer.createElement('span');
this.renderer.setStyle(newSpan, 'cursor', 'pointer');
this.renderer.setStyle(newSpan, 'height', '14px');
this.renderer.setStyle(newSpan, 'width', '14px');
this.renderer.setStyle(newSpan, 'position', 'absolute');
this.r... | {
this.renderer.setStyle(select, '-webkit-appearance', 'none');
this.renderer.setStyle(select, '-moz-appearance', 'none');
this.renderer.setStyle(select, 'appearance', 'none');
this.renderer.setStyle(select, 'height', '32px');
this.renderer.setStyle(select, 'width', `${this.width}px`);
this.rend... | identifier_body |
styled-select.directive.ts | import { Directive, ElementRef, Renderer2, AfterViewInit, Input } from '@angular/core';
@Directive({
selector: '[appStyledSelect]'
})
export class StyledSelectDirective implements AfterViewInit {
@Input()
width: string;
constructor(private el: ElementRef, private renderer: Renderer2) {}
ngAfterViewInit() {... | applyStyles() {
this.setParentDivStyles(this.el.nativeElement);
this.setDropdownArrow();
this.setSelectStyles(this.el.nativeElement.getElementsByTagName('select')[0]);
}
setParentDivStyles(parentDiv: ElementRef) {
this.renderer.setStyle(parentDiv, 'position', 'relative');
}
setSelectStyles(s... | random_line_split | |
scif.rs | //! formatter for %e %E scientific notation subs
use super::super::format_field::FormatField;
use super::super::formatter::{FormatPrimitive, Formatter, InPrefix};
use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis};
pub struct Scif {
as_num: f64,
}
impl Scif {
pub fn new() -> S... |
fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String {
primitive_to_str_common(prim, &field)
}
}
| {
let second_field = field.second_field.unwrap_or(6) + 1;
let analysis = FloatAnalysis::analyze(
str_in,
inprefix,
Some(second_field as usize + 1),
None,
false,
);
let f = get_primitive_dec(
inprefix,
&st... | identifier_body |
scif.rs | //! formatter for %e %E scientific notation subs
use super::super::format_field::FormatField;
use super::super::formatter::{FormatPrimitive, Formatter, InPrefix};
use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis};
pub struct Scif {
as_num: f64,
}
impl Scif { | impl Formatter for Scif {
fn get_primitive(
&self,
field: &FormatField,
inprefix: &InPrefix,
str_in: &str,
) -> Option<FormatPrimitive> {
let second_field = field.second_field.unwrap_or(6) + 1;
let analysis = FloatAnalysis::analyze(
str_in,
... | pub fn new() -> Scif {
Scif { as_num: 0.0 }
}
} | random_line_split |
scif.rs | //! formatter for %e %E scientific notation subs
use super::super::format_field::FormatField;
use super::super::formatter::{FormatPrimitive, Formatter, InPrefix};
use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis};
pub struct Scif {
as_num: f64,
}
impl Scif {
pub fn new() -> S... | (
&self,
field: &FormatField,
inprefix: &InPrefix,
str_in: &str,
) -> Option<FormatPrimitive> {
let second_field = field.second_field.unwrap_or(6) + 1;
let analysis = FloatAnalysis::analyze(
str_in,
inprefix,
Some(second_field as us... | get_primitive | identifier_name |
test_lipop1.py | import os
import unittest
import sys
import inmembrane
import inmembrane.tests
from inmembrane import helpers
from inmembrane.plugins import lipop1
from inmembrane.tests.PluginTestBase import PluginTestBase
class TestLipoP(PluginTestBase):
_plugin_name = "lipop1"
def test_lipop1(self):
if not self.... | unittest.main() | random_line_split | |
test_lipop1.py | import os
import unittest
import sys
import inmembrane
import inmembrane.tests
from inmembrane import helpers
from inmembrane.plugins import lipop1
from inmembrane.tests.PluginTestBase import PluginTestBase
class TestLipoP(PluginTestBase):
_plugin_name = "lipop1"
def test_lipop1(self):
if not self.... |
self.assertEqual(self.proteins[u'tr|Q9HYX8']['lipop_cleave_position'],
19)
self.assertIn('lipop_im_retention_signal', self.proteins[u'tr|Q9HYX8'])
self.assertTrue(
self.proteins[u'tr|Q9HYX8']['lipop_im_retention_signal'])
if __name__ == '__main__':
uni... | self.assertEqual(
self.expected_output[seqid], self.proteins[seqid]['is_lipop']) | conditional_block |
test_lipop1.py | import os
import unittest
import sys
import inmembrane
import inmembrane.tests
from inmembrane import helpers
from inmembrane.plugins import lipop1
from inmembrane.tests.PluginTestBase import PluginTestBase
class TestLipoP(PluginTestBase):
_plugin_name = "lipop1"
def test_lipop1(self):
|
if __name__ == '__main__':
unittest.main()
| if not self.params['lipop1_bin']:
self.params['lipop1_bin'] = 'LipoP'
lipop1.annotate(self.params, self.proteins)
self.expected_output = {
u'SPy_0252': True,
u'SPy_2077': False,
u'SPy_0317': True,
u'tr|Q9HYX8': True,
}
for se... | identifier_body |
test_lipop1.py | import os
import unittest
import sys
import inmembrane
import inmembrane.tests
from inmembrane import helpers
from inmembrane.plugins import lipop1
from inmembrane.tests.PluginTestBase import PluginTestBase
class TestLipoP(PluginTestBase):
_plugin_name = "lipop1"
def | (self):
if not self.params['lipop1_bin']:
self.params['lipop1_bin'] = 'LipoP'
lipop1.annotate(self.params, self.proteins)
self.expected_output = {
u'SPy_0252': True,
u'SPy_2077': False,
u'SPy_0317': True,
u'tr|Q9HYX8': True,
}... | test_lipop1 | identifier_name |
main.js | $(function() {
var toc = $('.toc-link'),
sidebar = $('#sidebar'),
main = $('#main'),
menu = $('#menu'),
x1, y1;
// run this function after pjax load.
var afterPjax = function() {
// open links in new tab.
$('#main').find('a').filter(function() {
return this.hostnam... | main.removeClass('fadeIn');
},
'pjax:end': function() {
afterPjax();
NProgress.done();
main.scrollTop(0).addClass('fadeIn');
menu.add(sidebar).removeClass('open');
}
});
// Tags Filter
$('#sidebar-tags').on('click', '.sidebar-tag', function() {
var filter = $... | random_line_split | |
main.js | $(function() {
var toc = $('.toc-link'),
sidebar = $('#sidebar'),
main = $('#main'),
menu = $('#menu'),
x1, y1;
// run this function after pjax load.
var afterPjax = function() {
// open links in new tab.
$('#main').find('a').filter(function() {
return this.hostnam... |
$(this).addClass('active').siblings().removeClass('active');
});
// Menu
menu.on('click', function() {
$(this).add(sidebar).toggleClass('open');
});
});
| {
toc.hide();
$('.toc-link[data-tags~=' + filter + ']').fadeIn(350);
} | conditional_block |
booking-toggle-buttons-snackbar.ts | import {_, ng} from 'entcore';
import {ROOTS} from "../../core/const/roots.const";
interface IViewModel {
$onInit(): any;
$onDestroy(): any;
editBooking(): void;
removeBookingSelection(): void;
validateBookingSelection(): void;
refuseBookingSelection(): void;
canEditBookingSelection(): bo... | vm.refuseBookingSelection = (): void => {
$scope.$eval(vm.onRefuseBooking);
};
vm.canEditBookingSelection = (): boolean => {
if (vm.display.list === true) {
let localSelection = _.filter(vm.bookings.selection(), function (booking) ... |
vm.validateBookingSelection = (): void => {
$scope.$eval(vm.onValidateBooking);
};
| random_line_split |
booking-toggle-buttons-snackbar.ts | import {_, ng} from 'entcore';
import {ROOTS} from "../../core/const/roots.const";
interface IViewModel {
$onInit(): any;
$onDestroy(): any;
editBooking(): void;
removeBookingSelection(): void;
validateBookingSelection(): void;
refuseBookingSelection(): void;
canEditBookingSelection(): bo... |
};
vm.canProcessBookingSelection = (): boolean => {
return _.every(vm.bookings.selection(), function (booking) {
return booking.isPending();
});
};
vm.$onDestroy = async () => {
};
}
};
}); | {
return (vm.bookings.selection().length === 1 &&
vm.bookings.selection()[0].resource.is_available === true
);
} | conditional_block |
jquery.grp_autocomplete_m2m.js | /**
* GRAPPELLI AUTOCOMPLETE M2M
* many-to-many lookup with autocomplete
*/
(function($){
var methods = {
init: function(options) {
options = $.extend({}, $.fn.grp_autocomplete_m2m.defaults, options);
return this.each(function() {
var $this = $(this);
... | else {
$.error('Method ' + method + ' does not exist on jQuery.grp_autocomplete_m2m');
}
return false;
};
var value_add = function(elem, value, options) {
var values = [];
if (elem.val()) values = elem.val().split(",");
values.push(value);
elem.... | {
return methods.init.apply(this, arguments);
} | conditional_block |
jquery.grp_autocomplete_m2m.js | /**
* GRAPPELLI AUTOCOMPLETE M2M
* many-to-many lookup with autocomplete
*/
(function($){
var methods = {
init: function(options) {
options = $.extend({}, $.fn.grp_autocomplete_m2m.defaults, options);
return this.each(function() {
var $this = $(this);
... | if (elem.val()) values = elem.val().split(",");
values.splice(position,1);
elem.val(values.join(","));
return values.join(",");
};
var loader = function() {
var loader = $('<div class="grp-loader">loader</div>');
return loader;
};
var remove_link... | var values = []; | random_line_split |
ClearServerStats.js | const computeRankScore = require("./RankScoreCalculator.js");
// Clear activity stats for a server
module.exports = (bot, db, winston, svr, serverDocument, callback) => {
// Rank members by activity score for the week
const topMembers = [];
serverDocument.members.forEach(memberDocument => {
const member = svr.mem... | else {
memberDocument.remove();
}
});
topMembers.sort((a, b) => {
return a[1] - b[1];
});
// Award points to top 3
const awardPoints = (member, amount) => {
db.users.findOrCreate({_id: member.id}, (err, userDocument) => {
if(!err && userDocument) {
userDocument.points += amount;
} else {
w... | {
const activityScore = computeRankScore(memberDocument.messages, memberDocument.voice);
topMembers.push([member, activityScore]);
memberDocument.rank_score += activityScore / 10;
memberDocument.rank = bot.checkRank(winston, svr, serverDocument, member, memberDocument, true);
memberDocument.messages = 0;... | conditional_block |
ClearServerStats.js | const computeRankScore = require("./RankScoreCalculator.js");
// Clear activity stats for a server
module.exports = (bot, db, winston, svr, serverDocument, callback) => {
// Rank members by activity score for the week
const topMembers = [];
serverDocument.members.forEach(memberDocument => {
const member = svr.mem... | // Reset game and command data
serverDocument.games = [];
serverDocument.command_usage = {};
serverDocument.markModified("command_usage");
// Reset stats timestamp
serverDocument.stats_timestamp = Date.now();
// Save changes to serverDocument
serverDocument.save(err => {
if(err) {
winston.error(`Failed t... | }
| random_line_split |
const-vecs-and-slices.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
static x : [int; 4]... | // | random_line_split |
const-vecs-and-slices.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 ... | {
println!("{}", x[1]);
println!("{}", y[1]);
println!("{}", z[1]);
println!("{}", zz[1]);
assert_eq!(x[1], 2);
assert_eq!(x[3], 4);
assert_eq!(x[3], y[3]);
assert_eq!(z[1], 2);
assert_eq!(z[3], 4);
assert_eq!(z[3], y[3]);
assert_eq!(zz[1], 2);
assert_eq!(zz[3], 4);
a... | identifier_body | |
const-vecs-and-slices.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 ... | () {
println!("{}", x[1]);
println!("{}", y[1]);
println!("{}", z[1]);
println!("{}", zz[1]);
assert_eq!(x[1], 2);
assert_eq!(x[3], 4);
assert_eq!(x[3], y[3]);
assert_eq!(z[1], 2);
assert_eq!(z[3], 4);
assert_eq!(z[3], y[3]);
assert_eq!(zz[1], 2);
assert_eq!(zz[3], 4);
... | main | identifier_name |
lib.rs | //! # Test CLI Applications
//!
//! This crate's goal is to provide you some very easy tools to test your CLI
//! applications. It can currently execute child processes and validate their
//! exit status as well as stdout and stderr output against your assertions.
//!
//! Include the crate like
//!
//! ```rust
//! #[ma... | mod assert;
mod diff;
mod output;
pub use assert::Assert;
pub use assert::OutputAssertionBuilder;
/// Environment is a re-export of the Environment crate
///
/// It allow you to define/override environment variables for one or more assertions.
pub use environment::Environment; | mod macros;
pub use macros::flatten_escaped_string;
| random_line_split |
main.rs | use byteorder::{BigEndian, ByteOrder};
fn main() {
// Exercise external crate, printing to stdout.
let buf = &[1,2,3,4];
let n = <BigEndian as ByteOrder>::read_u32(buf);
assert_eq!(n, 0x01020304);
println!("{:#010x}", n);
// Access program arguments, printing to stderr.
for arg in std::env... | () {
let mut rng = rand::rngs::StdRng::seed_from_u64(0xcafebeef);
let x: u32 = rng.gen();
let y: usize = rng.gen();
let z: u128 = rng.gen();
assert_ne!(x as usize, y);
assert_ne!(y as u128, z);
}
}
| rng | identifier_name |
main.rs | use byteorder::{BigEndian, ByteOrder};
fn main() {
// Exercise external crate, printing to stdout.
let buf = &[1,2,3,4];
let n = <BigEndian as ByteOrder>::read_u32(buf);
assert_eq!(n, 0x01020304);
println!("{:#010x}", n);
| eprintln!("{}", arg);
}
}
#[cfg(test)]
mod test {
use rand::{Rng, SeedableRng};
// Make sure in-crate tests with dev-dependencies work
#[test]
fn rng() {
let mut rng = rand::rngs::StdRng::seed_from_u64(0xcafebeef);
let x: u32 = rng.gen();
let y: usize = rng.gen();
... | // Access program arguments, printing to stderr.
for arg in std::env::args() { | random_line_split |
main.rs | use byteorder::{BigEndian, ByteOrder};
fn main() {
// Exercise external crate, printing to stdout.
let buf = &[1,2,3,4];
let n = <BigEndian as ByteOrder>::read_u32(buf);
assert_eq!(n, 0x01020304);
println!("{:#010x}", n);
// Access program arguments, printing to stderr.
for arg in std::env... |
}
| {
let mut rng = rand::rngs::StdRng::seed_from_u64(0xcafebeef);
let x: u32 = rng.gen();
let y: usize = rng.gen();
let z: u128 = rng.gen();
assert_ne!(x as usize, y);
assert_ne!(y as u128, z);
} | identifier_body |
webpack.config.optimize.js | 'use strict'; // eslint-disable-line
const { default: ImageminPlugin } = require('imagemin-webpack-plugin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const config = require('./config');
module.exports = {
plugins: [
new ImageminPlugin({
... | }),
],
}; | }, | random_line_split |
check_errors_xlsx.py | from openpyxl import load_workbook
import os
# list of text to search for
keyWordList = ['Resume', 'Label', 'Description', 'ClueText', 'Title', 'QTEtitle']
# default path for docs on my PC for sh8 game xlsx documents
#docDir = "d:/svn/ue3/SH8Game/Production/Dialogs/"
docDir = "d:/svn/ue3/SH8Game/Production/... | (sheetName, keyWord):
TextColList = []
for col in range(1,100):
findSpokenCoord = sheetName.cell(row = 1, column = col)
findSpokenVal = findSpokenCoord.value
#print findSpokenVal
if findSpokenVal:
if ('.' + keyWord) in findSpokenVal:
TextColList.append(col)
return TextColList
# comparing I... | FindLoc | identifier_name |
check_errors_xlsx.py | from openpyxl import load_workbook
import os
# list of text to search for
keyWordList = ['Resume', 'Label', 'Description', 'ClueText', 'Title', 'QTEtitle']
# default path for docs on my PC for sh8 game xlsx documents
#docDir = "d:/svn/ue3/SH8Game/Production/Dialogs/"
docDir = "d:/svn/ue3/SH8Game/Production/... | intColNum = FindBase(sheetName, keyWord)
locColNumList = FindLoc(sheetName, keyWord)
# checking if INT keyword is present in document
if intColNum:
# even for comments it is enough length
for row in range(4,200):
intRowCoord = sheetName.cell(row = row, column = intColNum)
# obtainin... | # iterating through sheets in document
for sheet in sheetList:
sheetName = workBook[sheet]
| random_line_split |
check_errors_xlsx.py | from openpyxl import load_workbook
import os
# list of text to search for
keyWordList = ['Resume', 'Label', 'Description', 'ClueText', 'Title', 'QTEtitle']
# default path for docs on my PC for sh8 game xlsx documents
#docDir = "d:/svn/ue3/SH8Game/Production/Dialogs/"
docDir = "d:/svn/ue3/SH8Game/Production/... |
return logVal
# collecting all .xlsxs from supplied path
genLog = ''
for path, dirs, fileNames in os.walk(docDir):
for fileName in fileNames:
docPath = os.path.join(path, fileName)
# filtering files except .xlsx
if '.xlsx' in docPath:
# filling log
genLog += FindAndLog(docPa... | for col in locColNumList:
locRowCoord = sheetName.cell(row = row, column = col)
# obtaining LOC cell value
locRowVal = locRowCoord.value
# checking whether LOC cell is duplicate of INT
if intRowVal == locRowVal:
#convering non ASCII characters
#locASCII = str(... | conditional_block |
check_errors_xlsx.py | from openpyxl import load_workbook
import os
# list of text to search for
keyWordList = ['Resume', 'Label', 'Description', 'ClueText', 'Title', 'QTEtitle']
# default path for docs on my PC for sh8 game xlsx documents
#docDir = "d:/svn/ue3/SH8Game/Production/Dialogs/"
docDir = "d:/svn/ue3/SH8Game/Production/... | # obtaining INT cell value
intRowVal = intRowCoord.value
# checking if INT cell is not empty
if intRowVal:
# iterating through LOC columns in list
for col in locColNumList:
locRowCoord = sheetName.cell(row = row, column = col)
# obtaining LOC cell value
... | logVal = ''
workBook = load_workbook(docPath)
# for test purposes
print docPath
# obtaining list of all sheets in document
sheetList = workBook.get_sheet_names()
# adding path to log
logVal += docPath + '\n'
# iterating through key words
for keyWord in keyWordList:
# iterating through sheets in doc... | identifier_body |
sysinfo.py | import os
from multiprocessing import cpu_count
_cpu_count = cpu_count()
if hasattr(os, 'getloadavg'):
def load_fair():
return 'load', os.getloadavg()[0] / _cpu_count
else:
from winperfmon import PerformanceCounter
from threading import Thread
from collections import deque
from time impor... | (self):
while True:
pql, pt = self.counter.query()
self.samples.append(pql)
if pt >= 100:
self.load = max(sum(self.samples) / len(self.samples) / _cpu_count, pt / 100.)
else:
self.load = pt / 100.
... | run | identifier_name |
sysinfo.py | import os
from multiprocessing import cpu_count
_cpu_count = cpu_count()
if hasattr(os, 'getloadavg'):
def load_fair():
return 'load', os.getloadavg()[0] / _cpu_count
else:
from winperfmon import PerformanceCounter
from threading import Thread
from collections import deque
from time impor... | self.counter = PerformanceCounter(r'\System\Processor Queue Length', r'\Processor(_Total)\% Processor Time')
def run(self):
while True:
pql, pt = self.counter.query()
self.samples.append(pql)
if pt >= 100:
self.load = m... | self.load = 0.5 | random_line_split |
sysinfo.py | import os
from multiprocessing import cpu_count
_cpu_count = cpu_count()
if hasattr(os, 'getloadavg'):
def load_fair():
return 'load', os.getloadavg()[0] / _cpu_count
else:
from winperfmon import PerformanceCounter
from threading import Thread
from collections import deque
from time impor... |
_load_thread = SystemLoadThread()
_load_thread.start()
def load_fair():
return 'load', _load_thread.load
def cpu_count():
return 'cpu-count', _cpu_count
report_callbacks = [load_fair, cpu_count]
| def __init__(self):
super(SystemLoadThread, self).__init__()
self.daemon = True
self.samples = deque(maxlen=10)
self.load = 0.5
self.counter = PerformanceCounter(r'\System\Processor Queue Length', r'\Processor(_Total)\% Processor Time')
def run(self):... | identifier_body |
sysinfo.py | import os
from multiprocessing import cpu_count
_cpu_count = cpu_count()
if hasattr(os, 'getloadavg'):
def load_fair():
return 'load', os.getloadavg()[0] / _cpu_count
else:
| self.load = pt / 100.
sleep(1)
_load_thread = SystemLoadThread()
_load_thread.start()
def load_fair():
return 'load', _load_thread.load
def cpu_count():
return 'cpu-count', _cpu_count
report_callbacks = [load_fair, cpu_count]
| from winperfmon import PerformanceCounter
from threading import Thread
from collections import deque
from time import sleep
class SystemLoadThread(Thread):
def __init__(self):
super(SystemLoadThread, self).__init__()
self.daemon = True
self.samples = deque(ma... | conditional_block |
index.ts | import * as Model from 'cerebral-model-baobab'
import { githubLibraryGet } from './signals/githubLibraryGet'
import { libraryGithubPath } from './signals/libraryGithubPath'
import { libraryGithubToken } from './signals/libraryGithubToken'
import { makeId } from '../../modules/Factory'
import { name } from './signals/na... | ( data ) {
const userById = data.userById || {}
return userById [ data.id || 'gaspard' ]
|| defaultUser
}
}
)
export const User =
( options = {}) => {
return (module, controller) => {
module.addState
( CurrentUser
)
module.addSignals
( { name
, githubLibraryGet... | get | identifier_name |
index.ts | import * as Model from 'cerebral-model-baobab'
import { githubLibraryGet } from './signals/githubLibraryGet'
import { libraryGithubPath } from './signals/libraryGithubPath'
import { libraryGithubToken } from './signals/libraryGithubToken'
import { makeId } from '../../modules/Factory'
import { name } from './signals/na... |
}
)
export const User =
( options = {}) => {
return (module, controller) => {
module.addState
( CurrentUser
)
module.addSignals
( { name
, githubLibraryGet
, libraryGithubPath
, libraryGithubToken
}
)
return {} // meta information
}
}
| {
const userById = data.userById || {}
return userById [ data.id || 'gaspard' ]
|| defaultUser
} | identifier_body |
index.ts | import * as Model from 'cerebral-model-baobab'
import { githubLibraryGet } from './signals/githubLibraryGet'
import { libraryGithubPath } from './signals/libraryGithubPath'
import { libraryGithubToken } from './signals/libraryGithubToken'
import { makeId } from '../../modules/Factory'
import { name } from './signals/na... | } | }
)
return {} // meta information
} | random_line_split |
executor.rs | use crossbeam::channel;
use scoped_pool::{Pool, ThreadConfig};
use Result;
/// Search executor whether search request are single thread or multithread.
///
/// We don't expose Rayon thread pool directly here for several reasons.
///
/// First dependency hell. It is not a good idea to expose the
/// API of a dependency... | }
#[cfg(test)]
mod tests {
use super::Executor;
#[test]
#[should_panic(expected = "panic should propagate")]
fn test_panic_propagates_single_thread() {
let _result: Vec<usize> = Executor::single_thread()
.map(
|_| {
panic!("panic should propagat... | random_line_split | |
executor.rs | use crossbeam::channel;
use scoped_pool::{Pool, ThreadConfig};
use Result;
/// Search executor whether search request are single thread or multithread.
///
/// We don't expose Rayon thread pool directly here for several reasons.
///
/// First dependency hell. It is not a good idea to expose the
/// API of a dependency... | // This ends the scope of fruit_sender.
// This is important as it makes it possible for the fruit_receiver iteration to
// terminate.
};
// This is lame, but safe.
let mut results_with_position = Vec::with_capac... | {
match self {
Executor::SingleThread => args.map(f).collect::<Result<_>>(),
Executor::ThreadPool(pool) => {
let args_with_indices: Vec<(usize, A)> = args.enumerate().collect();
let num_fruits = args_with_indices.len();
let fruit_receiver =... | identifier_body |
executor.rs | use crossbeam::channel;
use scoped_pool::{Pool, ThreadConfig};
use Result;
/// Search executor whether search request are single thread or multithread.
///
/// We don't expose Rayon thread pool directly here for several reasons.
///
/// First dependency hell. It is not a good idea to expose the
/// API of a dependency... | {
SingleThread,
ThreadPool(Pool),
}
impl Executor {
/// Creates an Executor that performs all task in the caller thread.
pub fn single_thread() -> Executor {
Executor::SingleThread
}
// Creates an Executor that dispatches the tasks in a thread pool.
pub fn multi_thread(num_threads... | Executor | identifier_name |
foodDetailsView.js | var app = app || {};
app.FoodDetailsView = Backbone.View.extend({// show food details, such as calories and food type, allow user to select how many servings they've had
el: "#food-details",
tagName: "div",
detailedTemplate: template("detailed-template"), // grab detailed item view template
initialize: functio... |
return this;
}
}); | { // initially there is no model, the model is passed when the event is triggered
this.$el.html(this.detailedTemplate(this.model.toJSON())); // renders the details of a food selected, and refreshes the view on new food selected
} | conditional_block |
foodDetailsView.js | var app = app || {};
app.FoodDetailsView = Backbone.View.extend({// show food details, such as calories and food type, allow user to select how many servings they've had
el: "#food-details",
tagName: "div",
detailedTemplate: template("detailed-template"), // grab detailed item view template
initialize: functio... |
return this;
}
}); |
} | random_line_split |
AnExChained.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule AnExChained
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
... | (props: Object) {
super(props);
this.state = {
stickers: [new Animated.ValueXY()], // 1 leader
};
var stickerConfig = {tension: 2, friction: 3}; // soft spring
for (var i = 0; i < 4; i++) { // 4 followers
var sticker = new Animated.... | constructor | identifier_name |
AnExChained.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule AnExChained
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
... | }),
Animated.spring(this.state.stickers[0], {
toValue: {x: 0, y: 0} // return to start
}),
]).start();
};
this.state.chainResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderGrant: () => {
th... | {
super(props);
this.state = {
stickers: [new Animated.ValueXY()], // 1 leader
};
var stickerConfig = {tension: 2, friction: 3}; // soft spring
for (var i = 0; i < 4; i++) { // 4 followers
var sticker = new Animated.ValueXY();
... | identifier_body |
AnExChained.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule AnExChained
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
... |
var releaseChain = (e, gestureState) => {
this.state.stickers[0].flattenOffset(); // merges offset into value and resets
Animated.sequence([ // spring to start after decay finishes
Animated.decay(this.state.stickers[0], { // coast to a stop
... | { // 4 followers
var sticker = new Animated.ValueXY();
Animated.spring(sticker, {
...stickerConfig,
toValue: this.state.stickers[i], // Animated toValue's are tracked
}).start();
this.state.stickers.push(sticker); // push on ... | conditional_block |
AnExChained.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule AnExChained
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
... | Animated.sequence([ // spring to start after decay finishes
Animated.decay(this.state.stickers[0], { // coast to a stop
velocity: {x: gestureState.vx, y: gestureState.vy},
deceleration: 0.997,
}),
Animated.spring(this.state.stickers[0]... | this.state.stickers[0].flattenOffset(); // merges offset into value and resets | random_line_split |
__main__.py | -d [input_directory] Specify the directory with the required
config and model files
-s Run simulation
-f Conduct model fitting. Must be done
after a complete run with `-s` flag... |
modelmatch = re.search(r"(?i)^model.*\.json$", fname)
if modelmatch is not None:
model_file_name = modelmatch.string
if config_file_name is None:
parser.error(
"Config file not found. "
"A valid config file name must begin with the term `config`, "
... | config_file_name = confmatch.string | conditional_block |
__main__.py | -d [input_directory] Specify the directory with the required
config and model files
-s Run simulation
-f Conduct model fitting. Must be done
after a complete run with `-s` flag... | choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
default="INFO",
help="Choose option for logging level from: \n"+
"DEBUG, INFO, WARNING, ERROR, CRITICAL.")
args = parser.parse_args()
# error handling
if args.input_directory and (args.config_file or args.model... | parser = argparse.ArgumentParser(
prog='sira', description="run sira", add_help=True)
# [Either] Supply config file and model file directly:
parser.add_argument("-c", "--config_file", type=str)
parser.add_argument("-m", "--model_file", type=str)
# [Or] Supply only the directory where the input... | identifier_body |
__main__.py | -d [input_directory] Specify the directory with the required
config and model files
-s Run simulation
-f Conduct model fitting. Must be done
after a complete run ... | # {}, # [6] hazard level vs component class dmg level pct
# {}] # [7] hazard level vs component class expected damage index
if args.simulation:
response_list = calculate_response(hazards, scenario, infrastructure)
# ----------------------------------------------------------------... | random_line_split | |
__main__.py | -d [input_directory] Specify the directory with the required
config and model files
-s Run simulation
-f Conduct model fitting. Must be done
after a complete run with `-s` flag... | ():
# define arg parser
parser = argparse.ArgumentParser(
prog='sira', description="run sira", add_help=True)
# [Either] Supply config file and model file directly:
parser.add_argument("-c", "--config_file", type=str)
parser.add_argument("-m", "--model_file", type=str)
# [Or] Supply o... | main | identifier_name |
user.service.ts | import {Injectable} from '@angular/core';
import {Headers, Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import {Store} from '@ngrx/store';
import {AppState} from './core/store';
import... |
private removeUser(): void {
this.store.dispatch(new User.Logout());
}
private handleError(error: Response): void {
if ([401, 403].indexOf(error.status) === -1) {
console.log(error);
}
this.removeUser();
}
private extractUsername(res: Response): string {
return res.json().usern... | {
this.store.dispatch(new User.Login(userName));
} | identifier_body |
user.service.ts | import {Injectable} from '@angular/core';
import {Headers, Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map'; |
@Injectable()
export class UserService {
private sessionUrl = '/session';
private loginUrl = '/login';
private logoutUrl = '/logout';
public user$: Observable<string>;
constructor(private http: Http, private store: Store<AppState>) {
this.user$ = store.select(state => state.user);
this.http.get(... | import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import {Store} from '@ngrx/store';
import {AppState} from './core/store';
import * as User from './core/store/user/user.actions'; | random_line_split |
user.service.ts | import {Injectable} from '@angular/core';
import {Headers, Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import {Store} from '@ngrx/store';
import {AppState} from './core/store';
import... |
this.removeUser();
}
private extractUsername(res: Response): string {
return res.json().username;
}
}
| {
console.log(error);
} | conditional_block |
user.service.ts | import {Injectable} from '@angular/core';
import {Headers, Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import {Store} from '@ngrx/store';
import {AppState} from './core/store';
import... | (userName: string): void {
this.store.dispatch(new User.Login(userName));
}
private removeUser(): void {
this.store.dispatch(new User.Logout());
}
private handleError(error: Response): void {
if ([401, 403].indexOf(error.status) === -1) {
console.log(error);
}
this.removeUser();
}... | storeUser | identifier_name |
config.js | /**
* @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here.
// For the complete reference:
// http://docs.ckeditor.com/#... | { name: 'forms' },
{ name: 'tools' },
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
{ name: 'others' },
'/',
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
{ name: 'styles' },
{ nam... | { name: 'insert' }, | random_line_split |
omnisharpServer.ts | else if (elapsedTime <= 1500) {
this.idleDelays += 1;
}
else if (elapsedTime <= 3000) {
this.nonFocusDelays += 1;
}
else {
this.bigDelays += 1;
}
}
public toMeasures(): {[key: string]: number} {
return {
immeda... |
private _setState(value: ServerState) : void {
if (typeof value !== 'undefined' && value !== this._state) {
this._state = value;
this._fireEvent(Events.StateChanged, this._state);
}
}
private _recordRequestDelay(requestName: string, elapsedTime: number) {
let delays = this._requestDelays[... | {
return this._state;
} | identifier_body |
omnisharpServer.ts | else if (elapsedTime <= 1500) {
this.idleDelays += 1;
}
else if (elapsedTime <= 3000) {
this.nonFocusDelays += 1;
}
else {
this.bigDelays += 1;
}
}
public toMeasures(): {[key: string]: number} {
return {
immeda... | listener = thisArg ? listener.bind(thisArg) : listener;
this._eventBus.addListener(event, listener);
return new Disposable(() => this._eventBus.removeListener(event, listener));
}
protected _fireEvent(event: string, args: any): void {
this._eventBus.emit(event, args);
}
// --- start, stop, and connect
p... | random_line_split | |
omnisharpServer.ts | else if (elapsedTime <= 1500) {
this.idleDelays += 1;
}
else if (elapsedTime <= 3000) {
this.nonFocusDelays += 1;
}
else {
this.bigDelays += 1;
}
}
public toMeasures(): {[key: string]: number} {
return {
immeda... |
}
public autoStart(preferredPath:string): Thenable<void> {
return getLaunchTargets().then(targets => {
if (targets.length === 0) {
return new Promise<void>((resolve, reject) => {
// 1st watch for files
let watcher = workspace.createFileSystemWatcher('{**/*.sln,**/project.json}', false, true, true... | {
return this.stop().then(() => {
this.start(solutionPath);
});
} | conditional_block |
omnisharpServer.ts | else if (elapsedTime <= 1500) {
this.idleDelays += 1;
}
else if (elapsedTime <= 3000) {
this.nonFocusDelays += 1;
}
else {
this.bigDelays += 1;
}
}
public toMeasures(): {[key: string]: number} {
return {
immeda... | (solutionPath: string = this._solutionPath): Promise<void> {
if (solutionPath) {
return this.stop().then(() => {
this.start(solutionPath);
});
}
}
public autoStart(preferredPath:string): Thenable<void> {
return getLaunchTargets().then(targets => {
if (targets.length === 0) {
return new Promise... | restart | identifier_name |
categoryAxis.ts | ".
*/
constructor(scale: Scales.Category, orientation: string) {
super(scale, orientation);
this.addClass("category-axis");
}
protected _setup() {
super._setup();
this._measurer = new SVGTypewriter.Measurers.CacheCharacterMeasurer(this._tickLabelContainer);
this._wrapper ... | let width = self._isHorizontal() ? bandWidth : axisWidth - self._maxLabelTickLength() - self.tickLabelPadding();
let height = self._isHorizontal() ? axisHeight - self._maxLabelTickLength() - self.tickLabelPadding() : bandWidth;
let writeOptions = {
selection: d3.select(this),
... | {
let self = this;
let xAlign: {[s: string]: string};
let yAlign: {[s: string]: string};
switch (this.tickLabelAngle()) {
case 0:
xAlign = {left: "right", right: "left", top: "center", bottom: "center"};
yAlign = {left: "center", right: "center", top: "bottom", bottom... | identifier_body |
categoryAxis.ts | ".
*/
constructor(scale: Scales.Category, orientation: string) {
super(scale, orientation);
this.addClass("category-axis");
}
protected _setup() {
super._setup();
this._measurer = new SVGTypewriter.Measurers.CacheCharacterMeasurer(this._tickLabelContainer);
this._wrapper ... | else {
widthRequiredByTicks += tierTotalHeight;
}
}
let categoryScale = <Scales.Category> this._scale;
let measureResult = this._measureTicks(offeredWidth, offeredHeight, categoryScale, categoryScale.domain());
return {
minWidth: measureResult.usedWidth + widthRequir... | {
heightRequiredByTicks += tierTotalHeight;
} | conditional_block |
categoryAxis.ts | ".
*/
constructor(scale: Scales.Category, orientation: string) {
super(scale, orientation);
this.addClass("category-axis");
}
protected _setup() {
super._setup();
this._measurer = new SVGTypewriter.Measurers.CacheCharacterMeasurer(this._tickLabelContainer);
this._wrapper ... | yAlign: yAlign[self.orientation()],
textRotation: self.tickLabelAngle()
};
self._writer.write(self.formatter()(d), width, height, writeOptions);
});
}
/**
* Measures the size of the ticks without making any (permanent) DOM
* changes.
*
* @param {str... | xAlign: xAlign[self.orientation()], | random_line_split |
categoryAxis.ts | ".
*/
| (scale: Scales.Category, orientation: string) {
super(scale, orientation);
this.addClass("category-axis");
}
protected _setup() {
super._setup();
this._measurer = new SVGTypewriter.Measurers.CacheCharacterMeasurer(this._tickLabelContainer);
this._wrapper = new SVGTypewriter.Wrappe... | constructor | identifier_name |
settings.js | module.exports = function(w)
{
var global = require('ui/common/globals');
w.barImage='images/iPhone_Nav_Bar_Bkgrd_With_Black.png';
// This is where I am going put the with all the results.
var overview = Ti.UI.createView({
width: Ti.UI.FILL,
height: Ti.UI.SIZE,
layout: 'vertical',
top: 0
});
// Creat... | left: 10,
right: 10,
backgroundColor: global.colors.dark,
backgroundImage:'none',
color: 'white',
font:{
fontFamily:'Helvetica Neue',
fontSize:18,
},
borderRadius: 5,
title: 'Logout'
});
overview.add(logout_button);
logout_button.addEventList... | height: 42, | random_line_split |
valdr-message-tests.ts | function ValdrMessageTests() {
var valdrMessage: valdr.message.ValdrMessage;
valdrMessage.templateUrl = 'valdrMesssageTemplate.html';
valdrMessage.translateAvailable = true;
valdrMessage.angularMessagesEnabled = true;
valdrMessage.setTemplate('<div class="valdr-message">{{ violation.message }}</div... | () {
var valdrMessageProvider: valdr.message.ValdrMessageProvider;
valdrMessageProvider.setTemplate('<div class="valdr-message" > {{ violation.message }}</div>');
valdrMessageProvider.setTemplateUrl('valdrMesssageTemplate.html');
valdrMessageProvider.addMessages({
'person.lastName.required': 'Th... | ValdrMessageProviderTests | identifier_name |
valdr-message-tests.ts | function ValdrMessageTests() {
var valdrMessage: valdr.message.ValdrMessage;
valdrMessage.templateUrl = 'valdrMesssageTemplate.html';
valdrMessage.translateAvailable = true;
valdrMessage.angularMessagesEnabled = true;
valdrMessage.setTemplate('<div class="valdr-message">{{ violation.message }}</div... | } | 'person.lastName.required': 'This last name is required.',
'person.age.number': 'The age has to be a number.'
});
var message = valdrMessageProvider.getMessage("person", "lastName", "required"); | random_line_split |
valdr-message-tests.ts | function ValdrMessageTests() {
var valdrMessage: valdr.message.ValdrMessage;
valdrMessage.templateUrl = 'valdrMesssageTemplate.html';
valdrMessage.translateAvailable = true;
valdrMessage.angularMessagesEnabled = true;
valdrMessage.setTemplate('<div class="valdr-message">{{ violation.message }}</div... | {
var valdrMessageProvider: valdr.message.ValdrMessageProvider;
valdrMessageProvider.setTemplate('<div class="valdr-message" > {{ violation.message }}</div>');
valdrMessageProvider.setTemplateUrl('valdrMesssageTemplate.html');
valdrMessageProvider.addMessages({
'person.lastName.required': 'This ... | identifier_body | |
order.ts | // Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
function blob(data: number[]): api.IValue {
return wrap(Buffer.from(data));
}
function resource(pathString: string): api.IValue {
return wrap(
new DocumentReference(
firestore,
QualifiedResourcePath.fromSlashSeparatedString(pathString)
)
);
}
function geopoint(lat: ... | {
const val = firestore._serializer!.encodeValue(value);
expect(val).to.not.be.null;
return val!;
} | identifier_body |
order.ts | // Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | [geopoint(0, -180)],
[geopoint(0, 0)],
[geopoint(0, 180)],
[geopoint(1, -180)],
[geopoint(1, 0)],
[geopoint(1, 180)],
[geopoint(90, -180)],
[geopoint(90, 0)],
[geopoint(90, 180)],
// arrays
[wrap([])],
[wrap(['bar'])],
[wrap(['foo'])],
... | [geopoint(-90, 180)], | random_line_split |
order.ts | // Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (n: number): api.IValue {
return {
doubleValue: n,
};
}
it('throws on invalid value', () => {
expect(() => {
order.compare(
{valueType: 'foo'} as InvalidApiUsage,
{valueType: 'foo'} as InvalidApiUsage
);
}).to.throw('Unexpected value type: foo');
});
it('throw... | double | identifier_name |
order.ts | // Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
expected = order.primitiveComparator(j, i);
expect(order.compare(right, left)).to.equal(
expected,
'comparing ' +
right +
' (' +
JSON.stringify(right) +
') to ' +
left +
'... | left of groups[i]) {
for (let j = 0; j < groups.length; j++) {
for (const right of groups[j]) {
let expected = order.primitiveComparator(i, j);
expect(order.compare(left, right)).to.equal(
expected,
'comparing ' +
left +
... | conditional_block |
lib.rs | #![deny(broken_intra_doc_links)]
//! Implementation of marshaller for rust-protobuf parameter types.
use bytes::Bytes;
use grpc::marshall::Marshaller;
use protobuf::CodedInputStream;
use protobuf::Message;
pub struct MarshallerProtobuf;
impl<M: Message> Marshaller<M> for MarshallerProtobuf {
fn write_size_est... |
fn write(&self, m: &M, _size_esimate: u32, out: &mut Vec<u8>) -> grpc::Result<()> {
m.write_to_vec(out)
.map_err(|e| grpc::Error::Marshaller(Box::new(e)))
}
fn read(&self, buf: Bytes) -> grpc::Result<M> {
// TODO: make protobuf simple
let mut is = CodedInputStream::fro... | {
// TODO: implement it
Ok(0)
} | identifier_body |
lib.rs | #![deny(broken_intra_doc_links)]
//! Implementation of marshaller for rust-protobuf parameter types.
use bytes::Bytes;
use grpc::marshall::Marshaller;
use protobuf::CodedInputStream;
use protobuf::Message;
pub struct | ;
impl<M: Message> Marshaller<M> for MarshallerProtobuf {
fn write_size_estimate(&self, _m: &M) -> grpc::Result<u32> {
// TODO: implement it
Ok(0)
}
fn write(&self, m: &M, _size_esimate: u32, out: &mut Vec<u8>) -> grpc::Result<()> {
m.write_to_vec(out)
.map_err(|e| grpc... | MarshallerProtobuf | identifier_name |
lib.rs | #![deny(broken_intra_doc_links)]
//! Implementation of marshaller for rust-protobuf parameter types.
use bytes::Bytes;
use grpc::marshall::Marshaller; |
use protobuf::CodedInputStream;
use protobuf::Message;
pub struct MarshallerProtobuf;
impl<M: Message> Marshaller<M> for MarshallerProtobuf {
fn write_size_estimate(&self, _m: &M) -> grpc::Result<u32> {
// TODO: implement it
Ok(0)
}
fn write(&self, m: &M, _size_esimate: u32, out: &mut Ve... | random_line_split | |
freq_analysis.py | #!/usr/bin/env python3
"""
Perform frequency analysis on text. This is already provided by !f, this script
exists for other reasons.
"""
import sys
import argparse
import re
from collections import Counter
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", t... |
def histogram(text, start, interval):
return Counter(re.findall("[a-zA-Z]", text)[start::interval])
if __name__ == "__main__":
args = parse_args()
plain = args.input.read()
for i in range(args.length):
print(printchart(histogram(plain, i, args.length), i, args.length))
| (_, highest), = hist.most_common(1)
highw = len(str(highest))
return ("IOC {:.4f}\nInterval [{}::{}]\n{}"
.format(IOC(hist), start, interval,
("\n".join("{!r} ({:{highw}}) {}"
.format(letter, frequency,
... | identifier_body |
freq_analysis.py | #!/usr/bin/env python3
"""
Perform frequency analysis on text. This is already provided by !f, this script
exists for other reasons.
"""
import sys
import argparse
import re
from collections import Counter
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", t... |
else:
return -1
def printchart(hist, start, interval, width=80):
(_, highest), = hist.most_common(1)
highw = len(str(highest))
return ("IOC {:.4f}\nInterval [{}::{}]\n{}"
.format(IOC(hist), start, interval,
("\n".join("{!r} ({:{highw}}) {}"
... | return (sum(freq ** 2 - freq for freq in cnt.values())
/ (total ** 2 - total)) | conditional_block |
freq_analysis.py | #!/usr/bin/env python3
"""
Perform frequency analysis on text. This is already provided by !f, this script
exists for other reasons.
"""
import sys
import argparse
import re
from collections import Counter
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", t... | (hist, start, interval, width=80):
(_, highest), = hist.most_common(1)
highw = len(str(highest))
return ("IOC {:.4f}\nInterval [{}::{}]\n{}"
.format(IOC(hist), start, interval,
("\n".join("{!r} ({:{highw}}) {}"
.format(letter, fr... | printchart | identifier_name |
freq_analysis.py | #!/usr/bin/env python3
"""
Perform frequency analysis on text. This is already provided by !f, this script
exists for other reasons.
"""
import sys
import argparse
import re
from collections import Counter
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", t... | (_, highest), = hist.most_common(1)
highw = len(str(highest))
return ("IOC {:.4f}\nInterval [{}::{}]\n{}"
.format(IOC(hist), start, interval,
("\n".join("{!r} ({:{highw}}) {}"
.format(letter, frequency,
... | def printchart(hist, start, interval, width=80): | random_line_split |
basic.js | var fs = require('fs')
var parseTorrent = require('parse-torrent')
var test = require('tape')
var WebTorrent = require('../')
var DHT = require('bittorrent-dht/client')
var parallel = require('run-parallel')
var bufferEqual = require('buffer-equal')
var leaves = fs.readFileSync(__dirname + '/torrents/leaves.torrent')
... |
var client1 = new WebTorrent({ dht: dhts[0], tracker: false })
var client2 = new WebTorrent({ dht: dhts[1], tracker: false })
client1.seed(data, { name: 'blah' }, function (torrent1) {
client2.download(torrent1.infoHash, function (torrent2) {
t.equal(torrent2.infoHash, torrent1.infoHash)
... | {
for (var j = 0; j < dhts.length; j++) {
if (i !== j) dhts[i].addNode('127.0.0.1:' + getDHTPort(dhts[j]), dhts[j].nodeId)
}
} | conditional_block |
basic.js | var fs = require('fs')
var parseTorrent = require('parse-torrent')
var test = require('tape')
var WebTorrent = require('../')
var DHT = require('bittorrent-dht/client')
var parallel = require('run-parallel')
var bufferEqual = require('buffer-equal')
var leaves = fs.readFileSync(__dirname + '/torrents/leaves.torrent')
... | t.equal(torrent2.infoHash, leavesTorrent.infoHash)
t.equal(torrent2.magnetURI, leavesMagnetURI)
client2.destroy()
})
} else {
console.log('Skipping Blob test because missing `Blob` constructor')
}
})
test('after client.destroy(), throw on client.add() or client.seed()', function (t) {
t... |
// Blob
if (typeof Blob !== 'undefined') {
var client2 = new WebTorrent({ dht: false, tracker: false })
client2.seed(new Blob([ leavesBook ]), opts, function (torrent2) { | random_line_split |
basic.js | var fs = require('fs')
var parseTorrent = require('parse-torrent')
var test = require('tape')
var WebTorrent = require('../')
var DHT = require('bittorrent-dht/client')
var parallel = require('run-parallel')
var bufferEqual = require('buffer-equal')
var leaves = fs.readFileSync(__dirname + '/torrents/leaves.torrent')
... | (dht) {
return dht.address().port
}
| getDHTPort | identifier_name |
basic.js | var fs = require('fs')
var parseTorrent = require('parse-torrent')
var test = require('tape')
var WebTorrent = require('../')
var DHT = require('bittorrent-dht/client')
var parallel = require('run-parallel')
var bufferEqual = require('buffer-equal')
var leaves = fs.readFileSync(__dirname + '/torrents/leaves.torrent')
... | {
return dht.address().port
} | identifier_body | |
merchants.test.ts | /**
* Copyright 2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | });
describe('GET /merchants', () => {
test('Should fetch a single merchant', async () => {
const expectedMerchantData = merchantFixtures.responseData?.[0];
const merchantId = expectedMerchantData.id;
const res = await request(app).get(`/merchants/${merchantId}`);
expect(res.status).t... | jest.clearAllMocks(); | random_line_split |
DocumentationCode.js | 'use strict';
/**
* Requirements
* @ignore
*/
const Documentation = require('./Documentation.js').Documentation;
/**
* @memberOf model.documentation
*/
class DocumentationCode extends Documentation
{
/**
* @inheritDoc
*/
static get className()
|
/**
* @inheritDocs
*/
get fields()
{
const fields = super.fields;
fields.visibility = 'public';
fields.namespace = '';
return fields;
}
/**
* @property {String}
*/
get namespace()
{
return this._namespace;
}
set namesp... | {
return 'model.documentation/DocumentationCode';
} | identifier_body |
DocumentationCode.js | 'use strict';
/**
* Requirements
* @ignore
*/ | /**
* @memberOf model.documentation
*/
class DocumentationCode extends Documentation
{
/**
* @inheritDoc
*/
static get className()
{
return 'model.documentation/DocumentationCode';
}
/**
* @inheritDocs
*/
get fields()
{
const fields = super.fields;
... | const Documentation = require('./Documentation.js').Documentation;
| random_line_split |
DocumentationCode.js | 'use strict';
/**
* Requirements
* @ignore
*/
const Documentation = require('./Documentation.js').Documentation;
/**
* @memberOf model.documentation
*/
class | extends Documentation
{
/**
* @inheritDoc
*/
static get className()
{
return 'model.documentation/DocumentationCode';
}
/**
* @inheritDocs
*/
get fields()
{
const fields = super.fields;
fields.visibility = 'public';
fields.namespace = ''... | DocumentationCode | identifier_name |
errors.rs | use std::error;
use std::fmt;
use std::io;
use parsed_class::FieldRef;
#[derive(Debug)]
pub enum ClassLoadingError {
NoClassDefFound(Result<String, io::Error>),
ClassFormatError(String),
UnsupportedClassVersion,
NoSuchFieldError(FieldRef),
#[allow(dead_code)]
IncompatibleClassChange,
#[allo... | } | match *self {
ClassLoadingError::NoClassDefFound(ref err) => err.as_ref().err().map(|e| e as &error::Error),
_ => None,
}
} | random_line_split |
errors.rs | use std::error;
use std::fmt;
use std::io;
use parsed_class::FieldRef;
#[derive(Debug)]
pub enum ClassLoadingError {
NoClassDefFound(Result<String, io::Error>),
ClassFormatError(String),
UnsupportedClassVersion,
NoSuchFieldError(FieldRef),
#[allow(dead_code)]
IncompatibleClassChange,
#[allo... |
fn cause(&self) -> Option<&error::Error> {
match *self {
ClassLoadingError::NoClassDefFound(ref err) => err.as_ref().err().map(|e| e as &error::Error),
_ => None,
}
}
}
| {
match *self {
ClassLoadingError::NoClassDefFound(..) => "NoClassDefFound",
ClassLoadingError::ClassFormatError(..) => "ClassFormatError",
ClassLoadingError::NoSuchFieldError(..) => "NoSuchFieldError",
ClassLoadingError::UnsupportedClassVersion => "UnsupportedCla... | identifier_body |
errors.rs | use std::error;
use std::fmt;
use std::io;
use parsed_class::FieldRef;
#[derive(Debug)]
pub enum | {
NoClassDefFound(Result<String, io::Error>),
ClassFormatError(String),
UnsupportedClassVersion,
NoSuchFieldError(FieldRef),
#[allow(dead_code)]
IncompatibleClassChange,
#[allow(dead_code)]
ClassCircularity,
}
impl fmt::Display for ClassLoadingError {
fn fmt(&self, f: &mut fmt::For... | ClassLoadingError | identifier_name |
base.py | """
Django settings for eproweb project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build path... | 'propagate': True,
},
'epro': {
'handlers': ['file'],
'level': 'WARNING',
'propagate': True,
},
'feedback': {
'handlers': ['file'],
'level': 'WARNING',
'propagate': True,
},
'app_admins': ... | 'level': 'INFO', | random_line_split |
issue-13482.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = [1,2];
let y = match x {
[] => None,
//~^ ERROR mismatched types
//~| expected `[_; 2]`
//~| found `[_; 0]`
//~| expected array with a fixed size of 2 elements
[a,_] => Some(a)
};
} | identifier_body | |
issue-13482.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let y = match x {
[] => None,
//~^ ERROR mismatched types
//~| expected `[_; 2]`
//~| found `[_; 0]`
//~| expected array with a fixed size of 2 elements
[a,_] => Some(a)
};
} |
#![feature(slice_patterns)]
fn main() {
let x = [1,2]; | random_line_split |
issue-13482.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = [1,2];
let y = match x {
[] => None,
//~^ ERROR mismatched types
//~| expected `[_; 2]`
//~| found `[_; 0]`
//~| expected array with a fixed size of 2 elements
[a,_] => Some(a)
};
}
| main | identifier_name |
index.d.ts | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
i... | export interface ParameterGroupingPostOptionalParameters {
customHeader?: string;
query?: number;
}
/**
* @class
* Initializes a new instance of the FirstParameterGroup class.
* @constructor
* Additional parameters for a set of operations, such as:
* ParameterGrouping_postMultiParamGroups,
* ParameterGroupin... | *
* @member {string} [customHeader]
* @member {number} [query] Query parameter with default. Default value: 30 .
*/ | random_line_split |
developmentMiddleware.js | import compose from 'koa-compose';
import webpack from 'webpack';
import { devMiddleware, hotMiddleware } from 'koa-webpack-middleware';
// Need to mock these files for development, because our Pug template
// will be looking for them, but they're actually all bundled up into one
// file during development with webpa... | {
console.log("Development environment, starting HMR");
const devConfig = require('../../../webpack.config.client');
const compile = webpack(devConfig);
return compose([
devMiddleware(compile, {
noInfo: true,
publicPath: devConfig.output.publicPath,
}),
hotMiddleware(compile),
]);
} | identifier_body | |
developmentMiddleware.js | import compose from 'koa-compose';
import webpack from 'webpack';
import { devMiddleware, hotMiddleware } from 'koa-webpack-middleware';
// Need to mock these files for development, because our Pug template
// will be looking for them, but they're actually all bundled up into one
// file during development with webpa... | " files for styles either)*/";
} else {
await next();
}
};
}
export function webpackMiddleware() {
console.log("Development environment, starting HMR");
const devConfig = require('../../../webpack.config.client');
const compile = webpack(devConfig);
return compose([
devMiddleware(... | if (ctx.path === '/dist/vendor.bundle.js' || ctx.path === '/dist/styles.css') {
ctx.body =
"/*Mocked files for development " +
"(not using separate bundle files for vendor" +
" and app code in development mode or separate" + | random_line_split |
developmentMiddleware.js | import compose from 'koa-compose';
import webpack from 'webpack';
import { devMiddleware, hotMiddleware } from 'koa-webpack-middleware';
// Need to mock these files for development, because our Pug template
// will be looking for them, but they're actually all bundled up into one
// file during development with webpa... | () {
return async(ctx, next) => {
if (ctx.path === '/dist/vendor.bundle.js' || ctx.path === '/dist/styles.css') {
ctx.body =
"/*Mocked files for development " +
"(not using separate bundle files for vendor" +
" and app code in development mode or separate" +
" files for style... | mockProductionStaticFiles | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.