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 |
|---|---|---|---|---|
bufferTime.ts | import { IScheduler } from '../Scheduler';
import { Action } from '../scheduler/Action';
import { Operator } from '../Operator';
import { async } from '../scheduler/async';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { is... |
let maxBufferSize: number = Number.POSITIVE_INFINITY;
if (length >= 3) {
maxBufferSize = arguments[2];
}
return function bufferTimeOperatorFunction(source: Observable<T>) {
return source.lift(new BufferTimeOperator<T>(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler));
};
}
class B... | {
bufferCreationInterval = arguments[1];
} | conditional_block |
bufferTime.ts | import { IScheduler } from '../Scheduler';
import { Action } from '../scheduler/Action';
import { Operator } from '../Operator';
import { async } from '../scheduler/async';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { is... | *
* Buffers values from the source for a specific time duration `bufferTimeSpan`.
* Unless the optional argument `bufferCreationInterval` is given, it emits and
* resets the buffer every `bufferTimeSpan` milliseconds. If
* `bufferCreationInterval` is given, this operator opens the buffer every
* `bufferCreationIn... | * <span class="informal">Collects values from the past as an array, and emits
* those arrays periodically in time.</span>
*
* <img src="./img/bufferTime.png" width="100%"> | random_line_split |
bufferTime.ts | import { IScheduler } from '../Scheduler';
import { Action } from '../scheduler/Action';
import { Operator } from '../Operator';
import { async } from '../scheduler/async';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { is... | (): Context<T> {
const context: Context<T> = new Context<T>();
this.contexts.push(context);
return context;
}
closeContext(context: Context<T>) {
this.destination.next(context.buffer);
const contexts = this.contexts;
const spliceIndex = contexts ? contexts.indexOf(context) : -1;
if (sp... | openContext | identifier_name |
group_details_view.js | var _ = require('underscore-cdb-v3');
var cdb = require('cartodb.js-v3');
var pluralizeString = require('../../../view_helpers/pluralize_string')
module.exports = cdb.core.View.extend({
initialize: function() {
_.each(['permission', 'isUsingVis'], function(name) {
if (_.isUndefined(this.options[name])) th... | } else if (this.options.isUsingVis) {
return xMembers + '. ' + pluralizeString('Member is', 'Members are', usersCount) + ' using this dataset';
} else {
return xMembers;
}
},
_willRevokeAccess: function() {
return this.options.isUsingVis && !this.options.permission.hasReadAccess(this.mo... | var usersCount = this.model.users.length;
var xMembers = pluralizeString.prefixWithCount('member', 'members', usersCount);
if (this._willRevokeAccess()) {
return xMembers + '. ' + pluralizeString("Member's", "Members'", usersCount) + ' maps will be affected'; | random_line_split |
requirejs_license_test.js | 'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actua... | var expected = grunt.file.read('test/expected/default_options');
test.equal(actual, expected, 'should describe what the default behavior is.');
*/
test.ok(true);
test.done();
},
custom_options: function(test) {
test.expect(1);
/*
var actual = grunt.file.read('tmp/custom_options');
var exp... |
/*var actual = grunt.file.read('tmp/default_options'); | random_line_split |
reporter.rs | use std::io::{self,Write};
use std::fmt::Debug;
use world_result::WorldResult;
#[derive(Debug)]
pub struct ProgressReporter;
pub trait Reporter: Debug {
fn example_failed(&self) -> Result<(), Box<::std::error::Error>>;
fn example_passed(&self) -> Result<(), Box<::std::error::Error>>;
fn report_result(&se... |
fn example_passed(&self) -> Result<(), Box<::std::error::Error>> {
print!("{}", colorize(".", Colors::Green));
io::stdout().flush().map_err(|e| e.into())
}
fn report_result(&self, result: &WorldResult) -> Result<(), Box<::std::error::Error>> {
println!("");
println!("Suite... | {
print!("{}", colorize("F", Colors::Red));
io::stdout().flush().map_err(|e| e.into())
} | identifier_body |
reporter.rs | use std::io::{self,Write};
use std::fmt::Debug;
use world_result::WorldResult;
#[derive(Debug)]
pub struct ProgressReporter;
pub trait Reporter: Debug {
fn example_failed(&self) -> Result<(), Box<::std::error::Error>>;
fn example_passed(&self) -> Result<(), Box<::std::error::Error>>;
fn report_result(&se... | };
io::stdout().flush().map_err(|e| e.into())
}
} | println!(" - {}", example);
} | random_line_split |
reporter.rs | use std::io::{self,Write};
use std::fmt::Debug;
use world_result::WorldResult;
#[derive(Debug)]
pub struct ProgressReporter;
pub trait Reporter: Debug {
fn example_failed(&self) -> Result<(), Box<::std::error::Error>>;
fn example_passed(&self) -> Result<(), Box<::std::error::Error>>;
fn report_result(&se... | {
Green,
Red,
}
fn colorize(string: &str, color: Colors) -> String {
let code = pick_code(color);
format!("\x1B[{}m{}\x1b[0m", code, string)
}
fn pick_code(color: Colors) -> &'static str {
match color {
Colors::Green => "32",
Colors::Red => "31",
}
}
impl Reporter for Progres... | Colors | identifier_name |
test_app.py | from bottle import route, default_app
app = default_app()
data = {
"id": 78874,
"seriesName": "Firefly",
"aliases": [
"Serenity"
],
"banner": "graphical/78874-g3.jpg",
"seriesId": "7097",
"status": "Ended",
"firstAired": "2002-09-20",
"network": "FOX (US)",
"networkId": "... | ():
return data
| api | identifier_name |
test_app.py | from bottle import route, default_app
app = default_app()
data = {
"id": 78874,
"seriesName": "Firefly",
"aliases": [
"Serenity"
],
"banner": "graphical/78874-g3.jpg",
"seriesId": "7097",
"status": "Ended",
"firstAired": "2002-09-20",
"network": "FOX (US)",
"networkId": "... | return data | identifier_body | |
test_app.py | from bottle import route, default_app
app = default_app()
data = {
"id": 78874,
"seriesName": "Firefly", | "seriesId": "7097",
"status": "Ended",
"firstAired": "2002-09-20",
"network": "FOX (US)",
"networkId": "",
"runtime": "45",
"genre": [
"Drama",
"Science-Fiction"
],
"overview": "In the far-distant future, Captain Malcolm \"Mal\" Reynolds is a renegade former brown-coat se... | "aliases": [
"Serenity"
],
"banner": "graphical/78874-g3.jpg", | random_line_split |
table.rs | // Copyright 2017 Robert L Snyder, Ithaca, NY <zoltatech@gmail.com>
// <robscary@gmail.com> | // you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOU... | //
// Licensed under the Apache License, Version 2.0 (the "License"); | random_line_split |
table.rs | // Copyright 2017 Robert L Snyder, Ithaca, NY <zoltatech@gmail.com>
// <robscary@gmail.com>
//
// 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
//... | else {
try!(read_table_header(self, &mut file));
}
Ok(file)
}
}
| {
try!(create_table_header(self, &mut file));
} | conditional_block |
table.rs | // Copyright 2017 Robert L Snyder, Ithaca, NY <zoltatech@gmail.com>
// <robscary@gmail.com>
//
// 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
//... | (table_name: String, path: String) -> Table {
Table{table_name: table_name, file_path: path, record_length: 0,
record_count: 0, first_record_pointer: 0, fields: vec![]}
}
pub fn open(&mut self) -> Result<File, Box<Error>> {
let path = Path::new(&self.file_path).join(&self.table_nam... | new | identifier_name |
table.rs | // Copyright 2017 Robert L Snyder, Ithaca, NY <zoltatech@gmail.com>
// <robscary@gmail.com>
//
// 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
//... |
pub fn open(&mut self) -> Result<File, Box<Error>> {
let path = Path::new(&self.file_path).join(&self.table_name);
let mut file =
OpenOptions::new().read(true).write(true).create(true).open(path)
.expect("Could not open table");
if try!(get_table_size(&mut file)) ... | {
Table{table_name: table_name, file_path: path, record_length: 0,
record_count: 0, first_record_pointer: 0, fields: vec![]}
} | identifier_body |
mod.rs | use validation::*;
use ::time::Duration;
pub mod time;
pub mod expiry;
pub mod not_before;
| /// Use positive grace periods to be lenient.
/// Use negative grace periods e.g. to renew tokens ahead of time.
pub fn claims_verifier<C,T>(tp: T, exp_grace: Duration, nbf_grace: Duration) -> ValidationSchema<C>
where C: expiry::ExpiryClaim + not_before::NotBeforeClaim + 'static,
T: time::TimePr... | /// Constructs a set of validation rules for the
/// exp and nbf claims for the type being validated.
/// Pass in exp and nbf claim grace period durations to adjust time comparisons. | random_line_split |
mod.rs | use validation::*;
use ::time::Duration;
pub mod time;
pub mod expiry;
pub mod not_before;
/// Constructs a set of validation rules for the
/// exp and nbf claims for the type being validated.
/// Pass in exp and nbf claim grace period durations to adjust time comparisons.
/// Use positive grace periods to be lenient... | <C,T>(tp: T, exp_grace: Duration, nbf_grace: Duration) -> ValidationSchema<C>
where C: expiry::ExpiryClaim + not_before::NotBeforeClaim + 'static,
T: time::TimeProvider + Clone + 'static {
let mut vs: ValidationSchema<C> = ValidationSchema::new();
vs.rule(Box::new(expiry::ExpiryVerif... | claims_verifier | identifier_name |
mod.rs | use validation::*;
use ::time::Duration;
pub mod time;
pub mod expiry;
pub mod not_before;
/// Constructs a set of validation rules for the
/// exp and nbf claims for the type being validated.
/// Pass in exp and nbf claim grace period durations to adjust time comparisons.
/// Use positive grace periods to be lenient... |
} | {
let now = UTC::now();
let tp = FixedTimeProvider(now);
let claims = JwtClaims::new();
let mut vs: ValidationSchema<JwtClaims> = claims_verifier(tp, Duration::zero(), Duration::zero());
vs.validate(&claims).unwrap();
} | identifier_body |
hdfs_space_metric_server.py | import asyncore, socket, logging, time, asynchat, os
from hdfs_space_common import get_tree_from_cache, get_child_node, TreeNode
FORMAT = '%(asctime)-15s: %(levelname)s %(module)s - %(funcName)s: %(message)s'
logging.basicConfig(format=FORMAT, level=logging.WARNING)
class ChatHandler(asynchat.async_chat):
def __ini... | (self):
self.handle_request()
def handle_request(self):
data = self.ibuffer.pop(0)
#Data should be like:
#metric:path|user|size
# OR
#db:new_path
command = data.split(":")[0]
if command == 'metric':
metric_args = data.split(":")[1].split('|')
hdfs_path = metric_args[0] if len(metric_args) > 0 el... | found_terminator | identifier_name |
hdfs_space_metric_server.py | import asyncore, socket, logging, time, asynchat, os
from hdfs_space_common import get_tree_from_cache, get_child_node, TreeNode
FORMAT = '%(asctime)-15s: %(levelname)s %(module)s - %(funcName)s: %(message)s'
logging.basicConfig(format=FORMAT, level=logging.WARNING)
class ChatHandler(asynchat.async_chat):
def __ini... |
result = get_child_node(file_tree, hdfs_path).get_size_by_user(user_name)
elif metric == "amount":
logging.info('Calculating the metric')
result = get_child_node(file_tree, hdfs_path).get_amount_by_user(user_name)
else:
logging.warning("The metric %s not implemented yet" % metric)
lo... | if metric == "size":
logging.info('Calculating the metric') | random_line_split |
hdfs_space_metric_server.py | import asyncore, socket, logging, time, asynchat, os
from hdfs_space_common import get_tree_from_cache, get_child_node, TreeNode
FORMAT = '%(asctime)-15s: %(levelname)s %(module)s - %(funcName)s: %(message)s'
logging.basicConfig(format=FORMAT, level=logging.WARNING)
class ChatHandler(asynchat.async_chat):
def __ini... |
def handle_expt(self):
logging.info("OOB detected for %s" % self)
if __name__ == '__main__':
file_tree = None
server = MetricServer()
try:
asyncore.loop()
finally:
if os.path.exists(server.sock_path):
os.unlink(server.sock_path)
| self.close()
logging.info('The socket is closed') | identifier_body |
hdfs_space_metric_server.py | import asyncore, socket, logging, time, asynchat, os
from hdfs_space_common import get_tree_from_cache, get_child_node, TreeNode
FORMAT = '%(asctime)-15s: %(levelname)s %(module)s - %(funcName)s: %(message)s'
logging.basicConfig(format=FORMAT, level=logging.WARNING)
class ChatHandler(asynchat.async_chat):
def __ini... |
elif user_name == "ALL" and metric == 'amount':
logging.info('Calculating the metric')
result = get_child_node(file_tree, hdfs_path).get_amount_for_all()
else:
if metric == "size":
logging.info('Calculating the metric')
result = get_child_node(file_tree, hdfs_path).get_size_by_user(... | logging.warning('Rather using this script try command "hdfs dfs -du /"') | conditional_block |
compareLocales.js | 'use strict';
module.exports = function(localeA, localeB, options) {
options = options || {};
if (typeof localeA !== 'object' || typeof localeB !== 'object') {
throw new Error('s18n: `localeA` and `localeB` must be objects.');
}
var localeAMissing = {};
var localeBMissing = {};
var unmodifiedStrings =... | {
var array = [];
for (var hash in resultsObj) {
array.push({
hash: hash,
string: resultsObj[hash]
});
}
return array;
} | identifier_body | |
compareLocales.js | 'use strict';
module.exports = function(localeA, localeB, options) {
options = options || {};
if (typeof localeA !== 'object' || typeof localeB !== 'object') {
throw new Error('s18n: `localeA` and `localeB` must be objects.');
}
var localeAMissing = {};
var localeBMissing = {};
var unmodifiedStrings =... | (resultsObj) {
var array = [];
for (var hash in resultsObj) {
array.push({
hash: hash,
string: resultsObj[hash]
});
}
return array;
}
| arrayifyResults | identifier_name |
compareLocales.js | 'use strict';
module.exports = function(localeA, localeB, options) {
options = options || {};
if (typeof localeA !== 'object' || typeof localeB !== 'object') {
throw new Error('s18n: `localeA` and `localeB` must be objects.');
}
var localeAMissing = {}; | for (var hashA in localeA) {
if (typeof localeB[hashA] === 'undefined') {
localeBMissing[hashA] = localeA[hashA];
} else {
if (localeA[hashA] === localeB[hashA]) {
unmodifiedStrings[hashA] = localeA[hashA];
} else {
modifiedStrings.push({
hash: hashA,
stri... | var localeBMissing = {};
var unmodifiedStrings = {};
var modifiedStrings = [];
| random_line_split |
compareLocales.js | 'use strict';
module.exports = function(localeA, localeB, options) {
options = options || {};
if (typeof localeA !== 'object' || typeof localeB !== 'object') {
throw new Error('s18n: `localeA` and `localeB` must be objects.');
}
var localeAMissing = {};
var localeBMissing = {};
var unmodifiedStrings =... |
}
}
for (var hashB in localeB) {
if (typeof localeA[hashB] === 'undefined') {
localeAMissing[hashB] = localeB[hashB];
}
}
return [
arrayifyResults(localeAMissing),
arrayifyResults(localeBMissing),
arrayifyResults(unmodifiedStrings),
modifiedStrings
];
};
function arrayify... | {
modifiedStrings.push({
hash: hashA,
strings: [
localeA[hashA],
localeB[hashA]
]
});
} | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(alloc)]
#![feature(plugin)]
#![feature(box_syntax)]
#![feature(core)]
#![feature(collections)]
#![featu... | extern crate lazy_static;
extern crate num;
extern crate util;
pub mod stylesheets;
pub mod parser;
pub mod selector_matching;
#[macro_use] pub mod values;
// Generated from the properties.mako.rs template by build.rs
#[macro_use]
pub mod properties {
include!(concat!(env!("OUT_DIR"), "/properties.rs"));
}
pub... | extern crate rustc_serialize;
extern crate string_cache;
extern crate selectors;
#[macro_use] | random_line_split |
ObservableBinding.ts | import binding = require('../interfaces');
import Binding = require('../Binding');
import core = require('../../interfaces');
/**
* The ObservableBinding class enables binding to {@link module:mayhem/Observable} objects.
*/
class | <T> extends Binding<T> {
static test(kwArgs:binding.IBindingArguments):boolean {
var object = <core.IObservable> kwArgs.object;
return object != null && typeof object.get === 'function' &&
typeof object.set === 'function' &&
typeof object.observe === 'function' &&
typeof kwArgs.path === 'string';
}
/**... | ObservableBinding | identifier_name |
ObservableBinding.ts | import binding = require('../interfaces');
import Binding = require('../Binding');
import core = require('../../interfaces'); | */
class ObservableBinding<T> extends Binding<T> {
static test(kwArgs:binding.IBindingArguments):boolean {
var object = <core.IObservable> kwArgs.object;
return object != null && typeof object.get === 'function' &&
typeof object.set === 'function' &&
typeof object.observe === 'function' &&
typeof kwArgs.... |
/**
* The ObservableBinding class enables binding to {@link module:mayhem/Observable} objects. | random_line_split |
ObservableBinding.ts | import binding = require('../interfaces');
import Binding = require('../Binding');
import core = require('../../interfaces');
/**
* The ObservableBinding class enables binding to {@link module:mayhem/Observable} objects.
*/
class ObservableBinding<T> extends Binding<T> {
static test(kwArgs:binding.IBindingArguments... |
get():T {
return this._object ? <any> this._object.get(this._property) : undefined;
}
getObject():{} {
return this._object;
}
set(value:T):void {
this._object && this._object.set(this._property, value);
}
}
export = ObservableBinding;
| {
super.destroy();
this._handle.remove();
this._handle = this._object = null;
} | identifier_body |
ExportToolView.py | # -*- coding: utf-8 -*-
import Tkinter as tk
import tkFont
import ttk
from CMApp import *
class CMExportToolView(ttk.Frame):
"""
export excel table tool view
"""
def __init__(self, root, parent, width_):
ttk.Frame.__init__(self, parent, class_="CMExportToolView", width=width_)
se... | (self):
self.ToolAdd = ttk.Button(self, text = '导出本天排表', command=self._export_this_day)
self.ToolAdd.pack(fill=tk.X, side=tk.TOP)
self.ToolDel = ttk.Button(self, text = '导出本天单影片排表', command=self._export_this_day_movie)
self.ToolDel.pack(fill=tk.X, side=tk.TOP)
self.ToolEdit = ttk... | _setup_widgets | identifier_name |
ExportToolView.py | # -*- coding: utf-8 -*-
import Tkinter as tk
import tkFont
import ttk
from CMApp import *
class CMExportToolView(ttk.Frame):
"""
export excel table tool view
"""
def __init__(self, root, parent, width_):
ttk.Frame.__init__(self, parent, class_="CMExportToolView", width=width_)
se... | self._setup_widgets()
return
def _setup_widgets(self):
self.ToolAdd = ttk.Button(self, text = '导出本天排表', command=self._export_this_day)
self.ToolAdd.pack(fill=tk.X, side=tk.TOP)
self.ToolDel = ttk.Button(self, text = '导出本天单影片排表', command=self._export_this_day_movie)
s... | random_line_split | |
ExportToolView.py | # -*- coding: utf-8 -*-
import Tkinter as tk
import tkFont
import ttk
from CMApp import *
class CMExportToolView(ttk.Frame):
"""
export excel table tool view
"""
def __init__(self, root, parent, width_):
ttk.Frame.__init__(self, parent, class_="CMExportToolView", width=width_)
se... | identifier_body | ||
test_coercion.py | """
Tests for values coercion in setitem-like operations on DataFrame.
For the most part, these should be multi-column DataFrames, otherwise
we would share the tests with Series.
"""
import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
MultiIndex,
NaT,
Series,
Times... |
A.loc[2:3, (1, slice(2, 3))] = np.ones((2, 2), dtype=np.float32)
assert (A.dtypes == np.float32).all()
A.loc[0:5, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32)
assert (A.dtypes == np.float32).all()
A.loc[:, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32)
... | A = A._consolidate() | conditional_block |
test_coercion.py | """
Tests for values coercion in setitem-like operations on DataFrame.
For the most part, these should be multi-column DataFrames, otherwise
we would share the tests with Series.
"""
import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
MultiIndex,
NaT,
Series,
Times... |
@pytest.mark.xfail(reason="Unnecessarily upcasts to float64")
def test_iloc_setitem_unnecesssary_float_upcasting():
# GH#12255
df = DataFrame(
{
0: np.array([1, 3], dtype=np.float32),
1: np.array([2, 4], dtype=np.float32),
2: ["a", "b"],
}
)
orig = ... | df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"])
df.loc[2] = Series({"a": 5, "b": 6})
assert (df.dtypes == np.int64).all()
df.loc[3] = Series({"a": 7})
# df["a"] doesn't have any NaNs, should not have been cast
exp_dtypes = Series([np.int64, np.float64], dtype=object, index=["a", "b"])
tm.... | identifier_body |
test_coercion.py | """
Tests for values coercion in setitem-like operations on DataFrame.
For the most part, these should be multi-column DataFrames, otherwise
we would share the tests with Series.
"""
import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
MultiIndex,
NaT,
Series,
Times... | # TODO: i think this isn't about MultiIndex and could be done with iloc?
def test_37477():
# fixed by GH#45121
orig = DataFrame({"A": [1, 2, 3], "B": [3, 4, 5]})
expected = DataFrame({"A": [1, 2, 3], "B": [3, 1.2, 5]})
df = orig.copy()
df.at[1, "B"] = 1.2
tm.assert_frame_equal(df, exp... | A.loc[:, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32)
assert (A.dtypes == np.float32).all()
| random_line_split |
test_coercion.py | """
Tests for values coercion in setitem-like operations on DataFrame.
For the most part, these should be multi-column DataFrames, otherwise
we would share the tests with Series.
"""
import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
MultiIndex,
NaT,
Series,
Times... | (indexer_al):
# .at case fixed by GH#45121 (best guess)
df = DataFrame(index=["A", "B", "C"])
df["D"] = 0
indexer_al(df)["C", "D"] = 2
expected = DataFrame({"D": [0, 0, 2]}, index=["A", "B", "C"], dtype=np.int64)
tm.assert_frame_equal(df, expected)
indexer_al(df)["C", "D"] = 44.5
expec... | test_26395 | identifier_name |
index.d.ts | import { Message } from "botkit";
import { Intent, Entity } from "../index";
export interface DialogFlowMessage extends Message {
/**
* The top intent of the message.
*/
topIntent: Intent,
/**
* A list of possible intents.
*/
intents: Intent[],
/**
* The entities th... | */
sessionId: string
}
/**
* The interface for DialogFlow Configuration
*/
export interface DialogFlowConfiguration {
/**
* The DialogFlow Endpoint.
*/
endpoint: string,
/**
* DialowFlow API Key.
*/
accessToken: string,
/**
* The Google Cloud Project ID.
*... | result: DialogFlowResult,
/**
* The session ID of the request. | random_line_split |
SocialIcons.tsx | import * as React from 'react'
import linkedIn from '@iconify-icons/jam/linkedin'
import gitHub from '@iconify-icons/jam/github'
import snapchat from '@iconify-icons/jam/snapchat'
import instagram from '@iconify-icons/jam/instagram' |
export default function SocialIcons() {
return (
<p
css={{
display: 'flex',
justifyContent: 'space-between',
// Prevent the icons from taking up extra vertical space
lineHeight: 1,
// The icons contain 8% padding on each side of them, causing this component to look off-center. The following f... | import Icon from '@iconify/react'
const height = 50 | random_line_split |
twoneurons.py | # -*- coding: utf-8 -*-
#
# twoneurons.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
... | nest.Connect(neuron1, neuron2, syn_spec={'weight':weight, 'delay':delay})
nest.Connect(voltmeter, neuron2)
nest.Simulate(100.0)
nest.voltage_trace.from_device(voltmeter)
nest.voltage_trace.show() | neuron1 = nest.Create("iaf_neuron")
neuron2 = nest.Create("iaf_neuron")
voltmeter = nest.Create("voltmeter")
nest.SetStatus(neuron1, {"I_e": stim}) | random_line_split |
buildRoboFabDistroFromSVN.py | """
Build the zipped robofab + dependency distros for RoboFab.
Check out fresh copies of the code from SVN.
Compile into zips.
Write optional html page.
"""
import os, glob, time
def getRevision(url):
""" Ask svn for the revision."""
cmd = "svn info \"%s\""%url
d = os.popen(cmd... |
def buildProducts(products, buildFolder=None, deleteBuilds=False, verbose=True):
""" Build the different distro products.
- checkout a clean version from svn
- add svn revision number to folder
- zip folder
"""
versions = {}
cleanup = []
filenames = [] # collect filenames ... | """ checkoutPackage"""
cwd = os.getcwd()
if not os.path.exists(stagingFolder):
os.makedirs(stagingFolder)
os.chdir(stagingFolder)
cmd = "svn export \"%s\" . --force"%(url)
d = os.popen(cmd)
if verbose:
print d.read()
else:
d.read()
d.close()
#d = os.popen("svn... | identifier_body |
buildRoboFabDistroFromSVN.py | """
Build the zipped robofab + dependency distros for RoboFab.
Check out fresh copies of the code from SVN.
Compile into zips.
Write optional html page.
"""
import os, glob, time
def getRevision(url):
""" Ask svn for the revision."""
cmd = "svn info \"%s\""%url
d = os.popen(cmd... | os.chdir(finalFolder)
d = os.popen("zip -r \"%s\" *"%finalFolder)
if verbose:
print d.read()
else:
d.read()
cleanup.append(finalFolder)
d.close()
if deleteBuilds:
for path in cleanup:
if verbose:
print "clea... | print d.read()
else:
d.read() | random_line_split |
buildRoboFabDistroFromSVN.py | """
Build the zipped robofab + dependency distros for RoboFab.
Check out fresh copies of the code from SVN.
Compile into zips.
Write optional html page.
"""
import os, glob, time
def getRevision(url):
""" Ask svn for the revision."""
cmd = "svn info \"%s\""%url
d = os.popen(cmd... | (url, stagingFolder, verbose=True):
""" checkoutPackage"""
cwd = os.getcwd()
if not os.path.exists(stagingFolder):
os.makedirs(stagingFolder)
os.chdir(stagingFolder)
cmd = "svn export \"%s\" . --force"%(url)
d = os.popen(cmd)
if verbose:
print d.read()
else:
d.rea... | checkoutPackage | identifier_name |
buildRoboFabDistroFromSVN.py | """
Build the zipped robofab + dependency distros for RoboFab.
Check out fresh copies of the code from SVN.
Compile into zips.
Write optional html page.
"""
import os, glob, time
def getRevision(url):
""" Ask svn for the revision."""
cmd = "svn info \"%s\""%url
d = os.popen(cmd... |
else:
d.read()
cleanup.append(finalFolder)
d.close()
if deleteBuilds:
for path in cleanup:
if verbose:
print "cleaning", path
d = os.popen("rm -r \"%s\""%(path))
if verbose:
print d.read()
e... | print d.read() | conditional_block |
index.js | const Koa = require('koa')
const screenshot = require('./screenshot')
const app = new Koa()
app.use(async ctx => {
var url = ctx.query.url
console.log('goto:', url)
if (!/^https?:\/\/.+/.test(url)) {
ctx.body = 'url 不合法'
} else {
if (!isNaN(ctx.query.wait)) {
ctx.query.wait = ~~ctx.query.wait
... |
app.listen(8000)
console.log('server start success at 8000')
// process.on('unCaughtException', function (err) {
// console.log(err)
// }) | random_line_split | |
index.js | const Koa = require('koa')
const screenshot = require('./screenshot')
const app = new Koa()
app.use(async ctx => {
var url = ctx.query.url
console.log('goto:', url)
if (!/^https?:\/\/.+/.test(url)) {
ctx.body = 'url 不合法'
} else {
if (!isNaN(ctx.query.wait)) {
ctx.query.wait = ~~ctx.query.wait
... | )
app.listen(8000)
console.log('server start success at 8000')
// process.on('unCaughtException', function (err) {
// console.log(err)
// })
| ctx.body = `<img src="data:image/jpeg;base64,${data}" />`
}
}
} | conditional_block |
job.rs | use ckb_jsonrpc_types::BlockTemplate;
use ckb_types::packed::Block;
use ckb_types::{
prelude::*,
utilities::compact_to_target,
};
use ckb_types::{H256, U256};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::time::Instant;
#[derive(Clone, Serialize)]
pub struct MiningJob... |
pub fn on_solved_share(&self, solved_share: &SolvedShare) -> Option<&MiningJob> {
self.jobs.get(&solved_share.pow_hash)
}
fn insert_job(&mut self, job: &MiningJob) {
if let Some(old_hash) = self
.hashes
.insert(job.job_time.clone(), job.pow_hash.clone())
{
... | {
let job: MiningJob = block_template.into();
self.insert_job(&job);
self.clean_jobs();
job
} | identifier_body |
job.rs | use ckb_jsonrpc_types::BlockTemplate;
use ckb_types::packed::Block;
use ckb_types::{
prelude::*,
utilities::compact_to_target,
};
use ckb_types::{H256, U256};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::time::Instant;
#[derive(Clone, Serialize)]
pub struct MiningJob... | .map(|(job_time, hash)| (job_time.clone(), hash.clone()))
.collect();
removables.iter().for_each(|(job_time, hash)| {
self.hashes.remove(job_time);
self.jobs.remove(hash);
})
}
} | .take(self.hashes.len().saturating_sub(256)) | random_line_split |
job.rs | use ckb_jsonrpc_types::BlockTemplate;
use ckb_types::packed::Block;
use ckb_types::{
prelude::*,
utilities::compact_to_target,
};
use ckb_types::{H256, U256};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::time::Instant;
#[derive(Clone, Serialize)]
pub struct MiningJob... | (&mut self, block_template: BlockTemplate) -> MiningJob {
let job: MiningJob = block_template.into();
self.insert_job(&job);
self.clean_jobs();
job
}
pub fn on_solved_share(&self, solved_share: &SolvedShare) -> Option<&MiningJob> {
self.jobs.get(&solved_share.pow_hash)
... | on_block_template | identifier_name |
job.rs | use ckb_jsonrpc_types::BlockTemplate;
use ckb_types::packed::Block;
use ckb_types::{
prelude::*,
utilities::compact_to_target,
};
use ckb_types::{H256, U256};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::time::Instant;
#[derive(Clone, Serialize)]
pub struct MiningJob... |
if let Some(old_job) = self.jobs.insert(job.pow_hash.clone(), job.clone()) {
self.hashes.remove(&old_job.job_time);
}
}
fn clean_jobs(&mut self) {
let removables: Vec<(Instant, H256)> = self
.hashes
.iter()
.take(self.hashes.len().saturat... | {
self.jobs.remove(&old_hash);
} | conditional_block |
fileGetNodeFilePropertiesFromComputeNodeOptions.js | /*
* 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.
*/
... |
/**
* Defines the metadata of FileGetNodeFilePropertiesFromComputeNodeOptions
*
* @returns {object} metadata of FileGetNodeFilePropertiesFromComputeNodeOptions
*
*/
FileGetNodeFilePropertiesFromComputeNodeOptions.prototype.mapper = function () {
return {
required: false,
type: {
name: 'Composite'... | {
} | identifier_body |
fileGetNodeFilePropertiesFromComputeNodeOptions.js | /*
* 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.
*/
... | () {
}
/**
* Defines the metadata of FileGetNodeFilePropertiesFromComputeNodeOptions
*
* @returns {object} metadata of FileGetNodeFilePropertiesFromComputeNodeOptions
*
*/
FileGetNodeFilePropertiesFromComputeNodeOptions.prototype.mapper = function () {
return {
required: false,
type: {
name: 'Comp... | FileGetNodeFilePropertiesFromComputeNodeOptions | identifier_name |
fileGetNodeFilePropertiesFromComputeNodeOptions.js | /*
* 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.
*/
... | * processing the request, in seconds. The default is 30 seconds. Default
* value: 30 .
*
* @member {string} [clientRequestId] The caller-generated request identity,
* in the form of a GUID with no decoration such as curly braces, e.g.
* 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
*
* @member {boolean} [returnClient... | * Additional parameters for the File_getNodeFilePropertiesFromComputeNode
* operation.
*
* @member {number} [timeout] The maximum time that the server can spend | random_line_split |
issue-21475.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 ... | m::START..=m::END => {},
0..=m::END => {},
m::START..=59 => {},
_ => {},
}
}
mod m {
pub const START: u32 = 4;
pub const END: u32 = 14;
} | use m::{START, END};
fn main() {
match 42 { | random_line_split |
issue-21475.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 ... | ,
}
}
mod m {
pub const START: u32 = 4;
pub const END: u32 = 14;
}
| {} | conditional_block |
issue-21475.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 ... | () {
match 42 {
m::START..=m::END => {},
0..=m::END => {},
m::START..=59 => {},
_ => {},
}
}
mod m {
pub const START: u32 = 4;
pub const END: u32 = 14;
}
| main | identifier_name |
issue-21475.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 ... |
mod m {
pub const START: u32 = 4;
pub const END: u32 = 14;
}
| {
match 42 {
m::START..=m::END => {},
0..=m::END => {},
m::START..=59 => {},
_ => {},
}
} | identifier_body |
AuthTokenProvider.js | "use strict";
/**
* Copyright 2017 Google Inc.
* | * You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See ... | * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. | random_line_split |
AuthTokenProvider.js | "use strict";
/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law ... | (app_) {
this.app_ = app_;
}
/**
* @param {boolean} forceRefresh
* @return {!Promise<FirebaseAuthTokenData>}
*/
AuthTokenProvider.prototype.getToken = function (forceRefresh) {
return this.app_['INTERNAL']['getToken'](forceRefresh).then(null,
// .catch
functio... | AuthTokenProvider | identifier_name |
AuthTokenProvider.js | "use strict";
/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law ... |
/**
* @param {boolean} forceRefresh
* @return {!Promise<FirebaseAuthTokenData>}
*/
AuthTokenProvider.prototype.getToken = function (forceRefresh) {
return this.app_['INTERNAL']['getToken'](forceRefresh).then(null,
// .catch
function (error) {
// TODO: Need to... | {
this.app_ = app_;
} | identifier_body |
hooks.py | # -*- coding: utf-8 -*-
# Copyright 2014 Nicolas Bessi, Alexandre Fayolle, Camptocamp SA
# Copyright 2016 Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
def post_init_hook(cr, registry):
""" Add street3 to address format """
query = """
UPDATE res_country
SET address_f... | """
cr.execute(query)
| """ Remove street3 from address format """
# Remove %(street3)s\n from address_format
query = """
UPDATE res_country
SET address_format = replace(
address_format,
E'%(street3)s\n',
''
)
"""
cr.execute(query)
# Remove %(street3)s from address_format
... | identifier_body |
hooks.py | # -*- coding: utf-8 -*-
# Copyright 2014 Nicolas Bessi, Alexandre Fayolle, Camptocamp SA
# Copyright 2016 Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
def post_init_hook(cr, registry):
""" Add street3 to address format """
query = """
UPDATE res_country
SET address_f... | address_format,
E'%(street3)s\n',
''
)
"""
cr.execute(query)
# Remove %(street3)s from address_format
query = """
UPDATE res_country
SET address_format = replace(
address_format,
E'%(street3)s',
''
)
"""
cr.execute(... | """ Remove street3 from address format """
# Remove %(street3)s\n from address_format
query = """
UPDATE res_country
SET address_format = replace( | random_line_split |
hooks.py | # -*- coding: utf-8 -*-
# Copyright 2014 Nicolas Bessi, Alexandre Fayolle, Camptocamp SA
# Copyright 2016 Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
def post_init_hook(cr, registry):
""" Add street3 to address format """
query = """
UPDATE res_country
SET address_f... | (cr, registry):
""" Remove street3 from address format """
# Remove %(street3)s\n from address_format
query = """
UPDATE res_country
SET address_format = replace(
address_format,
E'%(street3)s\n',
''
)
"""
cr.execute(query)
# Remove %(street3)s fr... | uninstall_hook | identifier_name |
utils.py | 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 License for the specific language gover... |
for key, value in env_variables.iteritems():
if posix:
f.write('export {0}={1}'.format(key, value))
f.write(linesep)
else:
f.write('set {0}={1}'.format(key, value))
f.write(linesep)
f.write(linesep)
return dest... | f.write('rem Environmnet file generated by Cloudify. Do not '
'delete unless you know exactly what you are doing.')
f.write(linesep) | conditional_block |
utils.py | 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 License for the specific language gover... |
@staticmethod
def get_storage_directory(username=None):
"""
Retrieve path to the directory where all daemon
registered under a specific username will be stored.
:param username: the user
"""
return os.path.join(get_home_dir(username), '.cfy-agent')
@sta... | """
Return the user the current daemon is running under
"""
return os.environ[cls.CLOUDIFY_DAEMON_USER_KEY] | identifier_body |
utils.py | _agent
from cloudify_agent import VIRTUALENV
from cloudify_agent.api import defaults
logger = setup_logger('cloudify_agent.api.utils')
class _Internal(object):
"""
Contains various internal utility methods. Import this at your own
peril, as backwards compatibility is not guaranteed.
"""
CLOUDIF... | :param content: the string to load
""" | random_line_split | |
utils.py | # distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
import uuid
import json
import copy
import tempfile
import os
im... | json_load | identifier_name | |
ants.js | import * as util from '../src/utils.js'
import World from '../src/World.js'
import Color from '../src/Color.js'
import ColorMap from '../src/ColorMap.js'
import ThreeView from '../src/ThreeView.js'
const params = util.RESTapi({
seed: false,
population: 100,
maxX: 30,
maxY: 30,
steps: 500,
shape... | // if (p.isNest) return nestColor.pixel
// if (p.isFood) return foodColor.pixel
// const color =
// p.foodPheromone > p.nestPheromone
// ? foodColorMap.scaleColor(p.foodPheromone, 0, 1)
// : nestColorMap.scaleColor(p.nestPheromone, 0, 1)
// ret... | // model.step()
// view.drawPatches(model.patches, p => { | random_line_split |
ace-background_tokenizer-tests.ts | /// <reference path="../ace.d.ts" />
function forceTokenize(session) {
for (var i = 0, l = session.getLength(); i < l; i++)
session.getTokens(i)
}
function testStates(session, states) {
for (var i = 0, l = session.getLength(); i < l; i++) | assert.equal(session.bgTokenizer.states[i], states[i])
assert.ok(l == states.length)
}
exports = {
"test background tokenizer update on session change": function() {
var doc = new AceAjax.EditSession([
"/*",
"*/",
"var juhu"
]);
doc.setMode("... | random_line_split | |
ace-background_tokenizer-tests.ts | /// <reference path="../ace.d.ts" />
function | (session) {
for (var i = 0, l = session.getLength(); i < l; i++)
session.getTokens(i)
}
function testStates(session, states) {
for (var i = 0, l = session.getLength(); i < l; i++)
assert.equal(session.bgTokenizer.states[i], states[i])
assert.ok(l == states.length)
}
exports = {
"test ... | forceTokenize | identifier_name |
ace-background_tokenizer-tests.ts | /// <reference path="../ace.d.ts" />
function forceTokenize(session) |
function testStates(session, states) {
for (var i = 0, l = session.getLength(); i < l; i++)
assert.equal(session.bgTokenizer.states[i], states[i])
assert.ok(l == states.length)
}
exports = {
"test background tokenizer update on session change": function() {
var doc = new AceAjax.EditSess... | {
for (var i = 0, l = session.getLength(); i < l; i++)
session.getTokens(i)
} | identifier_body |
v1.py | # Copyright (c) 2014 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
def get(self):
return self.JSON_HOME
| super(DefaultV1Controller, self).__init__(manager)
self.JSON_HOME = JSON_HOME | identifier_body |
v1.py | # Copyright (c) 2014 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | "GET"
],
"formats": {
"application/json": {}
}
}
}
}
}
class DefaultV1Controller(base.V1Controller):
def __init__(self, manager):
super(DefaultV1Controller, self).__init__(manager)
self... | "hints": {
"allow": [ | random_line_split |
v1.py | # Copyright (c) 2014 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | (self):
return self.JSON_HOME
| get | identifier_name |
test_rdbit.py | import unittest
import StringIO
from packetsexample import PacketsExample
from prers import RdBit
class TestRdBit(unittest.TestCase):
def reinit(self):
self.__stringbuffer1 = StringIO.StringIO()
self.__p1 = RdBit(self.__stringbuffer1)
def data_example(self):
data = PacketsExample()
... | def test_data_example(self):
self.reinit()
example = self.data_example()
for packet in example:
self.__p1(packet)
result = self.__p1.get_data()
for rdbit in example.get_information('rdBit'):
self.assertTrue(rdbit in result)
self.assertEq... | random_line_split | |
test_rdbit.py | import unittest
import StringIO
from packetsexample import PacketsExample
from prers import RdBit
class TestRdBit(unittest.TestCase):
def reinit(self):
self.__stringbuffer1 = StringIO.StringIO()
self.__p1 = RdBit(self.__stringbuffer1)
def data_example(self):
data = PacketsExample()
... | (self):
self.reinit()
example = self.data_example()
for packet in example:
self.__p1(packet)
result = self.__p1.get_data()
for rdbit in example.get_information('rdBit'):
self.assertTrue(rdbit in result)
self.assertEquals(example.expected_val... | test_data_example | identifier_name |
test_rdbit.py | import unittest
import StringIO
from packetsexample import PacketsExample
from prers import RdBit
class TestRdBit(unittest.TestCase):
def reinit(self):
self.__stringbuffer1 = StringIO.StringIO()
self.__p1 = RdBit(self.__stringbuffer1)
def data_example(self):
data = PacketsExample()
... |
data.set_expected("set", 5)
data.put_information('rdBit', ["set"])
return data
def test_data_example(self):
self.reinit()
example = self.data_example()
for packet in example:
self.__p1(packet)
result = self.__p1.get_data()
for rdbit... | data.add_packet({'flags': '0', 'queries': [
{'qname': 'www.nic.cl'}]}) | conditional_block |
test_rdbit.py | import unittest
import StringIO
from packetsexample import PacketsExample
from prers import RdBit
class TestRdBit(unittest.TestCase):
def reinit(self):
self.__stringbuffer1 = StringIO.StringIO()
self.__p1 = RdBit(self.__stringbuffer1)
def data_example(self):
data = PacketsExample()
... | self.reinit()
example = self.data_example()
for packet in example:
self.__p1(packet)
result = self.__p1.get_data()
for rdbit in example.get_information('rdBit'):
self.assertTrue(rdbit in result)
self.assertEquals(example.expected_value(rdbit), resul... | identifier_body | |
sync_provider.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... |
}
| {
map![
1.into() => TransactionStats {
first_seen: 10,
propagated_to: map![
128.into() => 16
],
},
5.into() => TransactionStats {
first_seen: 16,
propagated_to: map![
16.into() => 1
],
}
]
} | identifier_body |
sync_provider.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... |
//! Test implementation of SyncProvider.
use std::collections::BTreeMap;
use bigint::hash::H256;
use parking_lot::RwLock;
use ethsync::{SyncProvider, EthProtocolInfo, SyncStatus, SyncState, PeerInfo, TransactionStats};
/// TestSyncProvider config.
pub struct Config {
/// Protocol version.
pub network_id: u64,
///... |
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. | random_line_split |
sync_provider.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... | (&self, count: u64) {
let mut status = self.status.write();
let current_number = status.last_imported_block_number.unwrap_or(0);
status.last_imported_block_number = Some(current_number + count);
}
}
impl SyncProvider for TestSyncProvider {
fn status(&self) -> SyncStatus {
self.status.read().clone()
}
fn ... | increase_imported_block_number | identifier_name |
findbugs.py | # Copyright 2012 John Kleint
# This is free software, licensed under the MIT License; see LICENSE.txt.
"""
Parse FindBugs -xml:withMessages output.
FindBugs XML output is pretty straightforward: a sequence of <BugInstance> tags,
with type and rank (severity) attributes. Each has one or more <SourceLine>
tags; if mor... |
from xml.etree import ElementTree
from itertools import ifilter
from blamethrower import Analyne
__all__ = ['analyze', 'HELP', 'OPTIONS']
HELP = 'FindBugs -xml:withMessages'
OPTIONS = {'prefix': 'add path prefix to FindBugs filenames'}
def rank2severity(rank):
""":Return: the BlameThrower severity for a bug of... | sometimes outputs duplicate bugs.
""" | random_line_split |
findbugs.py | # Copyright 2012 John Kleint
# This is free software, licensed under the MIT License; see LICENSE.txt.
"""
Parse FindBugs -xml:withMessages output.
FindBugs XML output is pretty straightforward: a sequence of <BugInstance> tags,
with type and rank (severity) attributes. Each has one or more <SourceLine>
tags; if mor... | """:Return: an iterable of :class:`Analyne` objects read from FindBugs
-xml:withMessages file `bugsfile`.
:param str prefix: A path prefix to prepend to every filename.
"""
for _, bug in ifilter(lambda event_elt: event_elt[1].tag == 'BugInstance', ElementTree.iterparse(bugsfile)):
bugtype = bug... | identifier_body | |
findbugs.py | # Copyright 2012 John Kleint
# This is free software, licensed under the MIT License; see LICENSE.txt.
"""
Parse FindBugs -xml:withMessages output.
FindBugs XML output is pretty straightforward: a sequence of <BugInstance> tags,
with type and rank (severity) attributes. Each has one or more <SourceLine>
tags; if mor... | (rank):
""":Return: the BlameThrower severity for a bug of the given `rank`."""
if 1 <= rank <= 4:
return 'high'
elif rank <= 12:
return 'med'
elif rank <= 20:
return 'low'
else:
assert False
def analyze(bugsfile, prefix=''):
""":Return: an iterable of :class:`A... | rank2severity | identifier_name |
findbugs.py | # Copyright 2012 John Kleint
# This is free software, licensed under the MIT License; see LICENSE.txt.
"""
Parse FindBugs -xml:withMessages output.
FindBugs XML output is pretty straightforward: a sequence of <BugInstance> tags,
with type and rank (severity) attributes. Each has one or more <SourceLine>
tags; if mor... | bugtype = bug.get('type')
severity = rank2severity(int(bug.get('rank')))
sourcelines = bug.findall('SourceLine')
assert sourcelines, "No SourceLine for bug: {}".format(bug.attrib)
if len(sourcelines) > 1:
sourcelines = [line for line in sourcelines if line.attrib.get('primary... | conditional_block | |
jquery.highlight.js | /*
* jQuery Highlight plugin
*
* Based on highlight v3 by Johann Burkard
* http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
*
* Code a little bit refactored and cleaned (in my humble opinion).
* Most important changes:
* - has an option to highlight o... | ;
| {
var rExps=[
{re:/[\xC0-\xC6]/g, ch:'A'},
{re:/[\xE0-\xE6]/g, ch:'a'},
{re:/[\xC8-\xCB]/g, ch:'E'},
{re:/[\xE8-\xEB]/g, ch:'e'},
{re:/[\xCC-\xCF]/g, ch:'I'},
{re:/[\xEC-\xEF]/g, ch:'i'},
{re:/[\xD2-\xD6]/g, ch:'O'},
{re:/[\xF2-\xF6]/g, ch... | identifier_body |
jquery.highlight.js | /*
* jQuery Highlight plugin
*
* Based on highlight v3 by Johann Burkard
* http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
*
* Code a little bit refactored and cleaned (in my humble opinion).
* Most important changes:
* - has an option to highlight o... | else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
!/(script|style)/i.test(node.tagName) && // ignore script and style nodes
!(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
... | {
//var match = node.data.match(re);
var match = stripAccents(node.data).match(re);
if (match) {
var highlight = document.createElement(nodeName || 'span');
highlight.className = className || 'highlight';
var wordNode = node.splitText(match.inde... | conditional_block |
jquery.highlight.js | /*
* jQuery Highlight plugin
*
* Based on highlight v3 by Johann Burkard
* http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
*
* Code a little bit refactored and cleaned (in my humble opinion).
* Most important changes:
* - has an option to highlight o... | (str) {
var rExps=[
{re:/[\xC0-\xC6]/g, ch:'A'},
{re:/[\xE0-\xE6]/g, ch:'a'},
{re:/[\xC8-\xCB]/g, ch:'E'},
{re:/[\xE8-\xEB]/g, ch:'e'},
{re:/[\xCC-\xCF]/g, ch:'I'},
{re:/[\xEC-\xEF]/g, ch:'i'},
{re:/[\xD2-\xD6]/g, ch:'O'},
{re:/[\xF2-\xF6]... | stripAccents | identifier_name |
jquery.highlight.js | /*
* jQuery Highlight plugin
*
* Based on highlight v3 by Johann Burkard
* http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
*
* Code a little bit refactored and cleaned (in my humble opinion).
* Most important changes:
* - has an option to highlight o... | wordNode.parentNode.replaceChild(highlight, wordNode);
return 1; //skip added node in parent
}
} else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
!/(script|style)/i.test(node.tagName) && // ignore script and... | highlight.appendChild(wordClone); | random_line_split |
process_mutex.rs | #[cfg(not(target_os = "windows"))]
use std::path::PathBuf;
#[cfg(not(target_os = "windows"))]
extern crate nix;
#[cfg(not(target_os = "windows"))]
use self::nix::fcntl::FcntlArg::F_SETLK;
#[cfg(not(target_os = "windows"))]
use self::nix::fcntl::{flock, FlockArg};
#[cfg(not(target_os = "windows"))]
use self::nix::fcnt... | {
handle: std::os::windows::raw::HANDLE,
}
#[cfg(target_os = "windows")]
fn create_mutex(name: &str) -> Result<ProcessMutex, String> {
let name: Vec<u16> = OsStr::new(name)
.encode_wide()
.chain(Some(0))
.collect::<Vec<_>>();
let (err, mutie) = unsafe {
let mutie = CreateMutexW(
ptr::null_mut(),
win... | ProcessMutex | identifier_name |
process_mutex.rs | #[cfg(not(target_os = "windows"))]
use std::path::PathBuf;
#[cfg(not(target_os = "windows"))]
extern crate nix;
#[cfg(not(target_os = "windows"))]
use self::nix::fcntl::FcntlArg::F_SETLK;
#[cfg(not(target_os = "windows"))]
use self::nix::fcntl::{flock, FlockArg};
#[cfg(not(target_os = "windows"))]
use self::nix::fcnt... | use self::nix::unistd;
#[cfg(not(target_os = "windows"))]
use std::os::unix::io::RawFd;
use util;
#[derive(Debug)]
#[cfg(not(target_os = "windows"))]
pub struct ProcessMutex {
handle: RawFd,
}
#[cfg(not(target_os = "windows"))]
fn create_mutex(name: &str) -> Result<ProcessMutex, String> {
let path = format!("/tmp/... | use self::nix::sys::stat::S_IWUSR;
#[cfg(not(target_os = "windows"))] | random_line_split |
process_mutex.rs | #[cfg(not(target_os = "windows"))]
use std::path::PathBuf;
#[cfg(not(target_os = "windows"))]
extern crate nix;
#[cfg(not(target_os = "windows"))]
use self::nix::fcntl::FcntlArg::F_SETLK;
#[cfg(not(target_os = "windows"))]
use self::nix::fcntl::{flock, FlockArg};
#[cfg(not(target_os = "windows"))]
use self::nix::fcnt... | {
// convert name into a filename
let name = util::canon_path(name);
let name = name.replace("/", "_").replace(":", "_").replace(" ", "_");
let name = format!("greycrypt_mutex_{}", name);
create_mutex(&name)
} | identifier_body | |
test_orthography.py | # Copyright (c) 2013 Hesky Fisher
# See LICENSE.txt for details.
from orthography import add_suffix
import unittest
class OrthographyTestCase(unittest.TestCase):
def test_add_suffix(self):
cases = (
('artistic', 'ly', 'artistically'),
('cosmetic', 'ly', 'cosmetically'),
... |
for word, suffix, expected in failed:
print 'add_suffix(%s, %s) is %s not %s' % (word, suffix, add_suffix(word, suffix),expected)
self.assertEqual(len(failed), 0)
if __name__ == '__main__':
unittest.main() | failed.append((word, suffix, expected)) | conditional_block |
test_orthography.py | # Copyright (c) 2013 Hesky Fisher
# See LICENSE.txt for details.
from orthography import add_suffix
import unittest
class OrthographyTestCase(unittest.TestCase):
def test_add_suffix(self):
| ('pharmacy', 'ist', 'pharmacist'),
('melody', 'ist', 'melodist'),
('pacify', 'ist', 'pacifist'),
('geology', 'ist', 'geologist'),
('metallurgy', 'ist', 'metallurgist'),
('anarchy', 'ist', 'anarchist'),
('monopoly', 'ist', 'monopolist'),... | cases = (
('artistic', 'ly', 'artistically'),
('cosmetic', 'ly', 'cosmetically'),
('establish', 's', 'establishes'),
('speech', 's', 'speeches'),
('approach', 's', 'approaches'),
('beach', 's', 'beaches'),
('arch', 's', 'arches... | identifier_body |
test_orthography.py | # Copyright (c) 2013 Hesky Fisher
# See LICENSE.txt for details.
from orthography import add_suffix
import unittest
class OrthographyTestCase(unittest.TestCase):
def test_add_suffix(self):
cases = (
('artistic', 'ly', 'artistically'),
('cosmetic', 'ly', 'cosmetically'),
... | ('animate', 'ors', 'animators'),
('discontinue', 'ation', 'discontinuation'),
('innovate', 'ive', 'innovative'),
('future', 'ists', 'futurists'),
('illustrate', 'or', 'illustrator'),
('emerge', 'ent', 'emergent'),
('equip', 'ed', 'equip... | ('analyze', 'ed', 'analyzed'),
('narrate', 'ing', 'narrating'),
('believe', 'able', 'believable'), | random_line_split |
test_orthography.py | # Copyright (c) 2013 Hesky Fisher
# See LICENSE.txt for details.
from orthography import add_suffix
import unittest
class | (unittest.TestCase):
def test_add_suffix(self):
cases = (
('artistic', 'ly', 'artistically'),
('cosmetic', 'ly', 'cosmetically'),
('establish', 's', 'establishes'),
('speech', 's', 'speeches'),
('approach', 's', 'approaches'),
... | OrthographyTestCase | identifier_name |
index_hammer1.js | t = db.index_hammer1;
t.drop();
for ( i=0; i<10000; i++ )
t.insert( { x : i , y : i } );
db.getLastError();
ops = []
for ( i=0; i<50; i++ )
ops.push( { op : "find" , ns : t.getFullName() , query : { x : { $gt : 5000 } , y : { $gt : 5000 } } } )
ops[10] = { op : "createIndex" , ns : t.getFullName() , key : ... | assert.eq( 10000 , t.count() ); | random_line_split | |
main.rs | fn main() {
let mut my_struct = MyStruct {
my_field1: 0,
my_field2: 0,
my_field3: 0,
my_field4: 0,
my_field5: 0,
};
my_struct.my_field1 = 7;
assert_eq!(7, my_struct.my_field1);
assert_eq!(0, my_struct.my_field2);
assert_eq!(0, my_struct.my_field3);
a... | {
my_field1: i32,
my_field2: i32,
my_field3: i32,
my_field4: i32,
my_field5: i32,
}
struct MyTupleStruct(i32, i32, f32);
| MyStruct | identifier_name |
main.rs | fn main() {
let mut my_struct = MyStruct {
my_field1: 0,
my_field2: 0,
my_field3: 0,
my_field4: 0,
my_field5: 0,
};
my_struct.my_field1 = 7;
assert_eq!(7, my_struct.my_field1);
assert_eq!(0, my_struct.my_field2);
assert_eq!(0, my_struct.my_field3);
a... | my_field4: i32,
my_field5: i32,
}
struct MyTupleStruct(i32, i32, f32); |
struct MyStruct {
my_field1: i32,
my_field2: i32,
my_field3: i32, | random_line_split |
main.rs | fn main() | assert_eq!(7, my_struct2.my_field1);
assert_eq!(0, my_struct2.my_field2);
assert_eq!(5, my_struct2.my_field3);
assert_eq!(0, my_struct2.my_field4);
assert_eq!(0, my_struct2.my_field5);
let my_tuple_struct = MyTupleStruct(7, 42, 3.14);
assert_eq!(7, my_tuple_struct.0);
assert_eq!(42, my_... | {
let mut my_struct = MyStruct {
my_field1: 0,
my_field2: 0,
my_field3: 0,
my_field4: 0,
my_field5: 0,
};
my_struct.my_field1 = 7;
assert_eq!(7, my_struct.my_field1);
assert_eq!(0, my_struct.my_field2);
assert_eq!(0, my_struct.my_field3);
assert_eq!(... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.