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 |
|---|---|---|---|---|
index.d.ts | // Type definitions for koa-bodyparser 4.2
// Project: https://github.com/koajs/bodyparser
// Definitions by: Jerry Chin <https://github.com/hellopao>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/* =================== USAGE ===================
import bodyParser = ... | /**
* support extend types
*/
extendTypes?: {
json?: string[];
form?: string[];
text?: string[];
}
/**
* support custom error handle
*/
onerror?: (err: Error, ctx: Koa.Context) => void;
}): Koa.Middleware;
declare namespace bodyParser { }
export = bodyPa... | * custom json request detect function. Default is null
*/
detectJSON?: (ctx: Koa.Context) => boolean;
| random_line_split |
jquery.iframe.js | //copied from http://stackoverflow.com/questions/8407946/is-it-possible-to-use-iframes-in-ie-without-memory-leaks
(function($) {
$.fn.purgeFrame = function() {
var deferred;
var browser = bowser;
if (browser.msie && parseFloat(browser.version, 10) < 9) {
deferred = purge(this);
... |
return deferred.promise();
}
})(jQuery);
| {
deferred.resolve();
} | conditional_block |
jquery.iframe.js | //copied from http://stackoverflow.com/questions/8407946/is-it-possible-to-use-iframes-in-ie-without-memory-leaks
(function($) {
$.fn.purgeFrame = function() {
var deferred;
var browser = bowser;
if (browser.msie && parseFloat(browser.version, 10) < 9) {
deferred = purge(this);
... | var frame = this;
frame.contentWindow.document.innerHTML = '';
sem -= 1;
if (sem <= 0) {
$frame.remove();
deferred.resolve();
}
});
$frame.attr('src', 'about:blank');
if ($frame.length === 0) {
... |
$frame.load(function() { | random_line_split |
jquery.iframe.js | //copied from http://stackoverflow.com/questions/8407946/is-it-possible-to-use-iframes-in-ie-without-memory-leaks
(function($) {
$.fn.purgeFrame = function() {
var deferred;
var browser = bowser;
if (browser.msie && parseFloat(browser.version, 10) < 9) {
deferred = purge(this);
... | ($frame) {
var sem = $frame.length
, deferred = $.Deferred();
$frame.load(function() {
var frame = this;
frame.contentWindow.document.innerHTML = '';
sem -= 1;
if (sem <= 0) {
$frame.remove();
deferred.resolve();... | purge | identifier_name |
jquery.iframe.js | //copied from http://stackoverflow.com/questions/8407946/is-it-possible-to-use-iframes-in-ie-without-memory-leaks
(function($) {
$.fn.purgeFrame = function() {
var deferred;
var browser = bowser;
if (browser.msie && parseFloat(browser.version, 10) < 9) {
deferred = purge(this);
... | return deferred.promise();
}
})(jQuery);
| {
var sem = $frame.length
, deferred = $.Deferred();
$frame.load(function() {
var frame = this;
frame.contentWindow.document.innerHTML = '';
sem -= 1;
if (sem <= 0) {
$frame.remove();
deferred.resolve();
... | identifier_body |
parse_shebang_test.py | from __future__ import annotations
import contextlib
import os.path
import shutil
import sys
import pytest
from pre_commit import parse_shebang
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import Var
from pre_commit.util import make_executable
def _echo_exe() -> str:
exe = shutil.whi... | (in_tmpdir):
path = os.path.abspath(write_executable('/usr/bin/env sh'))
assert parse_shebang.find_executable('run') is None
with bin_on_path():
assert parse_shebang.find_executable('run') == path
def test_find_executable_path_ext(in_tmpdir):
"""Windows exports PATHEXT as a list of extensions ... | test_find_executable_path_added | identifier_name |
parse_shebang_test.py | from __future__ import annotations
import contextlib
import os.path
import shutil
import sys
import pytest
from pre_commit import parse_shebang
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import Var
from pre_commit.util import make_executable
def _echo_exe() -> str:
exe = shutil.whi... | make_executable(path)
return path
@contextlib.contextmanager
def bin_on_path():
bindir = os.path.join(os.getcwd(), 'bin')
with envcontext((('PATH', (bindir, os.pathsep, Var('PATH'))),)):
yield
def test_find_executable_path_added(in_tmpdir):
path = os.path.abspath(write_executable('/usr/b... | os.mkdir('bin')
path = os.path.join('bin', filename)
with open(path, 'w') as f:
f.write(f'#!{shebang}') | random_line_split |
parse_shebang_test.py | from __future__ import annotations
import contextlib
import os.path
import shutil
import sys
import pytest
from pre_commit import parse_shebang
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import Var
from pre_commit.util import make_executable
def _echo_exe() -> str:
exe = shutil.whi... |
def test_normalize_cmd_shebang(in_tmpdir):
echo = _echo_exe().replace(os.sep, '/')
path = write_executable(echo)
assert parse_shebang.normalize_cmd((path,)) == (echo, path)
def test_normalize_cmd_PATH_shebang_full_path(in_tmpdir):
echo = _echo_exe().replace(os.sep, '/')
path = write_executable(... | cmd = ('echo', '--version')
expected = (_echo_exe(), '--version')
assert parse_shebang.normalize_cmd(cmd) == expected | identifier_body |
mod.rs | use anyhow::Result;
use pueue_lib::network::message::Message;
use pueue_lib::network::protocol::*;
use pueue_lib::state::State;
mod edit;
mod format_state;
mod local_follow;
mod restart;
mod wait;
pub use edit::edit;
pub use format_state::format_state;
pub use local_follow::local_follow;
pub use restart::restart;
pu... | {
// Create the message payload and send it to the daemon.
send_message(Message::Status, stream).await?;
// Check if we can receive the response from the daemon
let message = receive_message(stream).await?;
match message {
Message::StatusResponse(state) => Ok(*state),
_ => unreacha... | identifier_body | |
mod.rs | use pueue_lib::state::State;
mod edit;
mod format_state;
mod local_follow;
mod restart;
mod wait;
pub use edit::edit;
pub use format_state::format_state;
pub use local_follow::local_follow;
pub use restart::restart;
pub use wait::wait;
// This is a helper function for easy retrieval of the current daemon state.
// T... | use anyhow::Result;
use pueue_lib::network::message::Message;
use pueue_lib::network::protocol::*; | random_line_split | |
mod.rs | use anyhow::Result;
use pueue_lib::network::message::Message;
use pueue_lib::network::protocol::*;
use pueue_lib::state::State;
mod edit;
mod format_state;
mod local_follow;
mod restart;
mod wait;
pub use edit::edit;
pub use format_state::format_state;
pub use local_follow::local_follow;
pub use restart::restart;
pu... | (stream: &mut GenericStream) -> Result<State> {
// Create the message payload and send it to the daemon.
send_message(Message::Status, stream).await?;
// Check if we can receive the response from the daemon
let message = receive_message(stream).await?;
match message {
Message::StatusRespon... | get_state | identifier_name |
obj2vxpGUI.py | #OBJ2VXP: Converts simple OBJ files to VXP expansions
#Copyright (C) 2004-2015 Foone Turing
#
#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 2 of the License, or (at your option) any ... |
def getEnhanceColor(self):
try:
val=self.config.get('obj2vxp','enhance')
return sockgui.BoolConv(val)
except:
return False
def getTextured(self):
try:
val=self.config.get('obj2vxp','textured')
return sockgui.BoolConv(val)
except:
return False
def getOBJList(self):
out=[]
for file in os... | try:
self.config.add_section('obj2vxp')
except:
pass
self.config.set('obj2vxp','enhance',`self.enhance_color.isChecked()`)
self.config.set('obj2vxp','textured',`self.textured.isChecked()`) | identifier_body |
obj2vxpGUI.py | #OBJ2VXP: Converts simple OBJ files to VXP expansions
#Copyright (C) 2004-2015 Foone Turing
#
#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 2 of the License, or (at your option) any ... |
except SaveError,e:
self.errortext.setText('Failed: ' + str(e).strip('"'))
except LoadError,e:
self.errortext.setText('Failed: ' + str(e).strip('"'))
except ValueError:
self.errortext.setText('Failed: Bad ID!')
except pygame.error,e:
self.errortext.setText('Failed: ' + str(e).strip('"'))
def copyA... | self.errortext.setText('Failed: unknown error (!ret)') | conditional_block |
obj2vxpGUI.py | #OBJ2VXP: Converts simple OBJ files to VXP expansions
#Copyright (C) 2004-2015 Foone Turing
#
#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 2 of the License, or (at your option) any ... | self.origauthorbox= sockgui.TextBox(ui,[120,ys+42-3],40)
self.shortnamebox= sockgui.TextBox(ui,[120,ys+58-3],40,callback=self.onShortNameChanged)
self.shortnamebox.setAllowedKeys(sockgui.UPPERCASE+sockgui.LOWERCASE+sockgui.DIGITS+'._-')
self.authorbox.setText(self.getAuthor())
ui.add(self.namebox)
ui.a... | self.authorbox= sockgui.TextBox(ui,[120,ys+26-3],40) | random_line_split |
obj2vxpGUI.py | #OBJ2VXP: Converts simple OBJ files to VXP expansions
#Copyright (C) 2004-2015 Foone Turing
#
#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 2 of the License, or (at your option) any ... | (ConverterBase):
def __init__(self,screen):
ConverterBase.__init__(self,screen)
ui=self.ui
ys=self.makeTab(10,94,'CFG settings')
ui.add(sockgui.Label(ui,[20,ys+10],'Expansion name:'))
ui.add(sockgui.Label(ui,[20,ys+26],'Author name:'))
ui.add(sockgui.Label(ui,[20,ys+42],'Orig. Author name:'))
ui.add(so... | obj2vxpGUI | identifier_name |
defineProperty_test.js | // ==========================================================================
// Project: SproutCore Metal
// Copyright: ©2011 Strobe Inc. and contributors.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
require('sproutcore-metal... | equals(obj.foo, 'FOO', 'real defined property should not be writable');
}
});
test('defining a non enumerable property', function() {
var obj = {};
SC.platform.defineProperty(obj, 'foo', {
enumerable: false,
writable: true,
value: 'FOO'
});
if (SC.platform.defineProperty.isSimulat... |
obj.foo = "BAR";
if (SC.platform.defineProperty.isSimulated) {
equals(obj.foo, 'BAR', 'simulated defineProperty should silently work');
} else { | random_line_split |
defineProperty_test.js | // ==========================================================================
// Project: SproutCore Metal
// Copyright: ©2011 Strobe Inc. and contributors.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
require('sproutcore-metal... |
});
test('defining a non enumerable property', function() {
var obj = {};
SC.platform.defineProperty(obj, 'foo', {
enumerable: false,
writable: true,
value: 'FOO'
});
if (SC.platform.defineProperty.isSimulated) {
equals(isEnumerable(obj, 'foo'), true, 'simulated defineProperty will ... |
equals(obj.foo, 'FOO', 'real defined property should not be writable');
}
| conditional_block |
defineProperty_test.js | // ==========================================================================
// Project: SproutCore Metal
// Copyright: ©2011 Strobe Inc. and contributors.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
require('sproutcore-metal... | obj, keyName) {
var keys = [];
for(var key in obj) {
if (obj.hasOwnProperty(key)) keys.push(key);
}
return keys.indexOf(keyName)>=0;
}
module("SC.platform.defineProperty()");
test("defining a simple property", function() {
var obj = {};
SC.platform.defineProperty(obj, 'foo', {
enumerable: true,
... | sEnumerable( | identifier_name |
defineProperty_test.js | // ==========================================================================
// Project: SproutCore Metal
// Copyright: ©2011 Strobe Inc. and contributors.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
require('sproutcore-metal... |
module("SC.platform.defineProperty()");
test("defining a simple property", function() {
var obj = {};
SC.platform.defineProperty(obj, 'foo', {
enumerable: true,
writable: true,
value: 'FOO'
});
equals(obj.foo, 'FOO', 'should have added property');
obj.foo = "BAR";
equals(obj.foo, '... |
var keys = [];
for(var key in obj) {
if (obj.hasOwnProperty(key)) keys.push(key);
}
return keys.indexOf(keyName)>=0;
}
| identifier_body |
du.rs | my_stat.fstat.size += this_stat.fstat.size;
my_stat.fstat.unstable.blocks += this_stat.fstat.unstable.blocks;
if options.all {
stats.push(Arc::new(this_stat))
}
}
}
}
for future in futures.iter_mut() {
... | {
let mut stats = vec!();
let mut futures = vec!();
if my_stat.fstat.kind == FileType::Directory {
let read = match fs::readdir(path) {
Ok(read) => read,
Err(e) => {
safe_writeln!(&mut stderr(), "{}: cannot read directory ‘{}‘: {}",
... | identifier_body | |
du.rs | _stat.fstat.size += stat.fstat.size;
my_stat.fstat.unstable.blocks += stat.fstat.unstable.blocks;
}
if options.max_depth == None || depth < options.max_depth.unwrap() {
stats.push(stat.clone());
}
}
}
stats.push(Arc::new(my_stat));
... | let mut numbers = String::new();
let mut letters = String::new();
for c in s.as_slice().chars() {
if found_letter && c.is_digit(10) || !found_number && !c.is_digit(10) {
show_error!("invalid --block-size argument '{}'", s);
re... | random_line_split | |
du.rs | }
}
}
}
for future in futures.iter_mut() {
for stat in future.get().into_iter().rev() {
if !options.separate_dirs && stat.path.dir_path() == my_stat.path {
my_stat.fstat.size += stat.fstat.size;
my_stat.fstat.unstable.bloc... | {
let read = match fs::readdir(path) {
Ok(read) => read,
Err(e) => {
safe_writeln!(&mut stderr(), "{}: cannot read directory ‘{}‘: {}",
options.program_name, path.display(), e);
return vec!(Arc::new(my_stat))
}
... | conditional_block | |
du.rs | (path: &Path, mut my_stat: Stat,
options: Arc<Options>, depth: usize) -> Vec<Arc<Stat>> {
let mut stats = vec!();
let mut futures = vec!();
if my_stat.fstat.kind == FileType::Directory {
let read = match fs::readdir(path) {
Ok(read) => read,
Err(e) => {
... | du | identifier_name | |
allskymap.py | ax=ax)
# Keep a local ref to lon_0 for hemisphere checking.
self._lon_0 = self.projparams['lon_0']
self._limb = None
def drawmapboundary(self,color='k',linewidth=1.0,fill_color=None,\
zorder=None,ax=None):
"""
draw boundary around map projection reg... | # If in the starting hemisphere, add to 1st polygon seg list.
if self.east_hem(lon) == start_hem: | random_line_split | |
allskymap.py | raise ValueError('Only hammer and moll projections supported!')
# Use Basemap's init, enforcing the values of many parameters that
# aren't used or whose Basemap defaults would not be altered for all-sky
# celestial maps.
Basemap.__init__(self, llcrnrlon=None, llcrnrlat=None,
... | pl.text(x, y, angle_symbol(lon_lbl), fontsize=fontsize,
verticalalignment=valign,
horizontalalignment=halign,color=color)
def east_hem(self, lon):
"""
Return True if lon is in the eastern hemisphere of the map wrt lon_0.
"""
if (l... | """
Label meridians with their longitude values in degrees.
This labels meridians with negative longitude l with the value 360-l;
for maps in celestial orientation, this means meridians to the right
of the central meridian are labeled from 360 to 180 (left to right).
... | identifier_body |
allskymap.py | (self,
projection='hammer',
lat_0=0., lon_0=0.,
suppress_ticks=True,
boundinglat=None,
fix_aspect=True,
anchor=str('C'),
ax=None):
if projection != '... | __init__ | identifier_name | |
allskymap.py | lon is in the eastern hemisphere of the map wrt lon_0.
"""
if (lon-self._lon_0) % 360. <= self.east_lon:
return True
else:
return False
def geodesic(self, lon1, lat1, lon2, lat2, del_s=.01, clip=True, **kwargs):
"""
Plot a geodesic curve from (lon1, ... | fig = figure(figsize=(12,6))
# Set up the projection and draw a grid.
map = AllSkyMap(projection='hammer')
# Save the bounding limb to use as a clip path later.
limb = map.drawmapboundary(fill_color='white')
map.drawparallels(np.arange(-75,76,15), linewidth=0.5, dashes=[1,2],
labels=[1,... | conditional_block | |
account_credit_alloc.py | # Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... |
def delete(self, ids, **kw):
inv_ids = []
for obj in self.browse(ids):
inv_ids.append(obj.invoice_id.id)
inv_ids.append(obj.credit_id.id)
if obj.move_id:
obj.move_id.void()
obj.move_id.delete()
super().delete(ids, **kw)
... | new_id = super().create(vals, **kw)
inv_id = vals["invoice_id"]
cred_id = vals["credit_id"]
get_model("account.invoice").function_store([inv_id, cred_id])
self.post([new_id])
return new_id | identifier_body |
account_credit_alloc.py | # Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... | (Model):
_name = "account.credit.alloc"
_fields = {
"invoice_id": fields.Many2One("account.invoice", "Invoice", required=True, on_delete="cascade"),
"credit_id": fields.Many2One("account.invoice", "Credit Note", required=True, on_delete="cascade"),
"credit_type": fields.Char("Credit Type... | CreditAlloc | identifier_name |
account_credit_alloc.py | # Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... |
def post(self, ids, context={}):
settings = get_model("settings").browse(1)
obj = self.browse(ids)[0]
inv = obj.invoice_id
contact = inv.contact_id
cred = obj.credit_id
if cred.inv_type == "credit":
desc = "Credit allocation: %s" % cred.contact_id.name
... | if obj.move_id:
obj.move_id.void()
obj.move_id.delete()
super().delete(ids, **kw)
get_model("account.invoice").function_store(inv_ids) | random_line_split |
account_credit_alloc.py | # Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... |
else:
base_amt = cur_amt
acc_id = line.account_id.id
if not acc_id:
raise Exception("Missing line account")
amt = base_amt * sign
line_vals = {
"description": desc,
... | tax_vals = {
"tax_comp_id": comp_id,
"amount_base": base_amt,
"amount_tax": tax_amt,
}
taxes[comp_id] = tax_vals | conditional_block |
input.rs | use std::f64;
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
use glutin;
use glutin::{ElementState, EventsLoop, VirtualKeyCode};
use glutin::WindowEvent::*;
pub const INPUT_UP: usize = 0;
pub const INPUT_DOWN: usize = 1;
pub const INPUT_LEFT: usize = 2;
pub const INPUT_RIGHT: usize = 3;
enum MouseSt... |
fn get_binding(&self, key: &VirtualKeyCode) -> Option<usize> {
if let Some(action) = self.bindings.get(&key) {
Some(*action)
} else {
None
}
}
pub fn gather(&mut self, events_loop: &mut EventsLoop) -> bool {
self.delta_x = 0.0;
self.delta_y ... | {
self.bindings.insert(key, action);
} | identifier_body |
input.rs | use std::f64;
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
use glutin;
use glutin::{ElementState, EventsLoop, VirtualKeyCode};
use glutin::WindowEvent::*;
pub const INPUT_UP: usize = 0;
pub const INPUT_DOWN: usize = 1;
pub const INPUT_LEFT: usize = 2;
pub const INPUT_RIGHT: usize = 3;
enum MouseSt... | (&self, key: &VirtualKeyCode) -> Option<usize> {
if let Some(action) = self.bindings.get(&key) {
Some(*action)
} else {
None
}
}
pub fn gather(&mut self, events_loop: &mut EventsLoop) -> bool {
self.delta_x = 0.0;
self.delta_y = 0.0;
let m... | get_binding | identifier_name |
input.rs | use std::f64;
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
use glutin;
use glutin::{ElementState, EventsLoop, VirtualKeyCode};
use glutin::WindowEvent::*;
pub const INPUT_UP: usize = 0;
pub const INPUT_DOWN: usize = 1;
pub const INPUT_LEFT: usize = 2;
pub const INPUT_RIGHT: usize = 3;
enum MouseSt... | INPUT_RIGHT => &mut self.strafe_right,
_ => unimplemented!(),
}
}
} | fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut bool {
match index {
INPUT_UP => &mut self.move_forward,
INPUT_DOWN => &mut self.move_backward,
INPUT_LEFT => &mut self.strafe_left, | random_line_split |
input.rs | use std::f64;
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
use glutin;
use glutin::{ElementState, EventsLoop, VirtualKeyCode};
use glutin::WindowEvent::*;
pub const INPUT_UP: usize = 0;
pub const INPUT_DOWN: usize = 1;
pub const INPUT_LEFT: usize = 2;
pub const INPUT_RIGHT: usize = 3;
enum MouseSt... | ,
MouseMoved{ position: (x, y), .. } => self.set_mouse(x, y),
_ => {},
}
}
});
continue_game
}
}
impl Index<usize> for Input {
type Output = bool;
fn index<'a>(&'a self, index: usize) -> &'a bool {
match index {
... | {
self.mouse = MouseState::Released;
} | conditional_block |
checkboxes.rs | /*
* Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, ... |
},
PlusToggle => {
if self.widgets.plus_button.is_active() {
self.components.minus_button.emit(Uncheck);
}
else {
self.components.minus_button.emit(Check);
}
},
}
}
}
... | {
self.components.plus_button.emit(Check);
} | conditional_block |
checkboxes.rs | /*
* Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, ... | () {
let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed");
let plus_button = &widgets.plus_button;
let minus_button = &widgets.minus_button;
assert!(!plus_button.is_active());
assert!(!minus_button.is_active());
click(plus_button);
... | check_uncheck | identifier_name |
checkboxes.rs | /*
* Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, ... | } |
click(minus_button);
assert!(!plus_button.is_active());
assert!(minus_button.is_active());
} | random_line_split |
checkboxes.rs | /*
* Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, ... | }
}
impl Widget for Win {
type Root = Window;
fn root(&self) -> Self::Root {
self.widgets.window.clone()
}
fn view(relm: &Relm<Self>, _model: Self::Model) -> Self {
let vbox = gtk::Box::new(Vertical, 0);
let plus_button = vbox.add_widget::<CheckButton>("+");
let ... | {
match event {
Quit => gtk::main_quit(),
MinusToggle => {
if self.widgets.minus_button.is_active() {
self.components.plus_button.emit(Uncheck);
}
else {
self.components.plus_button.emit(Check);
... | identifier_body |
cell.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// 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 b... | (c: char, fg: Color, bg: Color) -> Cell {
Cell {
c: c.into(),
bg: bg,
fg: fg,
flags: Flags::empty(),
}
}
#[inline]
pub fn is_empty(&self) -> bool {
self.c == ' ' &&
self.bg == Color::Named(NamedColor::Background) &&
... | new | identifier_name |
cell.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// 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 b... |
}
impl Cell {
pub fn bold(&self) -> bool {
self.flags.contains(BOLD)
}
pub fn new(c: char, fg: Color, bg: Color) -> Cell {
Cell {
c: c.into(),
bg: bg,
fg: fg,
flags: Flags::empty(),
}
}
#[inline]
pub fn is_empty(&self) -... | {
let mut length = Column(0);
if self[Column(self.len() - 1)].flags.contains(WRAPLINE) {
return Column(self.len());
}
for (index, cell) in self[..].iter().rev().enumerate() {
if cell.c != ' ' {
length = Column(self.len() - index);
... | identifier_body |
cell.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// 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 b... |
}
length
}
}
impl Cell {
pub fn bold(&self) -> bool {
self.flags.contains(BOLD)
}
pub fn new(c: char, fg: Color, bg: Color) -> Cell {
Cell {
c: c.into(),
bg: bg,
fg: fg,
flags: Flags::empty(),
}
}
#[inli... | {
length = Column(self.len() - index);
break;
} | conditional_block |
cell.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// 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 b... | Cell {
c: c.into(),
bg: bg,
fg: fg,
flags: Flags::empty(),
}
}
#[inline]
pub fn is_empty(&self) -> bool {
self.c == ' ' &&
self.bg == Color::Named(NamedColor::Background) &&
!self.flags.contains(INVERSE)
}
... | random_line_split | |
app.py | """Main Tornado app."""
from tornado import gen
from tornado.options import parse_command_line
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application
import logging
from tornado.options import options
from settings import settings
from urls import url_patterns
... | IOLoop.current().run_sync(main)
IOLoop.current().start() | conditional_block | |
app.py | """Main Tornado app."""
from tornado import gen
from tornado.options import parse_command_line
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application
import logging
from tornado.options import options
from settings import settings
from urls import url_patterns
... |
if __name__ == "__main__":
IOLoop.current().run_sync(main)
IOLoop.current().start() | http_server.listen(options.port, options.host) | random_line_split |
app.py | """Main Tornado app."""
from tornado import gen
from tornado.options import parse_command_line
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application
import logging
from tornado.options import options
from settings import settings
from urls import url_patterns
... |
if __name__ == "__main__":
IOLoop.current().run_sync(main)
IOLoop.current().start()
| """Main function."""
logging.info('Parsing command line')
parse_command_line()
if options.debug is True:
logging.getLogger().setLevel(logging.DEBUG)
logging.info('Running in debug mode')
else:
logging.getLogger().setLevel(logging.INFO)
# Single db connection for everything t... | identifier_body |
app.py | """Main Tornado app."""
from tornado import gen
from tornado.options import parse_command_line
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application
import logging
from tornado.options import options
from settings import settings
from urls import url_patterns
... | ():
"""Main function."""
logging.info('Parsing command line')
parse_command_line()
if options.debug is True:
logging.getLogger().setLevel(logging.DEBUG)
logging.info('Running in debug mode')
else:
logging.getLogger().setLevel(logging.INFO)
# Single db connection for ever... | main | identifier_name |
variance-regions-direct.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {}
| main | identifier_name |
variance-regions-direct.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | #[rustc_variance]
struct Test3<'a, 'b, 'c> { //~ ERROR regions=[[+, +, +];[];[];[]]
x: extern "Rust" fn(&'a int),
y: extern "Rust" fn(&'b [int]),
c: extern "Rust" fn(&'c str),
}
// Mutability induces invariance:
#[rustc_variance]
struct Test4<'a, 'b:'a> { //~ ERROR regions=[[-, o];[];[];[]]
x: &'a mut... | // Those same annotations in function arguments become covariant:
| random_line_split |
ControlGame.ts | /**
* 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/.
*/
export interface ControlPoint {
faction: string;
id: string;
size: string;
x: number;
y: number;
};... |
}
export default ControlGame;
| {
let a = new ControlGame();
return a;
} | identifier_body |
ControlGame.ts | /**
* 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/.
*/
export interface ControlPoint {
faction: string;
id: string;
size: string;
x: number;
y: number;
};... | () {
let a = new ControlGame();
return a;
}
}
export default ControlGame;
| create | identifier_name |
ControlGame.ts | /**
* 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/.
*/
export interface ControlPoint {
faction: string;
id: string;
size: string;
x: number;
y: number;
};... | return a;
}
}
export default ControlGame; | let a = new ControlGame(); | random_line_split |
gruntfile.js | module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-includes');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.initConfig({
sass: {
options: {
sourceMap: true,
outputStyle: 'compressed'
},
portal: {
fi... | js: {
files: {
'resources/js/glasscityhacks.min.js': [
'src/lib/jquery/jquery-2.1.4.min.js',
'src/lib/scrollspy/jquery.scrollspy.js',
'src/lib/scrollto/jquery.scrollTo.min.js',
'src/js/**/*.js'
]
}
}
},
includes: {
views: {
cwd: 'src/views',
src: ['**/*.htm... | random_line_split | |
network_listener.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/. */
use bluetooth_traits::{BluetoothResponseListener, BluetoothResponseResult};
use net_traits::{Action, FetchResponse... |
impl<Listener: PreInvoke + Send + 'static> NetworkListener<Listener> {
pub fn notify<A: Action<Listener> + Send + 'static>(&self, action: A) {
let runnable = box ListenerRunnable {
context: self.context.clone(),
action: action,
};
let result = if let Some(ref wrapper... | } | random_line_split |
network_listener.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/. */
use bluetooth_traits::{BluetoothResponseListener, BluetoothResponseResult};
use net_traits::{Action, FetchResponse... | (&self) -> bool {
true
}
}
/// A runnable for moving the async network events between threads.
struct ListenerRunnable<A: Action<Listener> + Send + 'static, Listener: PreInvoke + Send> {
context: Arc<Mutex<Listener>>,
action: A,
}
impl<A: Action<Listener> + Send + 'static, Listener: PreInvoke + Se... | should_invoke | identifier_name |
network_listener.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/. */
use bluetooth_traits::{BluetoothResponseListener, BluetoothResponseResult};
use net_traits::{Action, FetchResponse... |
}
/// A gating mechanism that runs before invoking the runnable on the target thread.
/// If the `should_invoke` method returns false, the runnable is discarded without
/// being invoked.
pub trait PreInvoke {
fn should_invoke(&self) -> bool {
true
}
}
/// A runnable for moving the async network even... | {
self.notify(action);
} | identifier_body |
network_listener.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/. */
use bluetooth_traits::{BluetoothResponseListener, BluetoothResponseResult};
use net_traits::{Action, FetchResponse... | ;
if let Err(err) = result {
warn!("failed to deliver network data: {:?}", err);
}
}
}
// helps type inference
impl<Listener: FetchResponseListener + PreInvoke + Send + 'static> NetworkListener<Listener> {
pub fn notify_fetch(&self, action: FetchResponseMsg) {
self.notify(ac... | {
self.task_source.queue_wrapperless(runnable)
} | conditional_block |
ParseGlobalConfig.spec.js | 'use strict';
var request = require('request');
var Parse = require('parse/node').Parse;
var DatabaseAdapter = require('../src/DatabaseAdapter');
let database = DatabaseAdapter.getDatabaseConnection('test', 'test_');
describe('a GlobalConfig', () => {
beforeEach(function(done) {
database.rawCollection('_Global... |
}); | random_line_split | |
sports.ts | import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class Sports {
constructor(public http: Http) {
}
getSports(options){
return new Promise(resolve => { | this.http.post('http://localhost:8080/api/sports', JSON.stringify(options), {headers: headers})
.map(res => res.json())
.subscribe(data => {
resolve(data);
});
});
}
createSport(data){
return new Promise(resolve => {
let headers = new Headers();
... | let headers = new Headers();
headers.append('Content-Type', 'application/json');
| random_line_split |
sports.ts | import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class Sports {
constructor(public http: Http) {
}
getSports(options){
return new Promise(resolve => {
let headers = new Headers();
headers.appen... |
} | {
return new Promise(resolve => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://localhost:8080/api/create/session', JSON.stringify(data), {headers: headers})
.subscribe((data) => {
resolve(data);
});
})... | identifier_body |
sports.ts | import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class Sports {
constructor(public http: Http) {
}
getSports(options){
return new Promise(resolve => {
let headers = new Headers();
headers.appen... | (data){
return new Promise(resolve => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://localhost:8080/api/create/session', JSON.stringify(data), {headers: headers})
.subscribe((data) => {
resolve(data);
});
... | createSport | identifier_name |
NumericInput.js | /**
* Created by isattrash on 8/30/16.
*/
import React from 'react';
import InputValidator from '../../InputValidator/InputValidator';
class NumericInput extends InputValidator {
constructor(props) {
super(props);
}
render() {
return (
<div className={'relative-pos form-gro... |
}
export default NumericInput; | {
let numericPattern = /^\d*$/;
if(numericPattern.test(this.numericInputRef.value)) {
return true;
} else {
return false;
}
} | identifier_body |
NumericInput.js | /**
* Created by isattrash on 8/30/16.
*/
import React from 'react';
import InputValidator from '../../InputValidator/InputValidator';
class NumericInput extends InputValidator {
constructor(props) {
super(props);
}
render() {
return (
<div className={'relative-pos form-gro... |
}
}
export default NumericInput; | {
return false;
} | conditional_block |
NumericInput.js | /**
* Created by isattrash on 8/30/16.
*/
import React from 'react';
import InputValidator from '../../InputValidator/InputValidator';
class NumericInput extends InputValidator {
constructor(props) {
super(props);
}
| () {
return (
<div className={'relative-pos form-group' + super.getValidationClass()}>
<label htmlFor="numeric-input">Number:</label>
<input type="number"
ref={node => this.numericInputRef = node}
onChange={() => { super.o... | render | identifier_name |
NumericInput.js | /** | */
import React from 'react';
import InputValidator from '../../InputValidator/InputValidator';
class NumericInput extends InputValidator {
constructor(props) {
super(props);
}
render() {
return (
<div className={'relative-pos form-group' + super.getValidationClass()}>
... | * Created by isattrash on 8/30/16. | random_line_split |
Anim.js | 'use strict';
import core from 'metal';
import { dom, features } from 'metal-dom';
class Anim {
/**
* Emulates animation or transition end event, the end event with longer
* duration will be used by the emulation. If they have the same value,
* transitionend will be emulated.
* @param {!Element} element
* ... |
/**
* Emulates animation end event. If `opt_durationMs` not specified the value
* will read from computed style for animation-duration.
* @param {!Element} element
* @param {number=} opt_durationMs
* @return {!Object} Object containing `abort` function.
*/
static emulateAnimationEnd(element, opt_duratio... | {
if (this.getComputedDurationMs(element, 'animation') > this.getComputedDurationMs(element, 'transition')) {
return this.emulateEnd_(element, 'animation', opt_durationMs);
} else {
return this.emulateEnd_(element, 'transition', opt_durationMs);
}
} | identifier_body |
Anim.js | 'use strict';
import core from 'metal';
import { dom, features } from 'metal-dom';
class Anim {
/**
* Emulates animation or transition end event, the end event with longer
* duration will be used by the emulation. If they have the same value,
* transitionend will be emulated.
* @param {!Element} element
* ... |
var delayed = setTimeout(function() {
dom.triggerEvent(element, features.checkAnimationEventName()[type]);
}, duration);
var abort = function() {
clearTimeout(delayed);
hoistedEvtHandler.removeListener();
};
var hoistedEvtHandler = dom.once(element, type + 'end', abort);
return {
abort: abor... | {
duration = this.getComputedDurationMs(element, type);
} | conditional_block |
Anim.js | 'use strict';
import core from 'metal';
import { dom, features } from 'metal-dom';
class Anim {
/**
* Emulates animation or transition end event, the end event with longer
* duration will be used by the emulation. If they have the same value,
* transitionend will be emulated.
* @param {!Element} element
* ... | (element, opt_durationMs) {
if (this.getComputedDurationMs(element, 'animation') > this.getComputedDurationMs(element, 'transition')) {
return this.emulateEnd_(element, 'animation', opt_durationMs);
} else {
return this.emulateEnd_(element, 'transition', opt_durationMs);
}
}
/**
* Emulates animation en... | emulateEnd | identifier_name |
Anim.js | 'use strict';
import core from 'metal';
import { dom, features } from 'metal-dom';
class Anim {
/**
* Emulates animation or transition end event, the end event with longer
* duration will be used by the emulation. If they have the same value,
* transitionend will be emulated.
* @param {!Element} element
* ... | * Emulates transition or animation end.
* @param {!Element} element
* @param {string} type
* @param {number=} opt_durationMs
* @return {!Object} Object containing `abort` function.
* @protected
*/
static emulateEnd_(element, type, opt_durationMs) {
var duration = opt_durationMs;
if (!core.isDef(opt_d... |
/** | random_line_split |
LexerATNSimulator.py | t in config.state.transitions:
c = self.getEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon)
if c is not None:
currentAltReachedAcceptState = self.closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon)
return curr... | return "EOF" | conditional_block | |
LexerATNSimulator.py | self.line = 1
# The index of the character relative to the beginning of the line 0..n-1#/
self.column = 0
from antlr4.Lexer import Lexer
self.mode = Lexer.DEFAULT_MODE
# Used during DFA/ATN exec to record the most recent accept configuration info
self.prevAccept =... | debug = False
dfa_debug = False
MIN_DFA_EDGE = 0
MAX_DFA_EDGE = 127 # forces unicode to stay in ATN
ERROR = None
match_calls = 0
def __init__(self, recog:Lexer, atn:ATN, decisionToDFA:list, sharedContextCache:PredictionContextCache):
super().__init__(atn, sharedContextCache)
... | identifier_body | |
LexerATNSimulator.py | in config.state.transitions:
c = self.getEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon)
if c is not None:
currentAltReachedAcceptState = self.closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon)
return curren... |
def getTokenName(self, t:int):
if t==-1:
return "EOF" | random_line_split | |
LexerATNSimulator.py | optimization makes a lot of sense for loops within DFA.
# A character will take us back to an existing DFA state
# that already has lots of edges out of it. e.g., .* in comments.
# print("Target for:" + str(s) + " and:" + str(t))
target = self.getExistingTargetState(s, t... | getEpsilonTarget | identifier_name | |
behavior_prompt.tsx | /*
* Copyright 2020 ThoughtWorks, 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 agr... |
}
| {
switch (size) {
case Size.SMALL:
return css.small;
case Size.MEDIUM:
return css.medium;
default:
return css.small;
}
} | identifier_body |
behavior_prompt.tsx | /*
* Copyright 2020 ThoughtWorks, 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 agr... | case Direction.RIGHT:
return css.arrowRight;
case Direction.UP:
return css.arrowUp;
case Direction.DOWN:
return css.arrowDown;
default:
return css.arrowRight;
}
}
}
export enum Size {
SMALL, MEDIUM
}
class SizeTransformer {
static transform(size?: Size... | switch (direction) {
case Direction.LEFT:
return css.arrowLeft; | random_line_split |
behavior_prompt.tsx | /*
* Copyright 2020 ThoughtWorks, 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 agr... | (size?: Size, css: Styles = style) {
switch (size) {
case Size.SMALL:
return css.small;
case Size.MEDIUM:
return css.medium;
default:
return css.small;
}
}
}
| transform | identifier_name |
resume.ts | import type { ExternalMethods } from './types'
const resume: ExternalMethods['resume'] = async (pool, readModelName) => {
const {
PassthroughError, | inlineLedgerRunQuery,
inlineLedgerForceStop,
tablePrefix,
escapeId,
escapeStr,
} = pool
const ledgerTableNameAsId = escapeId(`${tablePrefix}__LEDGER__`)
try {
pool.activePassthrough = true
while (true) {
try {
await inlineLedgerForceStop(pool, readModelName)
awai... | random_line_split | |
resume.ts | import type { ExternalMethods } from './types'
const resume: ExternalMethods['resume'] = async (pool, readModelName) => {
const {
PassthroughError,
inlineLedgerRunQuery,
inlineLedgerForceStop,
tablePrefix,
escapeId,
escapeStr,
} = pool
const ledgerTableNameAsId = escapeId(`${tablePrefix}... | throw err
}
}
}
return {
type: 'build-direct-invoke',
payload: {
continue: true,
},
}
} finally {
pool.activePassthrough = false
}
}
export default resume
| {
try {
await inlineLedgerForceStop(pool, readModelName)
await inlineLedgerRunQuery(
`START TRANSACTION;
SELECT * FROM ${ledgerTableNameAsId}
WHERE \`EventSubscriber\` = ${escapeStr(readModelName)}
FOR UPDATE NOWAIT;
UPDATE ${ledgerTableNameA... | conditional_block |
connection.py | """Module containing Connection class, connections between source and target populations."""
# Copyright 2013 Allen Institute
# This file is part of dipde
# dipde 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 Foundatio... | (self):
"""Initialiaze a delay queue for the connection.
The delay attribute of the connection defines the transmission delay of
the signal from the souce to the target. Firing rate values from the
source population are held in a queue, discretized by the timestep, that
is roll... | initialize_delay_queue | identifier_name |
connection.py | """Module containing Connection class, connections between source and target populations."""
# Copyright 2013 Allen Institute
# This file is part of dipde
# dipde 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 Foundatio... |
else:
return self.source_gid_or_population
@property
def target(self):
if isinstance(self.target_gid_or_population, int):
if self.simulation is None:
return None
else:
return self.simulation.gid_dict[self.target_gid_o... | return self.simulation.gid_dict[self.source_gid_or_population] | conditional_block |
connection.py | """Module containing Connection class, connections between source and target populations."""
# Copyright 2013 Allen Institute
# This file is part of dipde
# dipde 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 Foundatio... | conn_dist = ConnectionDistribution(self.target.edges, self.weights, self.probs)
conn_dist.simulation = self.simulation
self.simulation.connection_distribution_collection.add_connection_distribution(conn_dist)
self.connection_distribution = self.simulation.connection_distribution_collecti... | random_line_split | |
connection.py | """Module containing Connection class, connections between source and target populations."""
# Copyright 2013 Allen Institute
# This file is part of dipde
# dipde 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 Foundatio... | self.delay_ind = None
self.simulation = None
for key in kwargs.keys():
assert key in ['class']
@property
def nsyn(self):
if isinstance(self.nsyn_input, (int, float)):
return self.nsyn_input
elif hasattr(self.nsyn_input, "__call__"):
... | self.source_gid_or_population = source
self.target_gid_or_population = target
# Used for jumping off point for making a matched nest simulation:
self.original_weights = weights
self.original_delays = delays
self.nsyn_input = nsyn
self.synaptic_weight_dis... | identifier_body |
abstractMode.ts | c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {EventEmitter} from 'vs/base/common/eventEmitter';
import... | case 14:
return (c >= _0 && c <= _9) || (c >= _a && c <= _d) || (c >= _A && c <= _D);
case 15:
return (c >= _0 && c <= _9) || (c >= _a && c <= _e) || (c >= _A && c <= _E);
default:
return (c >= _0 && c <= _9) || (c >= _a && c <= _f) || (c >= _A && c <= _F);
}
};
})();
export class FrankensteinM... | case 13:
return (c >= _0 && c <= _9) || (c >= _a && c <= _c) || (c >= _A && c <= _C); | random_line_split |
abstractMode.ts | ) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {EventEmitter} from 'vs/base/common/eventEmitter';
import ... |
}
}
function _createModeSupportChangedEvent | {
modes.SuggestRegistry.register(this.getId(), new TextualSuggestSupport(editorWorkerService, configurationService), true);
} | conditional_block |
abstractMode.ts | c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {EventEmitter} from 'vs/base/common/eventEmitter';
import... | (): void {
this.tokenizationSupport = this._sourceMode.tokenizationSupport;
}
}
export var isDigit:(character:string, base:number)=>boolean = (function () {
var _0 = '0'.charCodeAt(0),
_1 = '1'.charCodeAt(0),
_2 = '2'.charCodeAt(0),
_3 = '3'.charCodeAt(0),
_4 = '4'.charCodeAt(0),
_5 = '5'.charCodeAt(0),... | _assignSupports | identifier_name |
abstractMode.ts | ) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {EventEmitter} from 'vs/base/common/eventEmitter';
import ... |
public addSupportChangedListener(callback: (e: IModeSupportChangedEvent) => void) : IDisposable {
return this._eventEmitter.addListener2('modeSupportChanged', callback);
}
public setTokenizationSupport<T>(callback:(mode:modes.IMode) => T) : IDisposable {
var supportImpl = callback(this);
this['tokenizationS... | {
if (!this._simplifiedMode) {
this._simplifiedMode = new SimplifiedMode(this);
}
return this._simplifiedMode;
} | identifier_body |
validate-list-of-email-address-with-filter.py | #!/usr/bin/python
import sys
import re
re_valid_email = re.compile(r'^[-_0-9a-zA-Z]+@[0-9a-zA-Z]+\.[0-9a-zA-Z]{1,3}$')
def valid_email(s):
return not (re_valid_email.search(s) == None)
N = int(raw_input().strip())
A = []
for i in range(N):
|
A.sort()
V = filter(valid_email, A)
print V
#### INPUT ##
## 3
## lara@hackerrank.com
## brian-23@hackerrank.com
## britts_54@hackerrank.com
##
#### OUTPUT ##
## ['brian-23@hackerrank.com', 'britts_54@hackerrank.com', 'lara@hackerrank.com']
#### INPUT ##
## 5
## dheeraj-234@gmail.com
## itsallcrap
## harsh_1234@red... | A += [ str(raw_input().strip()) ] | conditional_block |
validate-list-of-email-address-with-filter.py | #!/usr/bin/python
import sys
import re
re_valid_email = re.compile(r'^[-_0-9a-zA-Z]+@[0-9a-zA-Z]+\.[0-9a-zA-Z]{1,3}$')
def valid_email(s):
|
N = int(raw_input().strip())
A = []
for i in range(N):
A += [ str(raw_input().strip()) ]
A.sort()
V = filter(valid_email, A)
print V
#### INPUT ##
## 3
## lara@hackerrank.com
## brian-23@hackerrank.com
## britts_54@hackerrank.com
##
#### OUTPUT ##
## ['brian-23@hackerrank.com', 'britts_54@hackerrank.com', 'lara... | return not (re_valid_email.search(s) == None) | identifier_body |
validate-list-of-email-address-with-filter.py | #!/usr/bin/python
import sys
import re
re_valid_email = re.compile(r'^[-_0-9a-zA-Z]+@[0-9a-zA-Z]+\.[0-9a-zA-Z]{1,3}$')
def valid_email(s):
return not (re_valid_email.search(s) == None)
N = int(raw_input().strip())
A = []
for i in range(N):
A += [ str(raw_input().strip()) ]
A.sort()
V = filter(valid_email, ... | #### OUTPUT ##
## ['dheeraj-234@gmail.com', 'harsh_1234@rediff.in', 'kunal_shin@iop.az'] | ## | random_line_split |
validate-list-of-email-address-with-filter.py | #!/usr/bin/python
import sys
import re
re_valid_email = re.compile(r'^[-_0-9a-zA-Z]+@[0-9a-zA-Z]+\.[0-9a-zA-Z]{1,3}$')
def | (s):
return not (re_valid_email.search(s) == None)
N = int(raw_input().strip())
A = []
for i in range(N):
A += [ str(raw_input().strip()) ]
A.sort()
V = filter(valid_email, A)
print V
#### INPUT ##
## 3
## lara@hackerrank.com
## brian-23@hackerrank.com
## britts_54@hackerrank.com
##
#### OUTPUT ##
## ['brian... | valid_email | identifier_name |
getCompilerOptionsFromTsConfig.ts | import { FileSystemHost, RealFileSystemHost, TransactionalFileSystem } from "../fileSystem";
import { CompilerOptions, ts } from "../typescript";
import { TsConfigResolver } from "./TsConfigResolver";
export interface CompilerOptionsFromTsConfigOptions {
encoding?: string;
fileSystem?: FileSystemHost;
}
expor... | (filePath: string, options: CompilerOptionsFromTsConfigOptions = {}): CompilerOptionsFromTsConfigResult {
// remember, this is a public function
const fileSystemWrapper = new TransactionalFileSystem(options.fileSystem || new RealFileSystemHost());
const tsConfigResolver = new TsConfigResolver(fileSystemWrap... | getCompilerOptionsFromTsConfig | identifier_name |
getCompilerOptionsFromTsConfig.ts | import { FileSystemHost, RealFileSystemHost, TransactionalFileSystem } from "../fileSystem";
import { CompilerOptions, ts } from "../typescript";
import { TsConfigResolver } from "./TsConfigResolver";
export interface CompilerOptionsFromTsConfigOptions {
encoding?: string;
fileSystem?: FileSystemHost;
}
expor... | const fileSystemWrapper = new TransactionalFileSystem(options.fileSystem || new RealFileSystemHost());
const tsConfigResolver = new TsConfigResolver(fileSystemWrapper, fileSystemWrapper.getStandardizedAbsolutePath(filePath), options.encoding || "utf-8");
return {
options: tsConfigResolver.getCompile... | random_line_split | |
getCompilerOptionsFromTsConfig.ts | import { FileSystemHost, RealFileSystemHost, TransactionalFileSystem } from "../fileSystem";
import { CompilerOptions, ts } from "../typescript";
import { TsConfigResolver } from "./TsConfigResolver";
export interface CompilerOptionsFromTsConfigOptions {
encoding?: string;
fileSystem?: FileSystemHost;
}
expor... | {
// remember, this is a public function
const fileSystemWrapper = new TransactionalFileSystem(options.fileSystem || new RealFileSystemHost());
const tsConfigResolver = new TsConfigResolver(fileSystemWrapper, fileSystemWrapper.getStandardizedAbsolutePath(filePath), options.encoding || "utf-8");
return {... | identifier_body | |
restaurant.js | var mod = angular.module('restaurant', ['ngResource', 'ngRoute']);
mod.factory('Restaurant', ['$resource',
function($resource) {
return $resource('/api/restaurants/restaurants/:slug', {}, {
query: {
method: 'GET',
isArray: true,
}
});
}
]);
mod.factory('Ra... |
mod.controller('SearchCtrl', ['$scope', '$http', '$location', function($scope, $http, $location){
$scope.getRestaurants = function(val) {
return $http.get('/api/restaurants/restaurantsearch', {
params: {
name: val
}
}).then(function(response){
... | }
]); | random_line_split |
create-github-repo.ts | import * as denodeify from 'denodeify';
const Task = require('../ember-cli/lib/models/task');
const SilentError = require('silent-error');
import { exec } from 'child_process';
import * as https from 'https';
import { oneLine } from 'common-tags';
export default Task.extend({
run: function(commandOptions: any) {
... |
});
req.write(postData);
req.end();
});
});
}
});
| {
reject(new SilentError(oneLine`
Failed to create GitHub repo. Error: ${response.statusCode} ${response.statusMessage}
`));
} | conditional_block |
create-github-repo.ts | import * as denodeify from 'denodeify';
const Task = require('../ember-cli/lib/models/task');
const SilentError = require('silent-error');
import { exec } from 'child_process';
import * as https from 'https';
import { oneLine } from 'common-tags';
| run: function(commandOptions: any) {
const ui = this.ui;
let promise: Promise<any>;
// declared here so that tests can stub exec
const execPromise = denodeify(exec);
if (/.+/.test(commandOptions.ghToken) && /\w+/.test(commandOptions.ghUsername)) {
promise = Promise.resolve({
ghToke... | export default Task.extend({ | random_line_split |
tree_gravity.rs | //! Simple integration tests oriented towards gravity computations
extern crate acacia;
extern crate approx;
extern crate nalgebra;
extern crate quickcheck;
use acacia::partition::Ncube;
use acacia::{AssociatedData, DataQuery, Node, Positioned, Tree};
use approx::Relative;
use nalgebra::{distance, zero, Point2, Point... | })
.map(|&(com, m)| newton((m, com), test_point))
.fold(zero::<Vector3<f64>>(), |a, b| a + b);
// Now the tree gravity should approximate the exact one, within 10 %
TestResult::from_bool(
Relative::default()
.epsilon(0.1 * simple_gravity.n... | let &(ref center_of_mass, _) = node.data();
let d = distance(&test_point, center_of_mass);
let delta = distance(&node.partition().center(), center_of_mass);
d < node.partition().width() / theta + delta | random_line_split |
tree_gravity.rs | //! Simple integration tests oriented towards gravity computations
extern crate acacia;
extern crate approx;
extern crate nalgebra;
extern crate quickcheck;
use acacia::partition::Ncube;
use acacia::{AssociatedData, DataQuery, Node, Positioned, Tree};
use approx::Relative;
use nalgebra::{distance, zero, Point2, Point... | return TestResult::discard();
}
}
}
// (T, T, T) -> Point3<T>
fn pnt<T: Debug + PartialEq + Copy + 'static>(p: (T, T, T)) -> Point3<T> {
let (x, y, z) = p;
Point3::new(x, y, z)
}
let test_point = pnt(test_poi... | fn tree_gravity_approx(
starfield: Vec<(f64, (f64, f64, f64))>,
test_point: (f64, f64, f64),
) -> TestResult {
// We want to have at least one star
if starfield.is_empty() {
return TestResult::discard();
}
// Only test positive masses
if starfi... | identifier_body |
tree_gravity.rs | //! Simple integration tests oriented towards gravity computations
extern crate acacia;
extern crate approx;
extern crate nalgebra;
extern crate quickcheck;
use acacia::partition::Ncube;
use acacia::{AssociatedData, DataQuery, Node, Positioned, Tree};
use approx::Relative;
use nalgebra::{distance, zero, Point2, Point... | {
fn tree_gravity_approx(
starfield: Vec<(f64, (f64, f64, f64))>,
test_point: (f64, f64, f64),
) -> TestResult {
// We want to have at least one star
if starfield.is_empty() {
return TestResult::discard();
}
// Only test positive masses
if sta... | ee_gravity_approx() | identifier_name |
tree_gravity.rs | //! Simple integration tests oriented towards gravity computations
extern crate acacia;
extern crate approx;
extern crate nalgebra;
extern crate quickcheck;
use acacia::partition::Ncube;
use acacia::{AssociatedData, DataQuery, Node, Positioned, Tree};
use approx::Relative;
use nalgebra::{distance, zero, Point2, Point... | lse {
(orig, zero())
}
},
)
.expect("Couldn't construct tree");
let theta = 0.5; // A bit arbitrary but this appears to work
let tree_gravity = tree
.query_data(|node| {
let &(ref center_of_mass, _) = node.data()... | (com1 + (com2 - com1) * (m2 / (m1 + m2)), m1 + m2)
} e | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.