file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
pushNotificationService.js | var firebase = require("unirest"); | var config = require("config");
var async = require("async");
function buildMessage (message, deviceFirebaseId) {
return {
data: message,
to: deviceFirebaseId
};
}
module.exports = {
findActiveFirabseIds (user) {
if (!user || !user.firebaseInstanceIds) {
logger.warn("[firebaseService.findActiv... | var logger = require("../log/logger"); | random_line_split |
pushNotificationService.js | var firebase = require("unirest");
var logger = require("../log/logger");
var config = require("config");
var async = require("async");
function buildMessage (message, deviceFirebaseId) {
return {
data: message,
to: deviceFirebaseId
};
}
module.exports = {
findActiveFirabseIds (user) {
if (!user || ... |
};
| {
var activeDFireBaseIds = this.findActiveFirabseIds(user);
this.sendMessageToDevices(message, activeDFireBaseIds, callback);
} | identifier_body |
lib.rs | use std::fs::File;
use std::path::Path;
use std::str::FromStr;
use std::io::BufReader;
use std::io::prelude::*;
use std::collections::HashMap;
use std::cmp::Ordering;
enum GameResult {
Win,
Loss,
Draw,
}
struct Game {
team1: String,
team2: String,
result: GameResult,
}
struct TeamData {
p... |
}
games
}
fn calc_data(games: &Vec<Game>) -> HashMap<String, TeamData> {
let mut teams: HashMap<String, TeamData> = HashMap::new();
for game in games {
let ((w1, l1, d1, p1), (w2, l2, d2, p2)) = match game.result {
GameResult::Win => ((1, 0, 0, 3), (0, 1, 0, 0)),
GameRe... | {
games.push(game)
} | conditional_block |
lib.rs | use std::fs::File;
use std::path::Path;
use std::str::FromStr;
use std::io::BufReader;
use std::io::prelude::*;
use std::collections::HashMap;
use std::cmp::Ordering;
enum GameResult {
Win,
Loss,
Draw,
}
struct Game {
team1: String,
team2: String,
result: GameResult,
}
struct TeamData {
p... | (team1: &(&String, &TeamData), team2: &(&String, &TeamData)) -> Ordering {
match team1.1.points.cmp(&team2.1.points) {
Ordering::Equal => {
match team1.1.won.cmp(&team2.1.won) {
Ordering::Equal => team2.0.cmp(&team1.0),
ans @ _ => ans,
}
}
... | custom_sort | identifier_name |
lib.rs | use std::fs::File;
use std::path::Path;
use std::str::FromStr;
use std::io::BufReader;
use std::io::prelude::*;
use std::collections::HashMap;
use std::cmp::Ordering;
enum GameResult {
Win,
Loss,
Draw,
}
struct Game {
team1: String,
team2: String,
result: GameResult,
}
struct TeamData {
p... | {
let games: Vec<Game> = read_input(input);
let results = calc_data(&games);
let content = pretty_print_results(&results);
write_output(&content, output);
Some(games.len())
} | identifier_body | |
lib.rs | use std::fs::File;
use std::path::Path;
use std::str::FromStr;
use std::io::BufReader;
use std::io::prelude::*;
use std::collections::HashMap;
use std::cmp::Ordering;
enum GameResult {
Win,
Loss,
Draw,
}
struct Game {
team1: String,
team2: String,
result: GameResult,
}
struct TeamData {
p... | "win" => GameResult::Win,
"loss" => GameResult::Loss,
"draw" => GameResult::Draw,
_ => return Err("invalid outcame"),
};
Ok(Game {
team1: input[0].into(),
team2: input[1].into(),
result: outcame,
})
}
}
fn r... | random_line_split | |
webpack.client.config.js | const webpack = require('webpack')
const base = require('./webpack.base.config')
const vueConfig = require('./vue-loader.config')
const utils = require('./utils')
const path = require('path')
const HTMLPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const SWPreca... | module.exports = config | random_line_split | |
webpack.client.config.js | const webpack = require('webpack')
const base = require('./webpack.base.config')
const vueConfig = require('./vue-loader.config')
const utils = require('./utils')
const path = require('path')
const HTMLPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const SWPreca... |
module.exports = config
| {
// Use ExtractTextPlugin to extract CSS into a single file
// so it's applied on initial render.
vueConfig.loaders = utils.cssLoaders({
extract: true
})
config.plugins.push(
new ExtractTextPlugin('styles.css'),
// this is needed in webpack 2 for minifying CSS
new webpack.LoaderOptionsPlugin... | conditional_block |
mac_dev.py | # coding=utf-8
__author__ = "Daniel Arroyo <daniel@astroprint.com>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
import logging
import threading
import time
import os
from octoprint.server import eventManager
from octoprint.events import Events
from octoprint.settings import... | import yaml
config = None
with open(settings_file, "r") as f:
config = yaml.safe_load(f)
if config:
def merge_dict(a,b):
for key in b:
if isinstance(b[key], dict):
merge_dict(a[key], b[key])
else:
a[key] = b[key]
merge_dict(self._config, config) | conditional_block | |
mac_dev.py | # coding=utf-8
__author__ = "Daniel Arroyo <daniel@astroprint.com>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
import logging
import threading
import time
import os
from octoprint.server import eventManager
from octoprint.events import Events
from octoprint.settings import... | (self):
return '127.0.0.1'
@property
def networkDeviceInfo(self):
return [
{
'id': 'eth0',
'mac': 'wi:re:d2:34:56:78:90',
'type': 'wired',
'connected': True
},
{
'id': 'wlan0',
'mac': 'wi:fi:12:34:56:78:90',
'type': 'wifi',
'connected': False
}
]
def _goOnline(self... | activeIpAddress | identifier_name |
mac_dev.py | # coding=utf-8
__author__ = "Daniel Arroyo <daniel@astroprint.com>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
import logging
import threading
import time
import os
from octoprint.server import eventManager
from octoprint.events import Events
from octoprint.settings import... |
def deleteStoredWifiNetwork(self, networkId):
for i in range(0, len(self._storedWiFiNetworks)):
n = self._storedWiFiNetworks[i]
if n['id'] == networkId:
if n['active']:
self._goOffline()
eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'disconnected'})
del self._storedWiFiNe... | return self._storedWiFiNetworks | identifier_body |
mac_dev.py | # coding=utf-8
__author__ = "Daniel Arroyo <daniel@astroprint.com>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
import logging
import threading
import time
import os
from octoprint.server import eventManager
from octoprint.events import Events
from octoprint.settings import... | {"id": "80:1F:02:F9:16:1B", "name": "Secured Network", "secured": True, "signal": 80, "wep": False},
{"id": "90:1F:02:F9:16:1C", "name": "Open Network", "secured": False, "signal": 78, "wep": False},
{"id": "74:DA:38:88:51:90", "name": "WEP Network", "secured": True, "signal": 59, "wep": True},
{"id": "C0:7... | def hasWifi(self):
return True
def getWifiNetworks(self):
return [ | random_line_split |
statusbar.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | -> Option<StatusBar> {
let tmp_pointer = unsafe { ffi::gtk_statusbar_new() };
check_pointer!(tmp_pointer, StatusBar)
}
pub fn push(&mut self, context_id: u32, text: &str) -> u32 {
unsafe {
text.with_c_str(|c_str| {
ffi::gtk_statusbar_push(GTK_STATUSBAR(self.... | w() | identifier_name |
statusbar.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | pub fn remove(&mut self, context_id: u32, message_id: u32) {
unsafe {
ffi::gtk_statusbar_remove(GTK_STATUSBAR(self.pointer), context_id, message_id)
}
}
pub fn remove_all(&mut self, context_id: u32) {
unsafe {
ffi::gtk_statusbar_remove_all(GTK_STATUSBAR(self.... | unsafe {
ffi::gtk_statusbar_pop(GTK_STATUSBAR(self.pointer), context_id)
}
}
| identifier_body |
statusbar.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | use gtk::{mod, ffi};
/// GtkViewport — An adapter which makes widgets scrollable
struct_Widget!(StatusBar)
impl StatusBar {
pub fn new() -> Option<StatusBar> {
let tmp_pointer = unsafe { ffi::gtk_statusbar_new() };
check_pointer!(tmp_pointer, StatusBar)
}
pub fn push(&mut self, context_id... | // along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! An adapter which makes widgets scrollable
use gtk::cast::GTK_STATUSBAR; | random_line_split |
test_strop.py | from test_support import verbose
import strop, sys
def test(name, input, output, *args):
if verbose:
print 'string.%s%s =? %s... ' % (name, (input,) + args, output),
f = getattr(strop, name)
try:
value = apply(f, (input,) + args)
except:
value = sys.exc_type
if value != out... | :
def __init__(self): self.seq = 'wxyz'
def __len__(self): return len(self.seq)
def __getitem__(self, i): return self.seq[i]
test('join', ['a', 'b', 'c', 'd'], 'a b c d')
test('join', ('a', 'b', 'c', 'd'), 'abcd', '')
test('join', Sequence(), 'w x y z')
# try a few long ones
print strop.join(['x' * 100] *... | Sequence | identifier_name |
test_strop.py | from test_support import verbose
import strop, sys
def test(name, input, output, *args):
if verbose:
print 'string.%s%s =? %s... ' % (name, (input,) + args, output),
f = getattr(strop, name)
try:
value = apply(f, (input,) + args)
except:
value = sys.exc_type
if value != out... | strop.whitespace
strop.lowercase
strop.uppercase | random_line_split | |
test_strop.py | from test_support import verbose
import strop, sys
def test(name, input, output, *args):
|
test('atoi', " 1 ", 1)
test('atoi', " 1x", ValueError)
test('atoi', " x1 ", ValueError)
test('atol', " 1 ", 1L)
test('atol', " 1x ", ValueError)
test('atol', " x1 ", ValueError)
test('atof', " 1 ", 1.0)
test('atof', " 1x ", ValueError)
test('atof', " x1 ", ValueError)
test('capitalize', ' hello ', ' hello ')... | if verbose:
print 'string.%s%s =? %s... ' % (name, (input,) + args, output),
f = getattr(strop, name)
try:
value = apply(f, (input,) + args)
except:
value = sys.exc_type
if value != output:
if verbose:
print 'no'
print f, `input`, `output`, `value`
... | identifier_body |
test_strop.py | from test_support import verbose
import strop, sys
def test(name, input, output, *args):
if verbose:
print 'string.%s%s =? %s... ' % (name, (input,) + args, output),
f = getattr(strop, name)
try:
value = apply(f, (input,) + args)
except:
value = sys.exc_type
if value != out... |
print f, `input`, `output`, `value`
else:
if verbose:
print 'yes'
test('atoi', " 1 ", 1)
test('atoi', " 1x", ValueError)
test('atoi', " x1 ", ValueError)
test('atol', " 1 ", 1L)
test('atol', " 1x ", ValueError)
test('atol', " x1 ", ValueError)
test('atof', " 1 ", 1.0)
test('atof'... | print 'no' | conditional_block |
controller.ts | import * as _ from "lodash";
import * as clc from "cli-color";
import * as fs from "fs";
import * as path from "path";
import { logger } from "../logger";
import * as track from "../track";
import * as utils from "../utils";
import { EmulatorRegistry } from "./registry";
import {
Address,
ALL_SERVICE_EMULATORS,
... |
/**
* Hook to do things when we're exiting cleanly (this does not include errors). Will be skipped on a second SIGINT
* @param options
*/
export async function onExit(options: any) {
await exportOnExit(options);
}
/**
* Hook to clean up on shutdown (includes errors). Will be skipped on a third SIGINT
* Stops ... | {
const exportOnExitDir = options.exportOnExit;
if (exportOnExitDir) {
try {
utils.logBullet(
`Automatically exporting data using ${FLAG_EXPORT_ON_EXIT_NAME} "${exportOnExitDir}" ` +
"please wait for the export to finish..."
);
await exportEmulatorData(exportOnExitDir, option... | identifier_body |
controller.ts | import * as _ from "lodash";
import * as clc from "cli-color";
import * as fs from "fs";
import * as path from "path";
import { logger } from "../logger";
import * as track from "../track";
import * as utils from "../utils";
import { EmulatorRegistry } from "./registry";
import {
Address,
ALL_SERVICE_EMULATORS,
... | else {
// this should not work:
// firebase emulators:start --only doesnotexit
throw new FirebaseError(
`${name} is not a valid emulator name, valid options are: ${JSON.stringify(
ALL_SERVICE_EMULATORS
)}`,
{ exit: 1 }
);
}
}
}
if... | {
EmulatorLogger.forEmulator(name).logLabeled(
"WARN",
name,
`Not starting the ${clc.bold(name)} emulator, make sure you have run ${clc.bold(
"firebase init"
)}.`
);
} | conditional_block |
controller.ts | import * as _ from "lodash";
import * as clc from "cli-color";
import * as fs from "fs";
import * as path from "path";
import { logger } from "../logger";
import * as track from "../track";
import * as utils from "../utils";
import { EmulatorRegistry } from "./registry";
import {
Address,
ALL_SERVICE_EMULATORS,
... | (emulator: Emulators, options: Options): Promise<Address> {
if (emulator === Emulators.EXTENSIONS) {
// The Extensions emulator always runs on the same port as the Functions emulator.
emulator = Emulators.FUNCTIONS;
}
let host = options.config.src.emulators?.[emulator]?.host || Constants.getDefaultHost(em... | getAndCheckAddress | identifier_name |
controller.ts | import * as _ from "lodash";
import * as clc from "cli-color";
import * as fs from "fs";
import * as path from "path";
import { logger } from "../logger";
import * as track from "../track";
import * as utils from "../utils";
import { EmulatorRegistry } from "./registry";
import {
Address,
ALL_SERVICE_EMULATORS,
... | import { EmulatorLogger } from "./emulatorLogger";
import * as portUtils from "./portUtils";
import { EmulatorHubClient } from "./hubClient";
import { promptOnce } from "../prompt";
import { FLAG_EXPORT_ON_EXIT_NAME } from "./commandUtils";
import { fileExistsSync } from "../fsutils";
import { StorageEmulator } from ".... | import { EmulatorUI } from "./ui";
import { LoggingEmulator } from "./loggingEmulator";
import * as dbRulesConfig from "../database/rulesConfig"; | random_line_split |
tests.py | # This file is part of OpenHatch.
# Copyright (C) 2010 Parker Phinney
# Copyright (C) 2010 Jack Grigg
# Copyright (C) 2011 Krzysztof Tarnowski (krzysztof.tarnowski@ymail.com)
# Copyright (C) 2009, 2010, 2011 OpenHatch, Inc.
# Copyright (C) 2011 Jairo E. Lopez
#
# This program is free software: you can redistribute it a... |
class GoogleApiTests(unittest.TestCase):
def test_google_api(self):
""" Test to see if the google api is returning what we expect """
response_file_path = os.path.join(settings.MEDIA_ROOT, 'sample-data',
'google_api', 'sample_response')
with open... | def test(self):
# Find the base directory
dir_with_git = find_git_path()
# Get a list of files from git
files = subprocess.Popen(
['git', 'ls-files'],
shell=False,
stdout=subprocess.PIPE,
cwd=dir_with_git)
stdout, stderr = files.com... | identifier_body |
tests.py | # This file is part of OpenHatch.
# Copyright (C) 2010 Parker Phinney
# Copyright (C) 2010 Jack Grigg
# Copyright (C) 2011 Krzysztof Tarnowski (krzysztof.tarnowski@ymail.com)
# Copyright (C) 2009, 2010, 2011 OpenHatch, Inc.
# Copyright (C) 2011 Jairo E. Lopez
#
# This program is free software: you can redistribute it a... | (arg):
self.assertEqual(type(arg), unicode)
sample_thing(utf8_data)
class Feed(TwillTests):
fixtures = ['user-paulproteus', 'person-paulproteus']
def test_feed_shows_answers(self):
# Visit the homepage, notice that there are no answers in the context.
def get_answers_fr... | sample_thing | identifier_name |
tests.py | # This file is part of OpenHatch.
# Copyright (C) 2010 Parker Phinney
# Copyright (C) 2010 Jack Grigg
# Copyright (C) 2011 Krzysztof Tarnowski (krzysztof.tarnowski@ymail.com)
# Copyright (C) 2009, 2010, 2011 OpenHatch, Inc.
# Copyright (C) 2011 Jairo E. Lopez
#
# This program is free software: you can redistribute it a... |
recent_feed_items = (
mysite.search.models.Answer.objects.all().order_by(
'-modified_date'))
# Visit the homepage, assert that the feed item data is on the page,
# ordered by date descending.
actual_answer_pks = [
answer.pk for answer in get_ans... | mysite.search.models.Answer.create_dummy() | conditional_block |
tests.py | # This file is part of OpenHatch.
# Copyright (C) 2010 Parker Phinney
# Copyright (C) 2010 Jack Grigg
# Copyright (C) 2011 Krzysztof Tarnowski (krzysztof.tarnowski@ymail.com)
# Copyright (C) 2009, 2010, 2011 OpenHatch, Inc.
# Copyright (C) 2011 Jairo E. Lopez
#
# This program is free software: you can redistribute it a... |
# Step 2: Call it once to fill the cache
sc = SomeClass()
self.assertEqual(sc.some_method(), '1')
# Step 3: See if the cache has it now
mock_cache.set.assert_called_with(
'doodles', '{"value": "1"}', 86400 * 10)
class EnhanceNextWithNewUserMetadata(TwillTests):
... | def some_method(self):
self.call_counter += 1
return str(self.call_counter) | random_line_split |
build.rs | //#![feature(plugin)]
//#![plugin(bindgen_plugin)]
//#[allow(dead_code, uppercase_variables, non_camel_case_types)]
//#[plugin(bindgen_plugin)]
//mod mysql_bindings {
// bindgen!("/usr/include/mysql/mysql.h", match="mysql.h", link="mysql");
//}
//use std::env;
//use std::fs;
//use std::path::Path;
//use std:... |
println!("cargo:rustc-flags=-l dylib=crypto");
println!("cargo:rustc-flags=-l dylib=ssl");
println!("cargo:rustc-flags=-l dylib=stdc++");
println!("cargo:rustc-flags=-l dylib=uv");
println!("cargo:rustc-link-search={}", "/usr/lib/x86_64-linux-gnu");
println!("cargo:rustc-link-search={}", "/usr/... | {
for p in datastax_dir.split(";") {
println!("cargo:rustc-link-search={}", p);
}
} | conditional_block |
build.rs | //#![feature(plugin)]
//#![plugin(bindgen_plugin)]
//#[allow(dead_code, uppercase_variables, non_camel_case_types)]
//#[plugin(bindgen_plugin)]
//mod mysql_bindings {
// bindgen!("/usr/include/mysql/mysql.h", match="mysql.h", link="mysql");
//}
//use std::env;
//use std::fs;
//use std::path::Path;
//use std:... | {
let _ = libbindgen::builder()
.header("cassandra.h")
.use_core()
.generate().unwrap()
.write_to_file(Path::new("./src/").join("cassandra.rs"));
if let Some(datastax_dir) = option_env!("CASSANDRA_SYS_LIB_PATH") {
for p in datastax_dir.split(";") {
println!("cargo:rustc-link-... | identifier_body | |
build.rs | //#![feature(plugin)]
//#![plugin(bindgen_plugin)]
//#[allow(dead_code, uppercase_variables, non_camel_case_types)]
//#[plugin(bindgen_plugin)]
//mod mysql_bindings {
// bindgen!("/usr/include/mysql/mysql.h", match="mysql.h", link="mysql");
//}
//use std::env;
//use std::fs;
//use std::path::Path;
//use std:... | println!("cargo:rustc-link-search={}", "/usr/local/lib");
println!("cargo:rustc-link-search={}", "/usr/lib64/");
println!("cargo:rustc-link-search={}", "/usr/lib/");
println!("cargo:rustc-link-lib=static=cassandra_static");
} | random_line_split | |
build.rs | //#![feature(plugin)]
//#![plugin(bindgen_plugin)]
//#[allow(dead_code, uppercase_variables, non_camel_case_types)]
//#[plugin(bindgen_plugin)]
//mod mysql_bindings {
// bindgen!("/usr/include/mysql/mysql.h", match="mysql.h", link="mysql");
//}
//use std::env;
//use std::fs;
//use std::path::Path;
//use std:... | () {
let _ = libbindgen::builder()
.header("cassandra.h")
.use_core()
.generate().unwrap()
.write_to_file(Path::new("./src/").join("cassandra.rs"));
if let Some(datastax_dir) = option_env!("CASSANDRA_SYS_LIB_PATH") {
for p in datastax_dir.split(";") {
println!("cargo:rustc-li... | main | identifier_name |
T20_2set.js | import React from 'react';
import Module from 'Parser/Core/Module';
import Combatants from 'Parser/Core/Modules/Combatants';
import Enemies from 'Parser/Core/Modules/Enemies';
import SPELLS from 'common/SPELLS';
import { formatNumber } from 'common/format';
import SpellIcon from 'common/SpellIcon';
import SpellLink f... | (event) {
if (event.ability.guid === SPELLS.CHAOS_BOLT.id) {
this._totalCasts += 1;
this._totalDamage += event.amount + (event.absorbed || 0);
} else if (event.ability.guid === SPELLS.INCINERATE.id) {
const enemy = this.enemies.getEntity(event);
if (!enemy || enemy.hasBuff(SPELLS.HAVOC.... | on_byPlayer_damage | identifier_name |
T20_2set.js | import React from 'react';
import Module from 'Parser/Core/Module';
import Combatants from 'Parser/Core/Modules/Combatants';
import Enemies from 'Parser/Core/Modules/Enemies';
import SPELLS from 'common/SPELLS';
import { formatNumber } from 'common/format';
import SpellIcon from 'common/SpellIcon';
import SpellLink f... | static dependencies = {
enemies: Enemies,
combatants: Combatants,
};
_totalCasts = 0;
_totalDamage = 0;
_bonusFragments = 0;
on_initialized() {
this.active = this.combatants.selected.hasBuff(SPELLS.WARLOCK_DESTRO_T20_2P_BONUS.id);
}
on_byPlayer_damage(event) {
if (event.ability.guid =... |
const CHAOS_BOLT_COST = 20;
class T20_2set extends Module { | random_line_split |
T20_2set.js | import React from 'react';
import Module from 'Parser/Core/Module';
import Combatants from 'Parser/Core/Modules/Combatants';
import Enemies from 'Parser/Core/Modules/Enemies';
import SPELLS from 'common/SPELLS';
import { formatNumber } from 'common/format';
import SpellIcon from 'common/SpellIcon';
import SpellLink f... |
item() {
// if we haven't cast any Chaos Bolts, _totalTicks would be 0 and we would get an exception
// but with denominator 1 in this case, if this._totalDamage = 0, then dividing by 1 still gives correct result of average damage = 0
const avgDamage = this._totalDamage / (this._totalCasts > 0 ? this._t... | {
if (event.ability.guid === SPELLS.CHAOS_BOLT.id) {
this._totalCasts += 1;
this._totalDamage += event.amount + (event.absorbed || 0);
} else if (event.ability.guid === SPELLS.INCINERATE.id) {
const enemy = this.enemies.getEntity(event);
if (!enemy || enemy.hasBuff(SPELLS.HAVOC.id, even... | identifier_body |
pending.rs | use core::marker;
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future};
use futures_core::task::{Context, Poll};
/// Future for the [`pending()`] function.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Pending<T> {
_data: marker::PhantomData<T>,
}
i... | (&self) -> Self {
pending()
}
}
| clone | identifier_name |
pending.rs | use core::marker;
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future};
use futures_core::task::{Context, Poll};
/// Future for the [`pending()`] function. | pub struct Pending<T> {
_data: marker::PhantomData<T>,
}
impl<T> FusedFuture for Pending<T> {
fn is_terminated(&self) -> bool {
true
}
}
/// Creates a future which never resolves, representing a computation that never
/// finishes.
///
/// The returned future will forever return [`Poll::Pending`].... | #[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"] | random_line_split |
express-jwt-tests.ts | import express = require('express');
import jwt = require('express-jwt');
import unless = require('express-unless');
var app = express();
app.use(jwt({
secret: 'shhhhhhared-secret' |
app.use(jwt({
secret: (req: express.Request,
payload: any,
done: (err: any, secret: string) => void) => {
done(null, 'shhhhhhared-secret');
},
userProperty: 'auth'
}));
app.use(jwt({
secret: (req: express.Request,
header: any,
payload: any,
done: (err: a... | }));
app.use(jwt({
secret: 'shhhhhhared-secret',
userProperty: 'auth'
})); | random_line_split |
express-jwt-tests.ts |
import express = require('express');
import jwt = require('express-jwt');
import unless = require('express-unless');
var app = express();
app.use(jwt({
secret: 'shhhhhhared-secret'
}));
app.use(jwt({
secret: 'shhhhhhared-secret',
userProperty: 'auth'
}));
app.use(jwt({
secret: (req: express.Request,... | else {
next(new jwt.UnauthorizedError('invalid_token', new Error('error-message')));
}
});
| {
if (err instanceof jwt.UnauthorizedError) {
res.status(err.status);
res.end();
}
} | conditional_block |
conversions.rs | use std::str::FromStr;
use super::errors::TcpTransportError;
use super::typedefs::TcpTransportResult;
pub fn as_string(bytes: Vec<u8>) -> TcpTransportResult<String> {
match String::from_utf8(bytes) {
Ok(st) => Ok(st),
Err(_) => Err(TcpTransportError::Utf8Error),
}
}
pub fn as_number<N: FromS... |
// bytestring is not utf8
let err = as_string(vec![b'a', 254, b'b']).unwrap_err();
assert_eq!(err, TcpTransportError::Utf8Error);
}
#[test]
fn test_as_number() {
// bytestring is a number
let num = as_number::<u64>(vec![b'1', b'2']).unwrap();
assert_eq!(num,... | fn test_as_string() {
// bytestring is utf8
let st = as_string(vec![b'a', b'b']).unwrap();
assert_eq!(st, "ab".to_string()); | random_line_split |
conversions.rs | use std::str::FromStr;
use super::errors::TcpTransportError;
use super::typedefs::TcpTransportResult;
pub fn | (bytes: Vec<u8>) -> TcpTransportResult<String> {
match String::from_utf8(bytes) {
Ok(st) => Ok(st),
Err(_) => Err(TcpTransportError::Utf8Error),
}
}
pub fn as_number<N: FromStr>(bytes: Vec<u8>) -> TcpTransportResult<N> {
let string = try!(as_string(bytes));
match string.parse::<N>() {
... | as_string | identifier_name |
conversions.rs | use std::str::FromStr;
use super::errors::TcpTransportError;
use super::typedefs::TcpTransportResult;
pub fn as_string(bytes: Vec<u8>) -> TcpTransportResult<String> {
match String::from_utf8(bytes) {
Ok(st) => Ok(st),
Err(_) => Err(TcpTransportError::Utf8Error),
}
}
pub fn as_number<N: FromS... |
#[cfg(test)]
mod tests {
use tcp_transport::TcpTransportError;
use super::as_number;
use super::as_string;
#[test]
fn test_as_string() {
// bytestring is utf8
let st = as_string(vec![b'a', b'b']).unwrap();
assert_eq!(st, "ab".to_string());
// bytestring is not... | {
let string = try!(as_string(bytes));
match string.parse::<N>() {
Ok(num) => Ok(num),
Err(_) => Err(TcpTransportError::NumberParseError),
}
} | identifier_body |
SteamAvatar.tsx | import * as React from 'react';
import {BaseProvider} from "../Providers/BaseProvider";
export interface SteamAvatarProps {
steamId: string;
}
export interface SteamAvatarState {
url: string;
}
export class SteamAvatar extends React.Component<SteamAvatarProps, SteamAvatarState> {
static avatarCache: Map<string, s... | className='steam-avatar'/>
}
}
| {
if (this.state.url === '') {
this.getAvatarUrl(this.props.steamId)
.then(url => this.setState({url}));
}
return <img src={this.state.url} | identifier_body |
SteamAvatar.tsx | import * as React from 'react';
import {BaseProvider} from "../Providers/BaseProvider";
export interface SteamAvatarProps {
steamId: string;
}
export interface SteamAvatarState {
url: string;
}
export class SteamAvatar extends React.Component<SteamAvatarProps, SteamAvatarState> {
static avatarCache: Map<string, s... | () {
if (this.state.url === '') {
this.getAvatarUrl(this.props.steamId)
.then(url => this.setState({url}));
}
return <img src={this.state.url} className='steam-avatar'/>
}
}
| render | identifier_name |
SteamAvatar.tsx | import * as React from 'react';
import {BaseProvider} from "../Providers/BaseProvider";
export interface SteamAvatarProps {
steamId: string;
}
export interface SteamAvatarState {
url: string;
}
export class SteamAvatar extends React.Component<SteamAvatarProps, SteamAvatarState> {
static avatarCache: Map<string, s... |
const url = `${BaseProvider.getBaseUrl()}users/${steamId}`;
return fetch(url)
.then((response) => {
return response.json();
}).then((data: { avatar: string }) => {
if (!data) {
return (require(`../images/class_portraits/unknown.png`).default);
}
const avatar = data.avatar;
SteamAvat... | {
return Promise.resolve(SteamAvatar.avatarCache.get(steamId) as string);
} | conditional_block |
SteamAvatar.tsx | import * as React from 'react';
import {BaseProvider} from "../Providers/BaseProvider";
export interface SteamAvatarProps {
steamId: string;
}
export interface SteamAvatarState {
url: string;
}
export class SteamAvatar extends React.Component<SteamAvatarProps, SteamAvatarState> {
static avatarCache: Map<string, s... | }
const url = `${BaseProvider.getBaseUrl()}users/${steamId}`;
return fetch(url)
.then((response) => {
return response.json();
}).then((data: { avatar: string }) => {
if (!data) {
return (require(`../images/class_portraits/unknown.png`).default);
}
const avatar = data.avatar;
SteamA... | return Promise.resolve(SteamAvatar.avatarCache.get(steamId) as string); | random_line_split |
Basic_Calculator.py | """
This simple Python script embodies its namesake by acting as a
basic calculator. Currently, It can perform addition, subtraction,
division, multiplication, exponentiation, and square roots. More
functions may be added at a later date, or you could add your own!
"""
from __future__ import division # Importing the p... |
def division(x, y): # Division function
s = x / y
return "\n\t{} / {} = {}".format(x, y, s)
def multiplication(x, y): # Multiplication function
s = x * y
return "\n\t{} * {} = {}".format(x, y, s)
def exponentiation(x, y): # Exponentiation function
s = x ** y
return "\n\t{} ** {} ... | s = x - y
return "\n\t{} - {} = {}".format(x, y, s) | identifier_body |
Basic_Calculator.py | """
This simple Python script embodies its namesake by acting as a
basic calculator. Currently, It can perform addition, subtraction,
division, multiplication, exponentiation, and square roots. More
functions may be added at a later date, or you could add your own!
"""
from __future__ import division # Importing the p... | c == "1": # Calling on the proper function
print add(ia, ib)
elif c == "2":
print minus(ia, ib)
elif c == "3":
print division(ia, ib)
elif c == "4":
print multiplication(ia, ib)
elif c == "5":
print exponentiation(ia, ib)
elif c == "6":
print squareRoot(ia)
|
b = raw_input("\nChoose your second number: ")
ib = float(b)
except ValueError:
print "\nNegative/positive integers or decimals only." # Only options allowed
continue
else:
break
if | conditional_block |
Basic_Calculator.py | """
This simple Python script embodies its namesake by acting as a
basic calculator. Currently, It can perform addition, subtraction,
division, multiplication, exponentiation, and square roots. More
functions may be added at a later date, or you could add your own!
"""
from __future__ import division # Importing the p... | (x, y): # Division function
s = x / y
return "\n\t{} / {} = {}".format(x, y, s)
def multiplication(x, y): # Multiplication function
s = x * y
return "\n\t{} * {} = {}".format(x, y, s)
def exponentiation(x, y): # Exponentiation function
s = x ** y
return "\n\t{} ** {} = {}".format(x, y,... | division | identifier_name |
Basic_Calculator.py | """
This simple Python script embodies its namesake by acting as a
basic calculator. Currently, It can perform addition, subtraction,
division, multiplication, exponentiation, and square roots. More
functions may be added at a later date, or you could add your own!
"""
from __future__ import division # Importing the p... | print minus(ia, ib)
elif c == "3":
print division(ia, ib)
elif c == "4":
print multiplication(ia, ib)
elif c == "5":
print exponentiation(ia, ib)
elif c == "6":
print squareRoot(ia) | random_line_split | |
test_glazeddoorinterzone.py | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.thermal_zones_and_surfaces import GlazedDoorInterzone
log = logging.getLogger(__name__)
class TestGlazedDoorInterzone(unittest.TestCase):
def setUp(self):
self.fd, ... |
pyidf.validation_level = ValidationLevel.error
obj = GlazedDoorInterzone()
# alpha
var_name = "Name"
obj.name = var_name
# object-list
var_construction_name = "object-list|Construction Name"
obj.construction_name = var_construction_name
# object-... | def test_create_glazeddoorinterzone(self): | random_line_split |
test_glazeddoorinterzone.py | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.thermal_zones_and_surfaces import GlazedDoorInterzone
log = logging.getLogger(__name__)
class TestGlazedDoorInterzone(unittest.TestCase):
def setUp(self):
self.fd, ... |
idf2 = IDF(self.path)
self.assertEqual(idf2.glazeddoorinterzones[0].name, var_name)
self.assertEqual(idf2.glazeddoorinterzones[0].construction_name, var_construction_name)
self.assertEqual(idf2.glazeddoorinterzones[0].building_surface_name, var_building_surface_name)
self.asser... | log.debug(line.strip()) | conditional_block |
test_glazeddoorinterzone.py | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.thermal_zones_and_surfaces import GlazedDoorInterzone
log = logging.getLogger(__name__)
class TestGlazedDoorInterzone(unittest.TestCase):
| def setUp(self):
self.fd, self.path = tempfile.mkstemp()
def tearDown(self):
os.remove(self.path)
def test_create_glazeddoorinterzone(self):
pyidf.validation_level = ValidationLevel.error
obj = GlazedDoorInterzone()
# alpha
var_name = "Name"
obj.name =... | identifier_body | |
test_glazeddoorinterzone.py | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.thermal_zones_and_surfaces import GlazedDoorInterzone
log = logging.getLogger(__name__)
class | (unittest.TestCase):
def setUp(self):
self.fd, self.path = tempfile.mkstemp()
def tearDown(self):
os.remove(self.path)
def test_create_glazeddoorinterzone(self):
pyidf.validation_level = ValidationLevel.error
obj = GlazedDoorInterzone()
# alpha
var_name =... | TestGlazedDoorInterzone | identifier_name |
nav.js | $(document).ready(function() {
init();
});
/**
* Set up necessary listeners and stuff for the page
*/
function init() {
navbar_mouseover_setup();
}
/**
* Set up the mouse-over for the navbar that allows it to function.
*/
function navbar_mouseover_setup() {
$("#navbar > #nav > li").mouseover(function(... | });
} | }
}); | random_line_split |
nav.js | $(document).ready(function() {
init();
});
/**
* Set up necessary listeners and stuff for the page
*/
function | () {
navbar_mouseover_setup();
}
/**
* Set up the mouse-over for the navbar that allows it to function.
*/
function navbar_mouseover_setup() {
$("#navbar > #nav > li").mouseover(function() {
var type = $( this ).find("a").attr("data-subtype");
$("#navbar > #nav > li").each(function() {
... | init | identifier_name |
nav.js | $(document).ready(function() {
init();
});
/**
* Set up necessary listeners and stuff for the page
*/
function init() {
navbar_mouseover_setup();
}
/**
* Set up the mouse-over for the navbar that allows it to function.
*/
function navbar_mouseover_setup() {
$("#navbar > #nav > li").mouseover(function(... |
});
$( this ).addClass("active");
$('[id$="-navbar"]').each(function() {
var first = $( this ).attr("id").toString().split("-")[0];
if(first == type) {
$( this ).removeClass('navbar-hidden');
} else {
$( this ).addClass('navbar... | {
$( this ).removeClass("active");
} | conditional_block |
nav.js | $(document).ready(function() {
init();
});
/**
* Set up necessary listeners and stuff for the page
*/
function init() |
/**
* Set up the mouse-over for the navbar that allows it to function.
*/
function navbar_mouseover_setup() {
$("#navbar > #nav > li").mouseover(function() {
var type = $( this ).find("a").attr("data-subtype");
$("#navbar > #nav > li").each(function() {
var content = $( this ).find(... | {
navbar_mouseover_setup();
} | identifier_body |
os.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
}
pub fn unsetenv(n: &OsStr) {
unsafe {
let nbuf = n.to_cstring().unwrap();
if libc::funcs::posix01::unistd::unsetenv(nbuf.as_ptr()) != 0 {
panic!("failed unsetenv: {}", io::Error::last_os_error());
}
}
}
pub fn page_size() -> usize {
unsafe {
libc::sysco... | {
panic!("failed setenv: {}", io::Error::last_os_error());
} | conditional_block |
os.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | if sz == 0 { return Err(io::Error::last_os_error()); }
v.set_len(sz as usize - 1); // chop off trailing NUL
Ok(PathBuf::from(OsString::from_vec(v)))
}
}
#[cfg(target_os = "dragonfly")]
pub fn current_exe() -> io::Result<PathBuf> {
::fs::read_link("/proc/curproc/file")
}
#[cfg(any(targe... | ptr::null_mut(), 0 as libc::size_t);
if err != 0 { return Err(io::Error::last_os_error()); } | random_line_split |
os.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> usize {
unsafe {
libc::sysconf(libc::_SC_PAGESIZE) as usize
}
}
pub fn temp_dir() -> PathBuf {
getenv("TMPDIR".as_ref()).map(os2path).unwrap_or_else(|| {
if cfg!(target_os = "android") {
PathBuf::from("/data/local/tmp")
} else {
PathBuf::from("/tmp")
... | page_size | identifier_name |
os.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
#[derive(Debug)]
pub struct JoinPathsError;
pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
where I: Iterator<Item=T>, T: AsRef<OsStr>
{
let mut joined = Vec::new();
let sep = b':';
for (i, path) in p... | { self.iter.next() } | identifier_body |
dst-dtor-2.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 ... | (&mut self) {
unsafe { DROP_RAN += 1; }
}
}
struct Fat<T: ?Sized> {
f: T
}
pub fn main() {
{
let _x: Box<Fat<[Foo]>> = box Fat { f: [Foo, Foo, Foo] };
}
unsafe {
assert!(DROP_RAN == 3);
}
}
| drop | identifier_name |
dst-dtor-2.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: Box<Fat<[Foo]>> = box Fat { f: [Foo, Foo, Foo] };
}
unsafe {
assert!(DROP_RAN == 3);
}
} | { | random_line_split |
dst-dtor-2.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: Box<Fat<[Foo]>> = box Fat { f: [Foo, Foo, Foo] };
}
unsafe {
assert!(DROP_RAN == 3);
}
} | identifier_body | |
issue-410.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
pub mod root {
#[allow(unused_imports)]
use self::super::root;
pub mod JS {
#[allow(unused_imports)]
use self::super::s... | {
pub _address: u8,
}
#[test]
fn bindgen_test_layout_Value() {
assert_eq!(
::std::mem::size_of::<Value>(),
1usize,
concat!("Size of: ", stringify!(Value))
);
assert_eq!(
::std::mem::a... | Value | identifier_name |
issue-410.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
pub mod root {
#[allow(unused_imports)]
use self::super::root;
pub mod JS {
#[allow(unused_imports)]
use self::super::s... | 1usize,
concat!("Alignment of ", stringify!(Value))
);
}
extern "C" {
#[link_name = "\u{1}_ZN2JS5Value1aE10JSWhyMagic"]
pub fn Value_a(this: *mut root::JS::Value, arg1: root::JSWhyMagic);
}
impl Value {
#[inl... | assert_eq!(
::std::mem::align_of::<Value>(), | random_line_split |
HypothermicPresence.tsx | import SPELLS from 'common/SPELLS';
import Analyzer, { Options } from 'parser/core/Analyzer';
import BoringSpellValue from 'parser/ui/BoringSpellValue';
import Statistic from 'parser/ui/Statistic';
import { STATISTIC_ORDER } from 'parser/ui/StatisticBox';
import React from 'react';
import RunicPowerTracker from '../ru... | />
</Statistic>
);
}
}
export default HypothermicPresence; | <Statistic position={STATISTIC_ORDER.OPTIONAL(50)} size="flexible">
<BoringSpellValue
spell={SPELLS.HYPOTHERMIC_PRESENCE_TALENT}
value={`${this.runicPowerTracker.totalHypothermicPresenceReduction}`}
label="Runic Power saved" | random_line_split |
HypothermicPresence.tsx | import SPELLS from 'common/SPELLS';
import Analyzer, { Options } from 'parser/core/Analyzer';
import BoringSpellValue from 'parser/ui/BoringSpellValue';
import Statistic from 'parser/ui/Statistic';
import { STATISTIC_ORDER } from 'parser/ui/StatisticBox';
import React from 'react';
import RunicPowerTracker from '../ru... | extends Analyzer {
static dependencies = {
runicPowerTracker: RunicPowerTracker,
};
protected runicPowerTracker!: RunicPowerTracker;
constructor(options: Options) {
super(options);
this.active = this.selectedCombatant.hasTalent(SPELLS.HYPOTHERMIC_PRESENCE_TALENT.id);
if (!this.active) {
... | HypothermicPresence | identifier_name |
HypothermicPresence.tsx | import SPELLS from 'common/SPELLS';
import Analyzer, { Options } from 'parser/core/Analyzer';
import BoringSpellValue from 'parser/ui/BoringSpellValue';
import Statistic from 'parser/ui/Statistic';
import { STATISTIC_ORDER } from 'parser/ui/StatisticBox';
import React from 'react';
import RunicPowerTracker from '../ru... |
statistic() {
return (
<Statistic position={STATISTIC_ORDER.OPTIONAL(50)} size="flexible">
<BoringSpellValue
spell={SPELLS.HYPOTHERMIC_PRESENCE_TALENT}
value={`${this.runicPowerTracker.totalHypothermicPresenceReduction}`}
label="Runic Power saved"
/>
</S... | {
super(options);
this.active = this.selectedCombatant.hasTalent(SPELLS.HYPOTHERMIC_PRESENCE_TALENT.id);
if (!this.active) {
return;
}
} | identifier_body |
HypothermicPresence.tsx | import SPELLS from 'common/SPELLS';
import Analyzer, { Options } from 'parser/core/Analyzer';
import BoringSpellValue from 'parser/ui/BoringSpellValue';
import Statistic from 'parser/ui/Statistic';
import { STATISTIC_ORDER } from 'parser/ui/StatisticBox';
import React from 'react';
import RunicPowerTracker from '../ru... |
}
statistic() {
return (
<Statistic position={STATISTIC_ORDER.OPTIONAL(50)} size="flexible">
<BoringSpellValue
spell={SPELLS.HYPOTHERMIC_PRESENCE_TALENT}
value={`${this.runicPowerTracker.totalHypothermicPresenceReduction}`}
label="Runic Power saved"
/>
... | {
return;
} | conditional_block |
handshake.rs | // Copyright 2016 The Grin Developers
//
// 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 agree... |
/// Generate a new random nonce and store it in our ring buffer
fn next_nonce(&self) -> u64 {
let mut rng = OsRng::new().unwrap();
let nonce = rng.next_u64();
let mut nonces = self.nonces.write().unwrap();
nonces.push_back(nonce);
if nonces.len() >= NONCES_CAP {
nonces.pop_front();
}
nonce
}
}
| {
let nonces = self.nonces.clone();
Box::new(read_msg::<Hand>(conn)
.and_then(move |(conn, hand)| {
if hand.version != 1 {
return Err(Error::Serialization(ser::Error::UnexpectedData {
expected: vec![PROTOCOL_VERSION as u8],
received: vec![hand.version as u8],
}));
}
{
// ch... | identifier_body |
handshake.rs | // 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.
// Se... | // Copyright 2016 The Grin Developers
//
// 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 | |
handshake.rs | // Copyright 2016 The Grin Developers
//
// 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 agree... | (&self,
capab: Capabilities,
total_difficulty: Difficulty,
conn: TcpStream)
-> Box<Future<Item = (TcpStream, ProtocolV1, PeerInfo), Error = Error>> {
let nonces = self.nonces.clone();
Box::new(read_msg::<Hand>(conn)
.and_then(move |(conn, ha... | handshake | identifier_name |
handshake.rs | // Copyright 2016 The Grin Developers
//
// 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 agree... |
nonce
}
}
| {
nonces.pop_front();
} | conditional_block |
libstdc++.a-gdb.py | # -*- python -*-
# Copyright (C) 2009-2013 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later versio... |
# Strip off the prefix.
pythondir = pythondir[len (prefix):]
libdir = libdir[len (prefix):]
# Compute the ".."s needed to get from libdir to the prefix.
dotdots = ('..' + os.sep) * len (libdir.split (os.sep))
objfile = gdb.current_objfile ().filename
dir_ = os.path.join (os.path.dirname ... | prefix = os.path.dirname (prefix) + '/' | conditional_block |
libstdc++.a-gdb.py | # -*- python -*-
# Copyright (C) 2009-2013 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later versio... | # can happen if the user loads it manually. In this case we don't
# update sys.path; instead we just hope the user managed to do that
# beforehand.
if gdb.current_objfile () is not None:
# Update module path. We want to find the relative path from libdir
# to pythondir, and then we want to apply that relative... | pythondir = '/Users/igrokhotkov/projects/esp8266/esptools/crosstool-NG/builds/xtensa-lx106-elf/share/gcc-4.8.2/python'
libdir = '/Users/igrokhotkov/projects/esp8266/esptools/crosstool-NG/builds/xtensa-lx106-elf/xtensa-lx106-elf/lib'
# This file might be loaded when there is no current objfile. This | random_line_split |
hero.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Hero } from './hero';
import 'rxjs/add/operator/toPromise'
@Injectable()
export class HeroService {
private heroesUrl = 'app/heroes'; // URL to web api
constructor(private http: Http) {}
// Get Hero
getHeroe... |
return this.post(hero);
}
private handleError(error: any) {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
| {
return this.put(hero);
} | conditional_block |
hero.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Hero } from './hero';
import 'rxjs/add/operator/toPromise'
@Injectable()
export class HeroService {
private heroesUrl = 'app/heroes'; // URL to web api
constructor(private http: Http) {}
// Get Hero
getHeroe... |
// Add new Hero
private post(hero: Hero): Promise<Hero> {
let headers = new Headers({
'Content-Type': 'application/json'});
return this.http
.post(this.heroesUrl, JSON.stringify(hero), {headers: headers})
.toPromise()
.then(res => res.json().data)
... | {
return this.getHeroes()
.then(heroes => heroes.find(hero => hero.id === id));
} | identifier_body |
hero.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Hero } from './hero';
import 'rxjs/add/operator/toPromise'
@Injectable()
export class HeroService { | getHeroes() {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
// Get Hero
getHero(id: number) {
return this.getHeroes()
.then(heroes => heroes.find(hero => hero.id ===... |
private heroesUrl = 'app/heroes'; // URL to web api
constructor(private http: Http) {}
// Get Hero | random_line_split |
hero.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Hero } from './hero';
import 'rxjs/add/operator/toPromise'
@Injectable()
export class HeroService {
private heroesUrl = 'app/heroes'; // URL to web api
constructor(private http: Http) {}
// Get Hero
| () {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
// Get Hero
getHero(id: number) {
return this.getHeroes()
.then(heroes => heroes.find(hero => hero.id === id));
}
... | getHeroes | identifier_name |
destructured-fn-argument.rs | // Copyright 2013 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 ... | (rr: int, (ss, tt): (int, int)) {
zzz();
}
nested_function(60, (61, 62));
}
fn zzz() {()}
| nested_function | identifier_name |
destructured-fn-argument.rs | // Copyright 2013 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 ... |
fn different_order_of_struct_fields(Struct { b: s, a: t }: Struct ) {
zzz();
}
fn complex_nesting(((u, v ), ((w, (x, Struct { a: y, b: z})), Struct { a: ae, b: oe }), ue ):
((i16, i32), ((i64, (i32, Struct, )), Struct ), u16)) {
zzz();
}
fn managed_box(@... | {
zzz();
} | identifier_body |
destructured-fn-argument.rs | // Copyright 2013 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 ... |
// debugger:finish
// debugger:print kk
// check:$40 = 53
// debugger:print ll
// check:$41 = 54
// debugger:continue
// debugger:finish
// debugger:print mm
// check:$42 = 55
// debugger:print *nn
// check:$43 = 56
// debugger:continue
// debugger:finish
// debugger:print oo
// check:$44 = 57
// debugger:print pp
/... | // debugger:print *jj
// check:$39 = 52
// debugger:continue | random_line_split |
DirectEntryScroll.py | __all__ = ['DirectEntryScroll']
from pandac.PandaModules import *
import DirectGuiGlobals as DGG
from DirectScrolledFrame import *
from DirectFrame import *
from DirectEntry import *
class DirectEntryScroll(DirectFrame):
def __init__(self, entry, parent = None, **kw):
optiondefs = (
('pgFunc',... | DirectFrame.destroy(self)
def getCanvas(self):
return self.canvas
def setClipSize(self):
self.guiItem.setClipFrame(self['clipSize'])
self.clipXMin = self['clipSize'][0]
self.clipXMax = self['clipSize'][1]
self.visXMin = self.clipXMin
sel... | self.entry.destroy()
self.entry = None | random_line_split |
DirectEntryScroll.py | __all__ = ['DirectEntryScroll']
from pandac.PandaModules import *
import DirectGuiGlobals as DGG
from DirectScrolledFrame import *
from DirectFrame import *
from DirectEntry import *
class DirectEntryScroll(DirectFrame):
def __init__(self, entry, parent = None, **kw):
optiondefs = (
('pgFunc',... | (self):
# Destroy children of the canvas
for child in self.canvas.getChildren():
childGui = self.guiDict.get(child.getName())
if childGui:
childGui.destroy()
else:
parts = child.getName().split('-')
simpleChildGui = self... | destroy | identifier_name |
DirectEntryScroll.py | __all__ = ['DirectEntryScroll']
from pandac.PandaModules import *
import DirectGuiGlobals as DGG
from DirectScrolledFrame import *
from DirectFrame import *
from DirectEntry import *
class DirectEntryScroll(DirectFrame):
def __init__(self, entry, parent = None, **kw):
optiondefs = (
('pgFunc',... |
self.entry.destroy()
self.entry = None
DirectFrame.destroy(self)
def getCanvas(self):
return self.canvas
def setClipSize(self):
self.guiItem.setClipFrame(self['clipSize'])
self.clipXMin = self['clipSize'][0]
self.clipXMax = self['clipSi... | childGui = self.guiDict.get(child.getName())
if childGui:
childGui.destroy()
else:
parts = child.getName().split('-')
simpleChildGui = self.guiDict.get(parts[-1])
if simpleChildGui:
simpleChildGui.destroy() | conditional_block |
DirectEntryScroll.py | __all__ = ['DirectEntryScroll']
from pandac.PandaModules import *
import DirectGuiGlobals as DGG
from DirectScrolledFrame import *
from DirectFrame import *
from DirectEntry import *
class DirectEntryScroll(DirectFrame):
def __init__(self, entry, parent = None, **kw):
optiondefs = (
('pgFunc',... |
def resetCanvas(self):
self.canvas.setPos(0,0,0)
| self.guiItem.setClipFrame(self['clipSize'])
self.clipXMin = self['clipSize'][0]
self.clipXMax = self['clipSize'][1]
self.visXMin = self.clipXMin
self.visXMax = self.clipXMax
if self.canvas:
self.resetCanvas() | identifier_body |
setup.py | #!/usr/bin/env python
import sys
import os
import re
def setup_python3():
# Taken from "distribute" setup.py
from distutils.filelist import FileList
from distutils import dir_util, file_util, util, log
from os.path import join, exists
tmp_src = join("build", "src")
# Not covered by "setup.py ... | (filename):
_version_re = re.compile(r'__version__ = "(.*)"')
for line in open(filename):
version_match = _version_re.match(line)
if version_match:
return version_match.group(1)
version = find_version('rdflib/__init__.py')
packages = ['rdflib',
'rdflib/extras',
... | find_version | identifier_name |
setup.py | #!/usr/bin/env python
import sys
import os
import re
def setup_python3():
# Taken from "distribute" setup.py
from distutils.filelist import FileList
from distutils import dir_util, file_util, util, log
from os.path import join, exists
| tmp_src = join("build", "src")
# Not covered by "setup.py clean --all", so explicit deletion required.
if exists(tmp_src):
dir_util.remove_tree(tmp_src)
log.set_verbosity(1)
fl = FileList()
for line in open("MANIFEST.in"):
if not line.strip():
continue
fl.proc... | random_line_split | |
setup.py | #!/usr/bin/env python
import sys
import os
import re
def setup_python3():
# Taken from "distribute" setup.py
from distutils.filelist import FileList
from distutils import dir_util, file_util, util, log
from os.path import join, exists
tmp_src = join("build", "src")
# Not covered by "setup.py ... |
util.run_2to3(outfiles_2to3)
# arrange setup to use the copy
sys.path.insert(0, tmp_src)
return tmp_src
kwargs = {}
if sys.version_info[0] >= 3:
from setuptools import setup
kwargs['use_2to3'] = True
kwargs['install_requires'] = ['isodate', 'pyparsing']
kwargs['tests_require'] = ['h... | outf, copied = file_util.copy_file(f, join(tmp_src, f), update=1)
if copied and outf.endswith(".py"):
outfiles_2to3.append(outf) | conditional_block |
setup.py | #!/usr/bin/env python
import sys
import os
import re
def setup_python3():
# Taken from "distribute" setup.py
from distutils.filelist import FileList
from distutils import dir_util, file_util, util, log
from os.path import join, exists
tmp_src = join("build", "src")
# Not covered by "setup.py ... |
version = find_version('rdflib/__init__.py')
packages = ['rdflib',
'rdflib/extras',
'rdflib/plugins',
'rdflib/plugins/parsers',
'rdflib/plugins/parsers/pyRdfa',
'rdflib/plugins/parsers/pyRdfa/transform',
'rdflib/plugins/parsers/pyRdfa/extras',
... | _version_re = re.compile(r'__version__ = "(.*)"')
for line in open(filename):
version_match = _version_re.match(line)
if version_match:
return version_match.group(1) | identifier_body |
models.py | from __future__ import absolute_import
import urlparse
import urllib
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.utils.encoding import smart_unicode, ... | ordering = ('-datetime_created',)
verbose_name = _(u'recent search')
verbose_name_plural = _(u'recent searches') | identifier_body | |
models.py | from __future__ import absolute_import
import urlparse
import urllib
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.utils.encoding import smart_unicode, ... |
else:
# Is a simple search
display_string = smart_unicode(' '.join(query_dict['q']))
return u'%s (%s)' % (display_string, self.hits)
def save(self, *args, **kwargs):
self.datetime_created = datetime.now()
super(RecentSearch, self).save(*args, **kwargs)
... | advanced_string = []
for key, value in query_dict.items():
search_field = document_search.get_search_field(key)
advanced_string.append(u'%s: %s' % (search_field.label, smart_unicode(' '.join(value))))
display_string = u', '.join(advanced_string) | conditional_block |
models.py | from __future__ import absolute_import
import urlparse
import urllib
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.utils.encoding import smart_unicode, ... | class Meta:
ordering = ('-datetime_created',)
verbose_name = _(u'recent search')
verbose_name_plural = _(u'recent searches') | return 'q' not in urlparse.parse_qs(self.query)
| random_line_split |
models.py | from __future__ import absolute_import
import urlparse
import urllib
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.utils.encoding import smart_unicode, ... | (self):
document_search = SearchModel.get('documents.Document')
query_dict = urlparse.parse_qs(urllib.unquote_plus(smart_str(self.query)))
if self.is_advanced():
# Advanced search
advanced_string = []
for key, value in query_dict.items():
... | __unicode__ | identifier_name |
index.ts | import { AbortController, AbortSignal } from "./lib/abort";
import { Body, DataBody, JsonBody, StreamBody } from "./lib/body";
import { Context, ContextOptions } from "./lib/context";
import { PushHandler } from "./lib/context-http2";
import { CookieJar } from "./lib/cookie-jar";
import {
AbortError,
DecodeFunction,
... |
export {
setup,
context,
fetch,
disconnect,
disconnectAll,
onPush,
// Re-export
AbortController,
AbortSignal,
RequestInit,
FetchInit,
HttpProtocols,
Body,
JsonBody,
StreamBody,
DataBody,
Headers,
Request,
Response,
AbortError,
TimeoutError,
HttpVersion,
OnTrailers,
ContextOptions,
DecodeFunc... | {
const ctx = new Context( opts );
return {
disconnect: ctx.disconnect.bind( ctx ) as typeof disconnect,
disconnectAll: ctx.disconnectAll.bind( ctx ) as typeof disconnectAll,
fetch: ctx.fetch.bind( ctx ) as typeof fetch,
onPush: ctx.onPush.bind( ctx ) as typeof onPush,
setup: ctx.setup.bind( ctx ) as typeof... | identifier_body |
index.ts | import { AbortController, AbortSignal } from "./lib/abort";
import { Body, DataBody, JsonBody, StreamBody } from "./lib/body";
import { Context, ContextOptions } from "./lib/context";
import { PushHandler } from "./lib/context-http2";
import { CookieJar } from "./lib/cookie-jar";
import {
AbortError,
DecodeFunction,
... | ( opts?: Partial< ContextOptions > )
{
const ctx = new Context( opts );
return {
disconnect: ctx.disconnect.bind( ctx ) as typeof disconnect,
disconnectAll: ctx.disconnectAll.bind( ctx ) as typeof disconnectAll,
fetch: ctx.fetch.bind( ctx ) as typeof fetch,
onPush: ctx.onPush.bind( ctx ) as typeof onPush,
s... | context | identifier_name |
index.ts | import { AbortController, AbortSignal } from "./lib/abort";
import { Body, DataBody, JsonBody, StreamBody } from "./lib/body";
import { Context, ContextOptions } from "./lib/context";
import { PushHandler } from "./lib/context-http2";
import { CookieJar } from "./lib/cookie-jar";
import {
AbortError,
DecodeFunction,
... | Body,
JsonBody,
StreamBody,
DataBody,
Headers,
Request,
Response,
AbortError,
TimeoutError,
HttpVersion,
OnTrailers,
ContextOptions,
DecodeFunction,
Decoder,
CookieJar,
Method,
}; | HttpProtocols, | random_line_split |
get_cov_per_ind.py | #! /usr/bin/python
#
# This file reads through a vcf file and prints a space-separated text file, containing the coverage for each SNV (rows) and individual (columns). Alt and ref alleles are summed to total coverage at each SNV and locus.
# Usage: ~/hts_tools/get_cov_per_ind.py fltrd_pubRetStri_dipUG35_200bp.vcf > ou... |
count_list.append(str(count))
print ' '.join(count_list)
file.close()
| ad = ad.split(',')
count += int(ad[0]) + int(ad[1]) | conditional_block |
get_cov_per_ind.py | #! /usr/bin/python
#
# This file reads through a vcf file and prints a space-separated text file, containing the coverage for each SNV (rows) and individual (columns). Alt and ref alleles are summed to total coverage at each SNV and locus.
# Usage: ~/hts_tools/get_cov_per_ind.py fltrd_pubRetStri_dipUG35_200bp.vcf > ou... | count_list.append(str(count))
print ' '.join(count_list)
file.close() | count += int(ad[0]) + int(ad[1]) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.