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 |
|---|---|---|---|---|
1.run_find_repos.py | from glob import glob
import numpy
import pickle
import os
# Run iterations of "count" to count the number of terms in each folder of zipped up pubmed articles
home = os.environ["HOME"]
scripts = "%s/SCRIPT/repofish/analysis/methods" %(home)
base = "%s/data/pubmed" %os.environ["LAB"]
outfolder = "%s/repos" %(base)
ar... |
subset = folders[start:end]
script_file = "%s/findgithub_%s.job" %(scripts,i)
filey = open(script_file,'w')
filey.writelines("#!/bin/bash\n")
filey.writelines("#SBATCH --job-name=%s\n" %i)
filey.writelines("#SBATCH --output=.out/%s.out\n" %i)
filey.writelines("#SBATCH --error=.out/%s.err\n... | end = len(folders) | conditional_block |
div.rs | #![feature(core, core_simd)] | #[cfg(test)]
mod tests {
use core::simd::u32x4;
// #[simd]
// #[derive(Copy, Clone, Debug)]
// #[repr(C)]
// pub struct u32x4(pub u32, pub u32, pub u32, pub u32);
#[test]
fn div_test1() {
let x: u32x4 = u32x4(
0, 1, 2, 3
);
let y: u32x4 = u32x4(
2, 2, 2, 2
);
let z: u32x... | extern crate core;
| random_line_split |
div.rs | #![feature(core, core_simd)]
extern crate core;
#[cfg(test)]
mod tests {
use core::simd::u32x4;
// #[simd]
// #[derive(Copy, Clone, Debug)]
// #[repr(C)]
// pub struct u32x4(pub u32, pub u32, pub u32, pub u32);
#[test]
fn div_test1() |
}
| {
let x: u32x4 = u32x4(
0, 1, 2, 3
);
let y: u32x4 = u32x4(
2, 2, 2, 2
);
let z: u32x4 = x / y;
let result: String = format!("{:?}", z);
assert_eq!(result, "u32x4(0, 0, 1, 1)".to_string());
} | identifier_body |
div.rs | #![feature(core, core_simd)]
extern crate core;
#[cfg(test)]
mod tests {
use core::simd::u32x4;
// #[simd]
// #[derive(Copy, Clone, Debug)]
// #[repr(C)]
// pub struct u32x4(pub u32, pub u32, pub u32, pub u32);
#[test]
fn | () {
let x: u32x4 = u32x4(
0, 1, 2, 3
);
let y: u32x4 = u32x4(
2, 2, 2, 2
);
let z: u32x4 = x / y;
let result: String = format!("{:?}", z);
assert_eq!(result, "u32x4(0, 0, 1, 1)".to_string());
}
}
| div_test1 | identifier_name |
DefaultPreferences.js | /**
* Manages the default preferences used in the app. These can be overriden by explicit values set using
* PreferenceStorage through the PreferenceDialog
* @author Patrick Oladimeji
* @date 25/06/2015 9:25:20 AM
*/
define(function (require, exports, module) {
"use strict";
var preferenceKeys = requir... |
DefaultPreferences.prototype.get = function (key) {
return prefs[key];
};
module.exports = {
getInstance: function () {
instance = instance || new DefaultPreferences();
return instance;
}
};
});
| {
prefs[preferenceKeys.BACKUP_INTERVAL] = 60 * 10; //in seconds
prefs[preferenceKeys.REMEMBER_LAST_DIRECTORY] = true;
prefs[preferenceKeys.REMEMEBER_ENABLED_PLUGINS] = true;
prefs[preferenceKeys.LAST_DIRECTORY_VISITED] = "~";
prefs[preferenceKeys.WALL_CLOCK_NAME] = "tick";
... | identifier_body |
DefaultPreferences.js | /**
* Manages the default preferences used in the app. These can be overriden by explicit values set using
* PreferenceStorage through the PreferenceDialog
* @author Patrick Oladimeji
* @date 25/06/2015 9:25:20 AM
*/
define(function (require, exports, module) {
"use strict";
| Pictures: "~/Pictures" };
function DefaultPreferences() {
prefs[preferenceKeys.BACKUP_INTERVAL] = 60 * 10; //in seconds
prefs[preferenceKeys.REMEMBER_LAST_DIRECTORY] = true;
prefs[preferenceKeys.REMEMEBER_ENABLED_PLUGINS] = true;
prefs[preferenceKeys.LAST_DIRECTORY... | var preferenceKeys = require("preferences/PreferenceKeys");
var prefs = {}, instance;
var paths = { Desktop: "~/Desktop",
Documents: "~/Documents", | random_line_split |
DefaultPreferences.js | /**
* Manages the default preferences used in the app. These can be overriden by explicit values set using
* PreferenceStorage through the PreferenceDialog
* @author Patrick Oladimeji
* @date 25/06/2015 9:25:20 AM
*/
define(function (require, exports, module) {
"use strict";
var preferenceKeys = requir... | () {
prefs[preferenceKeys.BACKUP_INTERVAL] = 60 * 10; //in seconds
prefs[preferenceKeys.REMEMBER_LAST_DIRECTORY] = true;
prefs[preferenceKeys.REMEMEBER_ENABLED_PLUGINS] = true;
prefs[preferenceKeys.LAST_DIRECTORY_VISITED] = "~";
prefs[preferenceKeys.WALL_CLOCK_NAME] = "tick";
... | DefaultPreferences | identifier_name |
pipe.ts | import {ABSTRACT, BaseException, CONST} from 'angular2/src/facade/lang';
import {ChangeDetectorRef} from '../change_detector_ref';
/**
* Indicates that the result of a {@link Pipe} transformation has changed even though the reference
* has not changed.
*
* The wrapped value will be unwrapped by change detection, a... | {
constructor(public wrapped: any) {}
static wrap(value: any): WrappedValue {
var w = _wrappedValues[_wrappedIndex++ % 5];
w.wrapped = value;
return w;
}
}
var _wrappedValues = [
new WrappedValue(null),
new WrappedValue(null),
new WrappedValue(null),
new WrappedValue(null),
new WrappedVal... | WrappedValue | identifier_name |
pipe.ts | import {ABSTRACT, BaseException, CONST} from 'angular2/src/facade/lang';
import {ChangeDetectorRef} from '../change_detector_ref';
/**
* Indicates that the result of a {@link Pipe} transformation has changed even though the reference
* has not changed.
*
* The wrapped value will be unwrapped by change detection, a... |
onDestroy(): void {}
transform(value: any, args: List<any>): any { return _abstract(); }
}
/**
*
*/
export interface PipeFactory {
supports(obs): boolean;
create(cdRef: ChangeDetectorRef): Pipe;
}
function _abstract() {
throw new BaseException('This method is abstract');
}
| { return true; } | identifier_body |
pipe.ts | import {ABSTRACT, BaseException, CONST} from 'angular2/src/facade/lang';
import {ChangeDetectorRef} from '../change_detector_ref';
/**
* Indicates that the result of a {@link Pipe} transformation has changed even though the reference
* has not changed.
*
* The wrapped value will be unwrapped by change detection, a... | * onDestroy() {}
*
* transform(value, args = []) {
* return `${value}${value}`;
* }
* }
* ```
*/
export interface Pipe {
/**
* Query if a pipe supports a particular object instance.
*/
supports(obj): boolean;
onDestroy(): void;
transform(value: any, args: List<any>): any;
}
/**
* Provide... | random_line_split | |
settings.py | # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
DEBUG = True
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WAR... |
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'MST'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR+... | }
| random_line_split |
downloads.py | (str, enum.Enum):
"""Enum for supported hash URL schemes"""
chromium = 'chromium'
class HashMismatchError(BaseException):
"""Exception for computed hashes not matching expected hashes"""
class DownloadInfo: #pylint: disable=too-few-public-methods
"""Representation of an downloads.ini file for downlo... | HashesURLEnum | identifier_name | |
downloads.py | '): schema.Or(ExtractorEnum.TAR, ExtractorEnum.SEVENZIP,
ExtractorEnum.WINRAR),
schema.Optional(schema.Or(*_hashes)): schema.And(str, len),
schema.Optional('hash_url'): lambda x: DownloadInfo._is_hash_url(x), #pylint: disable=unnecessary-lambda... |
def _parse_data(self, path):
"""
Parses an INI file located at path
Raises schema.SchemaError if validation fails
"""
def _section_generator(data):
for section in data:
if section == configparser.DEFAULTSECT:
continue
... | if name in self._passthrough_properties:
return self._section_dict.get(name, fallback=None)
if name == 'hashes':
hashes_dict = {}
for hash_name in (*self._hashes, 'hash_url'):
value = self._section_dict.get(hash_name, fallback=None)
... | identifier_body |
downloads.py | '): schema.Or(ExtractorEnum.TAR, ExtractorEnum.SEVENZIP,
ExtractorEnum.WINRAR),
schema.Optional(schema.Or(*_hashes)): schema.And(str, len),
schema.Optional('hash_url'): lambda x: DownloadInfo._is_hash_url(x), #pylint: disable=unnecessary-lambda... |
# File name for partially download file
tmp_file_path = file_path.with_name(file_path.name + '.partial')
if tmp_file_path.exists():
get_logger().debug('Resuming downloading URL %s ...', url)
else:
get_logger().debug('Downloading URL %s ...', url)
# Perform download
if shutil.... | get_logger().info('%s already exists. Skipping download.', file_path)
return | conditional_block |
downloads.py | _passthrough_properties = (*_nonempty_keys, *_optional_keys, 'extractor', 'output_path')
_ini_vars = {
'_chromium_version': get_chromium_version(),
}
@staticmethod
def _is_hash_url(value):
return value.count(DownloadInfo.hash_url_delimiter) == 2 and value.split(
Download... | 'version',
'strip_leading_dirs',
) | random_line_split | |
pipe_transform.d.ts | /**
* To create a Pipe, you must implement this interface.
*
* Angular invokes the `transform` method with the value of a binding
* as the first argument, and any parameters as the second argument in list form.
*
* ## Syntax
*
* `value | pipeName[:arg0[:arg1...]]`
*
* ### Example ([live demo](http:/... | *
* @Pipe({name: 'repeat'})
* export class RepeatPipe implements PipeTransform {
* transform(value: any, args: any[] = []) {
* if (args.length == 0) {
* throw new Error('repeat pipe requires one argument');
* }
* let times: number = args[0];
* return value.repeat(times);
* }... | random_line_split | |
test_logging_support.py | #
# LMirror is Copyright (C) 2010 Robert Collins <robertc@robertcollins.net>
#
# LMirror 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... | resources = [('logging', LoggingResourceManager())]
def test_configure_logging_sets_converter(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out)
self.assertEqual(c_log, logging.root.handlers[0])
self.assertEqual(f_log, logging.root.handlers[1])
... | identifier_body | |
test_logging_support.py | #
# LMirror is Copyright (C) 2010 Robert Collins <robertc@robertcollins.net>
#
# LMirror 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... | (self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out)
self.assertEqual(c_log, logging.root.handlers[0])
self.assertEqual(f_log, logging.root.handlers[1])
self.assertEqual(None, c_log.formatter)
self.assertEqual(formatter, f_log.formatte... | test_configure_logging_sets_converter | identifier_name |
test_logging_support.py | #
# LMirror is Copyright (C) 2010 Robert Collins <robertc@robertcollins.net>
#
# LMirror 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... | import logging
import os.path
import time
from l_mirror import logging_support
from l_mirror.tests import ResourcedTestCase
from l_mirror.tests.logging_resource import LoggingResourceManager
from l_mirror.tests.stubpackage import TempDirResource
class TestLoggingSetup(ResourcedTestCase):
resources = [('logging'... | """Tests for logging support code."""
from StringIO import StringIO | random_line_split |
train_utils.py | truncate_data']:
annos = annos[:10]
for epoch in itertools.count():
random.shuffle(annos)
for anno in annos:
I = imread(anno.imageName)
#Skip Greyscale images
if len(I.shape) < 3:
continue
if I.shape[2] == 4:
I = I[:, :... | def load_data_gen(H, phase, jitter):
grid_size = H['grid_width'] * H['grid_height']
data = load_idl_tf(H["data"]['%s_idl' % phase], H, jitter={'train': jitter, 'test': False}[phase])
for d in data:
output = {}
rnn_len = H["rnn_len"]
flags = d['flags'][0, :, 0, 0:rnn_len, 0]
... | v[n] = 1.
return v
| random_line_split |
train_utils.py | truncate_data']:
annos = annos[:10]
for epoch in itertools.count():
random.shuffle(annos)
for anno in annos:
I = imread(anno.imageName)
#Skip Greyscale images
if len(I.shape) < 3:
continue
if I.shape[2] == 4:
I = I[:, :... |
def add_rectangles(H, orig_image, confidences, boxes, use_stitching=False, rnn_len=1, min_conf=0.1, show_removed=True, tau=0.25, show_suppressed=True):
image = np.copy(orig_image[0])
num_cells = H["grid_height"] * H["grid_width"]
boxes_r = np.reshape(boxes, (-1,
H["grid_he... | grid_size = H['grid_width'] * H['grid_height']
data = load_idl_tf(H["data"]['%s_idl' % phase], H, jitter={'train': jitter, 'test': False}[phase])
for d in data:
output = {}
rnn_len = H["rnn_len"]
flags = d['flags'][0, :, 0, 0:rnn_len, 0]
boxes = np.transpose(d['boxes'][0, :, :... | identifier_body |
train_utils.py | truncate_data']:
annos = annos[:10]
for epoch in itertools.count():
random.shuffle(annos)
for anno in annos:
I = imread(anno.imageName)
#Skip Greyscale images
if len(I.shape) < 3:
continue
if I.shape[2] == 4:
I = I[:, :... | (box1, box2):
return intersection(box1, box2) / union(box1, box2)
def to_idx(vec, w_shape):
'''
vec = (idn, idh, idw)
w_shape = [n, h, w, c]
'''
return vec[:, 2] + w_shape[2] * (vec[:, 1] + w_shape[1] * vec[:, 0])
def interp(w, i, channel_dim):
'''
Input:
w: A 4D block tensor o... | iou | identifier_name |
train_utils.py | truncate_data']:
annos = annos[:10]
for epoch in itertools.count():
random.shuffle(annos)
for anno in annos:
I = imread(anno.imageName)
#Skip Greyscale images
if len(I.shape) < 3:
continue
if I.shape[2] == 4:
I = I[:, :... |
if show_suppressed:
pairs = [(all_rects_r, (255, 0, 0))]
else:
pairs = []
pairs.append((acc_rects, (0, 255, 0)))
for rect_set, color in pairs:
for rect in rect_set:
if rect.confidence > min_conf:
cv2.rectangle(image,
(rect.cx-int... | acc_rects = all_rects_r | conditional_block |
str.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 std::from_str::FromStr;
use std::hash::{Hash, sip};
use std::path::BytesContainer;
use std::str;
#[deriving(E... | (&self) -> bool {
// Classifications of characters necessary for the [CRLF] (SP|HT) rule
#[deriving(PartialEq)]
enum PreviousCharacter {
Other,
CR,
LF,
SPHT // SP or HT
}
let ByteString(ref vec) = *self;
let mut prev = Other... | is_field_value | identifier_name |
str.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 std::from_str::FromStr;
use std::hash::{Hash, sip};
use std::path::BytesContainer;
use std::str;
#[deriving(E... |
pub fn as_str<'a>(&'a self) -> Option<&'a str> {
let ByteString(ref vec) = *self;
str::from_utf8(vec.as_slice())
}
pub fn as_slice<'a>(&'a self) -> &'a [u8] {
let ByteString(ref vector) = *self;
vector.as_slice()
}
pub fn len(&self) -> uint {
let ByteString... | {
ByteString(value)
} | identifier_body |
str.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 std::from_str::FromStr;
use std::hash::{Hash, sip};
use std::path::BytesContainer;
use std::str;
#[deriving(E... |
pub fn to_lower(&self) -> ByteString {
let ByteString(ref vec) = *self;
ByteString::new(vec.iter().map(|&x| {
if x > 'A' as u8 && x < 'Z' as u8 {
x + ('a' as u8) - ('A' as u8)
} else {
x
}
}).collect())
}
pub fn is... | // XXXManishearth make this more efficient
self.to_lower() == other.to_lower()
} | random_line_split |
main.rs | #[derive(Debug, Clone)]
struct Node {
x: usize,
y: usize,
value: String,
}
#[derive(Debug, Clone)]
struct Edge {
edge: bool,
node: Option<String>,
}
#[derive(Debug)]
struct Graphadj {
nodenums: usize,
graphadj: Vec<Vec<Edge>>,
}
impl Node {
fn new(x: usize, y:usize, value: String) -> ... | impl Graphadj {
fn new(nums: usize) -> Self {
Graphadj {
nodenums: nums,
graphadj: vec![vec![Edge::new();nums];nums]
}
}
fn insert_edge(&mut self, v: Node) {
match v.x < self.nodenums && v.y < self.nodenums {
true => {
self.graphad... | }
}
| random_line_split |
main.rs | #[derive(Debug, Clone)]
struct Node {
x: usize,
y: usize,
value: String,
}
#[derive(Debug, Clone)]
struct | {
edge: bool,
node: Option<String>,
}
#[derive(Debug)]
struct Graphadj {
nodenums: usize,
graphadj: Vec<Vec<Edge>>,
}
impl Node {
fn new(x: usize, y:usize, value: String) -> Self {
Node{
x: x,
y: y,
value: value,
}
}
}
impl Edge {
fn ne... | Edge | identifier_name |
main.rs | #[derive(Debug, Clone)]
struct Node {
x: usize,
y: usize,
value: String,
}
#[derive(Debug, Clone)]
struct Edge {
edge: bool,
node: Option<String>,
}
#[derive(Debug)]
struct Graphadj {
nodenums: usize,
graphadj: Vec<Vec<Edge>>,
}
impl Node {
fn new(x: usize, y:usize, value: String) -> ... |
fn insert_edge(&mut self, v: Node) {
match v.x < self.nodenums && v.y < self.nodenums {
true => {
self.graphadj[v.x][v.y] = Edge::have_edge(v.value.clone());
self.graphadj[v.y][v.x] = Edge::have_edge(v.value);
}
false => {
... | {
Graphadj {
nodenums: nums,
graphadj: vec![vec![Edge::new();nums];nums]
}
} | identifier_body |
main.rs | #[derive(Debug, Clone)]
struct Node {
x: usize,
y: usize,
value: String,
}
#[derive(Debug, Clone)]
struct Edge {
edge: bool,
node: Option<String>,
}
#[derive(Debug)]
struct Graphadj {
nodenums: usize,
graphadj: Vec<Vec<Edge>>,
}
impl Node {
fn new(x: usize, y:usize, value: String) -> ... |
}
}
}
fn main() {
let mut g = Graphadj::new(2);
let v1 = Node::new(0, 1,"v1".to_string());
g.insert_edge(v1);
println!("{:?}", g);
}
| {
panic!("your nodeid is bigger than nodenums!")
} | conditional_block |
utils.py | (self):
"""Map disk image as a device."""
SyncFileSystem()
kpartx_cmd = ['kpartx', '-a', '-v', '-s', self._file_path]
output = RunCommand(kpartx_cmd)
devs = []
for line in output.splitlines():
split_line = line.split()
if (len(split_line) > 2 and split_line[0] == 'add'
and ... | __enter__ | identifier_name | |
utils.py | devs.append('/dev/mapper/' + split_line[2])
time.sleep(2)
return devs
def __exit__(self, unused_exc_type, unused_exc_value, unused_exc_tb):
"""Unmap disk image as a device.
Args:
unused_exc_type: unused.
unused_exc_value: unused.
unused_exc_tb: unused.
"""
SyncFileSystem()... |
mkfs_cmd = ['mkfs', '-t', fs_type, dev_path]
RunCommand(mkfs_cmd)
if fs_type is 'xfs':
set_uuid_cmd = ['xfs_admin', '-U', uuid, dev_path]
else:
set_uuid_cmd = ['tune2fs', '-U', uuid, dev_path]
RunCommand(set_uuid_cmd)
return uuid
def Rsync(src, dest, exclude_file, ignore_hard_links, recursive,... | raise MakeFileSystemException(dev_path) | conditional_block |
utils.py | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for image bundling tool."""
import logging
import os
import subprocess
import time
import urllib2
METADATA_URL_PREFIX = 'http... | #
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, | random_line_split | |
utils.py | devs.append('/dev/mapper/' + split_line[2])
time.sleep(2)
return devs
def __exit__(self, unused_exc_type, unused_exc_value, unused_exc_tb):
"""Unmap disk image as a device.
Args:
unused_exc_type: unused.
unused_exc_value: unused.
unused_exc_tb: unused.
"""
SyncFileSystem()... | if xattrs:
rsync_cmd.append('--xattrs')
if exclude_file:
rsync_cmd.append('--exclude-from=' + exclude_file)
rsync_cmd.extend([src, dest])
logging.debug('Calling: %s', repr(rsync_cmd))
if exclude_file:
logging.debug('Contents of exclude file %s:', exclude_file)
with open(exclude_file, 'rb') as... | """Copy files from specified directory using rsync.
Args:
src: Source location to copy.
dest: Destination to copy files to.
exclude_file: A path to a file which contains a list of exclude from copy
filters.
ignore_hard_links: If True a hard links are copied as a separate files. If
False, ... | identifier_body |
bindings.ts | 'use strict';
import {compileExpression} from './bindings';
import {Meta} from './tree';
import * as utils from './utils';
export class AttributeBinding {
attr: Attr;
VM: Function;
vm: AttributeCtrl;
constructor(attr: Attr, VM: Function) {
this.attr = attr;
this.VM = VM;
}
refreshAndPhase(elemen... | (): boolean {return !this.vm}
}
export class AttributeInterpolation {
attr: Attr;
expression: TextExpression;
constructor(attr: Attr) {
this.attr = attr;
this.expression = compileInterpolation(attr.value);
}
}
// Problem: provides access to globals.
export function compileExpression(expression: string... | isNew | identifier_name |
bindings.ts | 'use strict';
import {compileExpression} from './bindings';
import {Meta} from './tree';
import * as utils from './utils';
export class AttributeBinding {
attr: Attr;
VM: Function;
vm: AttributeCtrl;
constructor(attr: Attr, VM: Function) |
refreshAndPhase(element: Element, meta: Meta): boolean {
this.refreshState(element, meta);
return this.phase();
}
refreshState(element: Element, meta: Meta): void {
if (!this.isNew) return;
let attr = this.attr;
this.vm = utils.instantiate(this.VM, {
attribute: attr,
element: el... | {
this.attr = attr;
this.VM = VM;
} | identifier_body |
bindings.ts | 'use strict';
import {compileExpression} from './bindings';
import {Meta} from './tree';
import * as utils from './utils';
export class AttributeBinding {
attr: Attr;
VM: Function;
vm: AttributeCtrl;
constructor(attr: Attr, VM: Function) {
this.attr = attr;
this.VM = VM;
}
refreshAndPhase(elemen... | this.vm.onDestroy();
}
this.vm = null;
}
get isNew(): boolean {return !this.vm}
}
export class AttributeInterpolation {
attr: Attr;
expression: TextExpression;
constructor(attr: Attr) {
this.attr = attr;
this.expression = compileInterpolation(attr.value);
}
}
// Problem: provides ac... | random_line_split | |
bindings.ts | 'use strict';
import {compileExpression} from './bindings';
import {Meta} from './tree';
import * as utils from './utils';
export class AttributeBinding {
attr: Attr;
VM: Function;
vm: AttributeCtrl;
constructor(attr: Attr, VM: Function) {
this.attr = attr;
this.VM = VM;
}
refreshAndPhase(elemen... |
return false;
}
destroy(): void {
utils.assert(!!this.vm, `unexpected destroy() call on binding without vm:`, this);
if (typeof this.vm.onDestroy === 'function') {
this.vm.onDestroy();
}
this.vm = null;
}
get isNew(): boolean {return !this.vm}
}
export class AttributeInterpolation ... | {
return this.vm.onPhase(), true;
} | conditional_block |
datepicker-section.ts | import {Component} from 'angular2/core';
import {CORE_DIRECTIVES} from 'angular2/common';
import {TAB_DIRECTIVES} from '../../ng2-bootstrap';
import {DatepickerDemo} from './datepicker/datepicker-demo';
let name = 'Datepicker';
let src = 'https://github.com/valor-software/ng2-bootstrap/blob/master/components/datepick... | <hr>
<div class="description">${titleDoc}</div>
<br/>
<div class="example">
<h2>Example</h2>
<div class="card card-block panel panel-default panel-body">
<datepicker-demo></datepicker-demo>
</div>
</div>
<br/>
<div class="markup">
<tabset>
... | selector: 'datepicker-section',
template: `
<section id="${name.toLowerCase()}">
<h1>${name}<small>(<a href="${src}">src</a>)</small></h1>
| random_line_split |
datepicker-section.ts | import {Component} from 'angular2/core';
import {CORE_DIRECTIVES} from 'angular2/common';
import {TAB_DIRECTIVES} from '../../ng2-bootstrap';
import {DatepickerDemo} from './datepicker/datepicker-demo';
let name = 'Datepicker';
let src = 'https://github.com/valor-software/ng2-bootstrap/blob/master/components/datepick... | {
}
| DatepickerSection | identifier_name |
gardens_wysiwyg.js | (function ($) {
Drupal.gardens_wysiwgy = Drupal.gardens_wysiwyg || {};
Drupal.behaviors.gardens_wysiwyg = {
attach: function(context, settings) {
if (typeof CKEDITOR != 'undefined') {
// Bind events to handle enabling and disabling of the WYSIWYG.
CKEDITOR.on('instanceReady', Drupal.behaviors.garden... |
};
})(jQuery); | {
var $wrapper = $('#' + params.field).parents('.form-textarea-wrapper:first');
$wrapper.removeOnce('textarea').removeClass('.resizable-textarea')
.find('.grippie').remove();
} | conditional_block |
gardens_wysiwyg.js | (function ($) {
Drupal.gardens_wysiwgy = Drupal.gardens_wysiwyg || {};
Drupal.behaviors.gardens_wysiwyg = {
attach: function(context, settings) {
if (typeof CKEDITOR != 'undefined') {
// Bind events to handle enabling and disabling of the WYSIWYG.
CKEDITOR.on('instanceReady', Drupal.behaviors.garden... | }
};
/**
* Overides the default attach behavior for text formats without an editor
*/
Drupal.wysiwyg.editor.attach.none = function(context, params, settings) {
var $field = $('#' + params.field);
var $original = $('#' + params.trigger);
var $clone = $original.clone().val($original.val());
var $container = ... | $(this).closest('.text-format-wrapper').find('.wysiwyg-toggle-wrapper a').click();
} | random_line_split |
test_leave_period.py | # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import unittest
import frappe
import erpnext
test_dependencies = ["Employee", "Leave Type", "Leave Policy"]
class TestLeavePeriod(unittest.TestCase):
pass
def create_leave_period(from_date, to_date, company=None):
leave_perio... |
leave_period = frappe.get_doc({
"doctype": "Leave Period",
"company": company or erpnext.get_default_company(),
"from_date": from_date,
"to_date": to_date,
"is_active": 1
}).insert()
return leave_period
| return frappe.get_doc("Leave Period", leave_period) | conditional_block |
test_leave_period.py | # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import unittest
import frappe
import erpnext
test_dependencies = ["Employee", "Leave Type", "Leave Policy"]
class TestLeavePeriod(unittest.TestCase):
pass
def create_leave_period(from_date, to_date, company=None):
leave_perio... |
leave_period = frappe.get_doc({
"doctype": "Leave Period",
"company": company or erpnext.get_default_company(),
"from_date": from_date,
"to_date": to_date,
"is_active": 1
}).insert()
return leave_period | from_date=from_date,
to_date=to_date,
is_active=1), 'name')
if leave_period:
return frappe.get_doc("Leave Period", leave_period) | random_line_split |
test_leave_period.py | # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import unittest
import frappe
import erpnext
test_dependencies = ["Employee", "Leave Type", "Leave Policy"]
class TestLeavePeriod(unittest.TestCase):
|
def create_leave_period(from_date, to_date, company=None):
leave_period = frappe.db.get_value('Leave Period',
dict(company=company or erpnext.get_default_company(),
from_date=from_date,
to_date=to_date,
is_active=1), 'name')
if leave_period:
return frappe.get_doc("Leave Period", leave_period)
leave_p... | pass | identifier_body |
test_leave_period.py | # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import unittest
import frappe
import erpnext
test_dependencies = ["Employee", "Leave Type", "Leave Policy"]
class TestLeavePeriod(unittest.TestCase):
pass
def | (from_date, to_date, company=None):
leave_period = frappe.db.get_value('Leave Period',
dict(company=company or erpnext.get_default_company(),
from_date=from_date,
to_date=to_date,
is_active=1), 'name')
if leave_period:
return frappe.get_doc("Leave Period", leave_period)
leave_period = frappe.get_doc({
... | create_leave_period | identifier_name |
urlsearchparams.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::URLSearchParamsBinding::... | else {
k != &name.0
}
});
match index {
Some(index) => list[index].1 = value.0,
None => list.push((name.0, value.0)), // Step 2.
};
} // Un-borrow self.list
// Step 3.
self.update_steps();
... | {
if k == &name.0 {
index = Some(i);
} else {
i += 1;
}
true
} | conditional_block |
urlsearchparams.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::URLSearchParamsBinding::... |
// https://url.spec.whatwg.org/#dom-urlsearchparams-getall
fn GetAll(&self, name: USVString) -> Vec<USVString> {
let list = self.list.borrow();
list.iter()
.filter_map(|&(ref k, ref v)| {
if k == &name.0 {
Some(USVString(v.clone()))
... | {
let list = self.list.borrow();
list.iter()
.find(|&kv| kv.0 == name.0)
.map(|ref kv| USVString(kv.1.clone()))
} | identifier_body |
urlsearchparams.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::URLSearchParamsBinding::... | global,
URLSearchParamsWrap,
)
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
pub fn Constructor(
global: &GlobalScope,
init: USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString,
) -> Fallible<DomRoot<URLSearchParams>> {
... |
pub fn new(global: &GlobalScope, url: Option<&URL>) -> DomRoot<URLSearchParams> {
reflect_dom_object(
Box::new(URLSearchParams::new_inherited(url)), | random_line_split |
urlsearchparams.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::URLSearchParamsBinding::... | (&self, name: USVString) -> bool {
let list = self.list.borrow();
list.iter().any(|&(ref k, _)| k == &name.0)
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-set
fn Set(&self, name: USVString, value: USVString) {
{
// Step 1.
let mut list = self.list.bo... | Has | identifier_name |
test_correlog.py | from spectrum import CORRELOGRAMPSD, CORRELATION, pcorrelogram, marple_data
from spectrum import data_two_freqs
from pylab import log10, plot, savefig, linspace
from numpy.testing import assert_array_almost_equal, assert_almost_equal
def test_correlog():
psd = CORRELOGRAMPSD(marple_data, marple_data, lag=15)
... |
if __name__ == "__main__":
create_figure()
| psd = test_correlog()
f = linspace(-0.5, 0.5, len(psd))
psd = cshift(psd, len(psd)/2)
plot(f, 10*log10(psd/max(psd)))
savefig('psd_corr.png') | identifier_body |
test_correlog.py | from spectrum import CORRELOGRAMPSD, CORRELATION, pcorrelogram, marple_data
from spectrum import data_two_freqs
from pylab import log10, plot, savefig, linspace
from numpy.testing import assert_array_almost_equal, assert_almost_equal
def | ():
psd = CORRELOGRAMPSD(marple_data, marple_data, lag=15)
assert_almost_equal(psd[0], 0.138216970)
assert_almost_equal(psd[1000-1], 7.900110787)
assert_almost_equal(psd[2000-1], 0.110103858)
assert_almost_equal(psd[3000-1], 0.222184134)
assert_almost_equal(psd[4000-1], -0.036255277)
as... | test_correlog | identifier_name |
test_correlog.py | from spectrum import CORRELOGRAMPSD, CORRELATION, pcorrelogram, marple_data
from spectrum import data_two_freqs
from pylab import log10, plot, savefig, linspace
from numpy.testing import assert_array_almost_equal, assert_almost_equal
def test_correlog():
psd = CORRELOGRAMPSD(marple_data, marple_data, lag=15)
... | create_figure() | conditional_block | |
test_correlog.py | from spectrum import CORRELOGRAMPSD, CORRELATION, pcorrelogram, marple_data
from spectrum import data_two_freqs
from pylab import log10, plot, savefig, linspace
from numpy.testing import assert_array_almost_equal, assert_almost_equal
def test_correlog():
psd = CORRELOGRAMPSD(marple_data, marple_data, lag=15)
... | create_figure() | savefig('psd_corr.png')
if __name__ == "__main__": | random_line_split |
decrementOperatorWithUnsupportedBooleanType.ts | // -- operator on boolean type
var BOOLEAN: boolean; | function foo(): boolean { return true; }
class A {
public a: boolean;
static foo() { return true; }
}
module M {
export var n: boolean;
}
var objA = new A();
// boolean type var
var ResultIsNumber1 = --BOOLEAN;
var ResultIsNumber2 = BOOLEAN--;
// boolean type literal
var ResultIsNumber3 = --true;
var R... | random_line_split | |
decrementOperatorWithUnsupportedBooleanType.ts | // -- operator on boolean type
var BOOLEAN: boolean;
function foo(): boolean { return true; }
class A {
public a: boolean;
static foo() |
}
module M {
export var n: boolean;
}
var objA = new A();
// boolean type var
var ResultIsNumber1 = --BOOLEAN;
var ResultIsNumber2 = BOOLEAN--;
// boolean type literal
var ResultIsNumber3 = --true;
var ResultIsNumber4 = --{ x: true, y: false };
var ResultIsNumber5 = --{ x: true, y: (n: boolean) => { return n; ... | { return true; } | identifier_body |
decrementOperatorWithUnsupportedBooleanType.ts | // -- operator on boolean type
var BOOLEAN: boolean;
function foo(): boolean { return true; }
class | {
public a: boolean;
static foo() { return true; }
}
module M {
export var n: boolean;
}
var objA = new A();
// boolean type var
var ResultIsNumber1 = --BOOLEAN;
var ResultIsNumber2 = BOOLEAN--;
// boolean type literal
var ResultIsNumber3 = --true;
var ResultIsNumber4 = --{ x: true, y: false };
var Res... | A | identifier_name |
diary-card.component.ts | import {Component, Input, EventEmitter,Output} from '@angular/core';
@Component({
selector: 'diary-card',
template: `
<div class="card-container row shadow-3">
<div class="col-xs-3">
{{diary.date | date:'dd/MMM/yyyy'}} <br>
<button
md-raised-button
[routerLink]=" [ diary._id]"
cl... | {
@Input() diary = {}
user_name = window.localStorage.getItem('cpms_user_name')
// showDiary: boolean = false;
// toggle(){
// this.showDiary = !this.showDiary;
// }
}
| DiaryCard | identifier_name |
diary-card.component.ts | import {Component, Input, EventEmitter,Output} from '@angular/core';
@Component({
selector: 'diary-card',
template: `
<div class="card-container row shadow-3">
<div class="col-xs-3">
{{diary.date | date:'dd/MMM/yyyy'}} <br>
<button
md-raised-button
[routerLink]=" [ diary._id]"
cl... | #slider1
></md-slider>
{{diary.overAllMoodLevel}}</div>
</div>
`
})
export class DiaryCard {
@Input() diary = {}
user_name = window.localStorage.getItem('cpms_user_name')
// showDiary: boolean = false;
// toggle(){
// this.showDiary = !this.showDiary;
// }
} | disabled | random_line_split |
www.ts | #!/usr/bin/env node
/**
* Module dependencies.
*/
import { app } from '../app';
import { serverPort } from '../config';
import * as http from 'http';
/**
* Get port from environment and store in Express.
*/
const port = normalizePort(process.env.PORT || serverPort);
app.set('port', port);
/**
* Create HTTP ser... | throw error;
}
}
/**
* Event listener for HTTP server 'listening' event.
*/
function onListening() {
const addr = server.address();
const bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.log('Listening on ' + bind);
}
| {
if (error.syscall !== 'listen') {
throw error;
}
const bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.... | identifier_body |
www.ts | #!/usr/bin/env node
/**
* Module dependencies.
*/
import { app } from '../app';
import { serverPort } from '../config';
import * as http from 'http';
/**
* Get port from environment and store in Express.
*/
const port = normalizePort(process.env.PORT || serverPort);
app.set('port', port);
/**
* Create HTTP ser... | function normalizePort(val): boolean | number {
const normalizedPort = parseInt(val, 10);
if (isNaN(normalizedPort)) {
// named pipe
return val;
}
if (normalizedPort >= 0) {
// port number
return normalizedPort;
}
return false;
}
/**
* Event listener for HTTP server 'error' event.
*/
... |
/**
* Normalize a port into a number, string, or false.
*/
| random_line_split |
www.ts | #!/usr/bin/env node
/**
* Module dependencies.
*/
import { app } from '../app';
import { serverPort } from '../config';
import * as http from 'http';
/**
* Get port from environment and store in Express.
*/
const port = normalizePort(process.env.PORT || serverPort);
app.set('port', port);
/**
* Create HTTP ser... | (error) {
if (error.syscall !== 'listen') {
throw error;
}
const bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
... | onError | identifier_name |
www.ts | #!/usr/bin/env node
/**
* Module dependencies.
*/
import { app } from '../app';
import { serverPort } from '../config';
import * as http from 'http';
/**
* Get port from environment and store in Express.
*/
const port = normalizePort(process.env.PORT || serverPort);
app.set('port', port);
/**
* Create HTTP ser... |
const bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console... | {
throw error;
} | conditional_block |
Repository.ts | export class Repository {
| (owner: string, repo: string) {
this.owner = owner;
this.name = repo;
}
readonly owner : string;
readonly name : string;
toString() : string {
return `${this.owner}/${this.name}`;
}
static parse(s: string) : Repository|null {
if (!s) {
return null;
... | constructor | identifier_name |
Repository.ts | export class Repository {
constructor(owner: string, repo: string) {
this.owner = owner;
this.name = repo;
}
readonly owner : string;
readonly name : string;
toString() : string {
return `${this.owner}/${this.name}`;
}
static parse(s: string) : Repository|null {
... |
const actualPrefix = Repository._getPrefix(prefix);
const owner = hash[`${actualPrefix}.owner`];
const name = hash[`${actualPrefix}.name`];
if (!owner || !name) {
return null;
}
return new Repository(owner, name);
}
} | {
return null;
} | conditional_block |
Repository.ts | export class Repository {
constructor(owner: string, repo: string) {
this.owner = owner;
this.name = repo;
}
readonly owner : string;
readonly name : string;
toString() : string {
return `${this.owner}/${this.name}`;
}
static parse(s: string) : Repository|null {
... | }
const actualPrefix = Repository._getPrefix(prefix);
const owner = hash[`${actualPrefix}.owner`];
const name = hash[`${actualPrefix}.name`];
if (!owner || !name) {
return null;
}
return new Repository(owner, name);
}
} |
static fromHash(hash: Map<string, any>, prefix?: string) : Repository|null {
if (!hash) {
return null; | random_line_split |
Repository.ts | export class Repository {
constructor(owner: string, repo: string) {
this.owner = owner;
this.name = repo;
}
readonly owner : string;
readonly name : string;
toString() : string {
return `${this.owner}/${this.name}`;
}
static parse(s: string) : Repository|null {
... |
private static _getPrefix(prefix?: string) : string {
return prefix || 'repository';
}
static fromHash(hash: Map<string, any>, prefix?: string) : Repository|null {
if (!hash) {
return null;
}
const actualPrefix = Repository._getPrefix(prefix);
const o... | {
const actualPrefix = Repository._getPrefix(prefix);
let result = hash || new Map<string, any>();
result[`${actualPrefix}.owner`] = this.owner;
result[`${actualPrefix}.name`] = this.name;
return result;
} | identifier_body |
test_iterator_compatibility.py | from __future__ import division
import unittest
import itertools
import numpy
from chainer import iterators
from chainer import serializer
from chainer import testing
class DummySerializer(serializer.Serializer):
def __init__(self, target):
super(DummySerializer, self).__init__()
self.target = ... |
it = it_after()
it.serialize(DummyDeserializer(target))
self.assertFalse(it.is_new_epoch)
self.assertAlmostEqual(it.epoch_detail, 4 / 6)
batch3 = it.next()
self.assertEqual(len(batch3), 2)
self.assertIsInstance(batch3, list)
... | it.serialize(DummySerializer(target)) | random_line_split |
test_iterator_compatibility.py | from __future__ import division
import unittest
import itertools
import numpy
from chainer import iterators
from chainer import serializer
from chainer import testing
class DummySerializer(serializer.Serializer):
def __init__(self, target):
super(DummySerializer, self).__init__()
self.target = ... | (self):
dataset = [1, 2, 3, 4, 5, 6]
iters = (
lambda: iterators.SerialIterator(dataset, 2),
lambda: iterators.MultiprocessIterator(dataset, 2, **self.options),
)
for it_before, it_after in itertools.permutations(iters, 2):
it = it_before()
... | test_iterator_compatibilty | identifier_name |
test_iterator_compatibility.py | from __future__ import division
import unittest
import itertools
import numpy
from chainer import iterators
from chainer import serializer
from chainer import testing
class DummySerializer(serializer.Serializer):
def __init__(self, target):
super(DummySerializer, self).__init__()
self.target = ... |
@testing.parameterize(*testing.product({
'n_prefetch': [1, 2],
'shared_mem': [None, 1000000],
}))
class TestIteratorCompatibility(unittest.TestCase):
def setUp(self):
self.n_processes = 2
self.options = {'n_processes': self.n_processes,
'n_prefetch': self.n_prefet... | if value is None:
value = self.target[key]
elif isinstance(value, numpy.ndarray):
numpy.copyto(value, self.target[key])
else:
value = type(value)(numpy.asarray(self.target[key]))
return value | identifier_body |
test_iterator_compatibility.py | from __future__ import division
import unittest
import itertools
import numpy
from chainer import iterators
from chainer import serializer
from chainer import testing
class DummySerializer(serializer.Serializer):
def __init__(self, target):
super(DummySerializer, self).__init__()
self.target = ... | self.assertFalse(it.is_new_epoch)
self.assertAlmostEqual(it.epoch_detail, 4 / 6)
batch3 = it.next()
self.assertEqual(len(batch3), 2)
self.assertIsInstance(batch3, list)
self.assertTrue(it.is_new_epoch)
self.assertEqual(sorted(batch1 + ... | it = it_before()
self.assertEqual(it.epoch, 0)
self.assertAlmostEqual(it.epoch_detail, 0 / 6)
batch1 = it.next()
self.assertEqual(len(batch1), 2)
self.assertIsInstance(batch1, list)
self.assertFalse(it.is_new_epoch)
self.assertAlmostEq... | conditional_block |
test-fs-write.js | // Copyright Joyent, Inc. and other Node contributors.
//
// 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, modi... | fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'ucs2'));
}
{
const expected = '中文 2'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(false, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'utf8');
fs.closeSync(... | random_line_split | |
DistributedPartyJukeboxActivityBaseAI.py | from direct.directnotify import DirectNotifyGlobal
from toontown.parties.DistributedPartyActivityAI import DistributedPartyActivityAI
from direct.task import Task
import PartyGlobals
class DistributedPartyJukeboxActivityBaseAI(DistributedPartyActivityAI):
notify = DirectNotifyGlobal.directNotify.newCategory("Distr... | for toon in self.toonsPlaying:
self.sendUpdateToAvatarId(toon, 'moveHostSongToTop', []) | self.owners.insert(0, host)
self.queue.insert(0, song)
| random_line_split |
DistributedPartyJukeboxActivityBaseAI.py | from direct.directnotify import DirectNotifyGlobal
from toontown.parties.DistributedPartyActivityAI import DistributedPartyActivityAI
from direct.task import Task
import PartyGlobals
class DistributedPartyJukeboxActivityBaseAI(DistributedPartyActivityAI):
notify = DirectNotifyGlobal.directNotify.newCategory("Distr... |
def toonExitDemand(self):
avId = self.air.getAvatarIdFromSender()
if avId != self.currentToon:
return
taskMgr.remove('removeToon%d' % self.doId)
self.currentToon = 0
self.toonsPlaying.remove(avId)
self.updateToonsPlaying()
def __removeToon(self):
... | pass | identifier_body |
DistributedPartyJukeboxActivityBaseAI.py | from direct.directnotify import DirectNotifyGlobal
from toontown.parties.DistributedPartyActivityAI import DistributedPartyActivityAI
from direct.task import Task
import PartyGlobals
class DistributedPartyJukeboxActivityBaseAI(DistributedPartyActivityAI):
notify = DirectNotifyGlobal.directNotify.newCategory("Distr... | self.sendUpdateToAvatarId(toon, 'moveHostSongToTop', []) | conditional_block | |
DistributedPartyJukeboxActivityBaseAI.py | from direct.directnotify import DirectNotifyGlobal
from toontown.parties.DistributedPartyActivityAI import DistributedPartyActivityAI
from direct.task import Task
import PartyGlobals
class DistributedPartyJukeboxActivityBaseAI(DistributedPartyActivityAI):
notify = DirectNotifyGlobal.directNotify.newCategory("Distr... | (self, details, owner):
self.sendUpdate('setSongPlaying', [details, owner])
def queuedSongsRequest(self):
avId = self.air.getAvatarIdFromSender()
if avId in self.owners:
index = self.owners.index(avId)
else:
index = -1
self.sendUpdateToAvatarId(avId, ... | d_setSongPlaying | identifier_name |
stream.rs | use libc::c_int;
use libc::c_uint;
use libc::c_void;
use format::format::Format;
use format::sample::SampleType;
use format::sample::Stream;
use format::error::DriverError;
use alsa::device::AlsaDevice;
use alsa::device::create_error;
use alsa::format::AlsaFormat;
use alsa::mixer::Params;
use alsa::ffi::*;
pub struc... |
pub fn output(&self, data: &[S]) -> Result<usize, DriverError> {
let available = data.len();
let mut written: usize = 0;
while written < available {
let subdata = &data[written..data.len()];
match self.write_some(subdata) {
Ok(count) => written += count,
Err(err) => return Err(err),
}
}
re... | {
let data_ptr = data.as_ptr() as *const c_void;
let frames = data.len() as snd_pcm_uframes_t;
let mut size = 0;
unsafe {
match self.wait() {
Ok(status) => size = snd_pcm_writei(self.device.get_pcm(), data_ptr, frames),
Err(err) => return Err(err),
}
}
if size < 0 {
return Err(create_error... | identifier_body |
stream.rs | use libc::c_int;
use libc::c_uint;
use libc::c_void;
use format::format::Format;
use format::sample::SampleType;
use format::sample::Stream;
use format::error::DriverError;
use alsa::device::AlsaDevice;
use alsa::device::create_error;
use alsa::format::AlsaFormat;
use alsa::mixer::Params;
use alsa::ffi::*;
pub struc... | }
impl<F: AlsaFormat, S: SampleType<Sample=F>> Stream<S> for AlsaStream<S> {
fn push(&mut self, frames: &[S]) {
self.output(frames).expect("Failed to output to device");
}
} | }
return Ok(written);
} | random_line_split |
stream.rs | use libc::c_int;
use libc::c_uint;
use libc::c_void;
use format::format::Format;
use format::sample::SampleType;
use format::sample::Stream;
use format::error::DriverError;
use alsa::device::AlsaDevice;
use alsa::device::create_error;
use alsa::format::AlsaFormat;
use alsa::mixer::Params;
use alsa::ffi::*;
pub struc... | (device: AlsaDevice) -> Result<Self, DriverError> {
let sample_rate = 44100;
let params = Params::new().expect("Failed to create hw params");
params.any(&device);
params.format(&device, sample_rate, S::CHANNELS as c_uint, F::FORMAT_ID);
params.apply(&device);
//device.setup(&mut params);
let buffer_siz... | open | identifier_name |
test_invoice_due_cost.py | # -*- coding: utf-8 -*-
#
# Author: Andrea Gallina
# © 2015 Apulia Software srl
#
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp.tests.common import TransactionCase
class T | TransactionCase):
def _create_pterm(self):
return self.env['account.payment.term'].create({
'name': 'Ri.Ba. 30/60',
'riba': True,
'riba_payment_cost': 5.00,
'line_ids': [
(0, 0,
{'value': 'procent', 'days': 30,
... | estInvoiceDueCost( | identifier_name |
test_invoice_due_cost.py | # -*- coding: utf-8 -*-
#
# Author: Andrea Gallina
# © 2015 Apulia Software srl
#
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp.tests.common import TransactionCase
class TestInvoiceDueCost(TransactionCase):
def _create_pterm(self):
return self.env['account.payment.te... | def setUp(self):
super(TestInvoiceDueCost, self).setUp()
self.partner = self.env.ref('base.res_partner_8')
self.product1 = self.env.ref('product.product_product_33')
self.journalrec = self.env['account.journal'].search(
[('type', '=', 'sale')])[0]
self.payment_ter... | random_line_split | |
test_invoice_due_cost.py | # -*- coding: utf-8 -*-
#
# Author: Andrea Gallina
# © 2015 Apulia Software srl
#
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp.tests.common import TransactionCase
class TestInvoiceDueCost(TransactionCase):
def _create_pterm(self):
r |
def _create_pterm2(self):
return self.env['account.payment.term'].create({
'name': 'Ri.Ba. 30',
'riba': True,
'riba_payment_cost': 5.00,
'line_ids': [
(0, 0,
{'value': 'balance', 'days': 30,
'days2': -1})
... | eturn self.env['account.payment.term'].create({
'name': 'Ri.Ba. 30/60',
'riba': True,
'riba_payment_cost': 5.00,
'line_ids': [
(0, 0,
{'value': 'procent', 'days': 30,
'days2': -1, 'value_amount': 0.50}),
(... | identifier_body |
search.py | endStatus = SNATCHED_PROPER
# NZBs can be sent straight to SAB or saved to disk
if result.resultType in ("nzb", "nzbdata"):
if sickbeard.NZB_METHOD == "blackhole":
dlResult = _downloadResult(result)
elif sickbeard.NZB_METHOD == "sabnzbd":
dlResult = sab.sendNZB(r... | """
Contains the internal logic necessary to actually "snatch" a result that
has been found.
Returns a bool representing success.
result: SearchResult instance to be snatched.
endStatus: the episode status that should be used for the episode object once it's snatched.
"""
if result is Non... | identifier_body | |
search.py | if cur_result.quality not in anyQualities + bestQualities:
logger.log(cur_result.name + " is a quality we know we don't want, rejecting it", logger.DEBUG)
continue
if show.rls_ignore_words and show_name_helpers.containsAtLeastOneWord(cur_result.name, cur_result.show.rls_ignore_w... | if curProvider.anime_only and not show.is_anime:
logger.log(u"" + str(show.name) + " is not an anime, skiping", logger.DEBUG)
continue | random_line_split | |
search.py | (cur_result.name, cur_result.show.rls_require_words):
logger.log(u"Ignoring " + cur_result.name + " based on required words filter: " + show.rls_require_words,
logger.INFO)
continue
if not show_name_helpers.filterBadReleases(cur_result.name, parse=False):
... | if curProvider.anime_only and not show.is_anime:
logger.log(u"" + str(show.name) + " is not an anime, skiping", logger.DEBUG)
continue
threading.currentThread().name = origThreadName + " :: [" + curProvider.name + "]"
foundResults[curProvider.name] = {}
searchCount = 0... | conditional_block | |
search.py | (result, endStatus=SNATCHED):
"""
Contains the internal logic necessary to actually "snatch" a result that
has been found.
Returns a bool representing success.
result: SearchResult instance to be snatched.
endStatus: the episode status that should be used for the episode object once it's snatc... | snatchEpisode | identifier_name | |
full.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'recipe_engine/buildbucket',
'recipe_engine/context',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recip... | (api):
yield api.test('basic')
yield api.test('basic_tags') + api.properties(tags=True)
yield api.test('basic_ref') + api.buildbucket.ci_build(git_ref='refs/foo/bar')
yield api.test('basic_branch') + api.buildbucket.ci_build(
git_ref='refs/heads/testing')
yield api.test('basic_hash') + api.buildbucket.c... | GenTests | identifier_name |
full.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'recipe_engine/buildbucket',
'recipe_engine/context',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recip... |
# Bundle the repository.
api.git.bundle_create(
api.path['start_dir'].join('all.bundle'))
def GenTests(api):
yield api.test('basic')
yield api.test('basic_tags') + api.properties(tags=True)
yield api.test('basic_ref') + api.buildbucket.ci_build(git_ref='refs/foo/bar')
yield api.test('basic_branc... | pass # Success! | conditional_block |
full.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'recipe_engine/buildbucket',
'recipe_engine/context',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recip... | assert retVal == "deadbeef", (
"expected retVal to be %r but was %r" % ("deadbeef", retVal))
# count_objects shows number and size of objects in .git dir.
api.git.count_objects(
name='count-objects',
can_fail_build=api.properties.get('count_objects_can_fail_build'),
git_config_options={'foo... | tags=api.properties.get('tags'))
| random_line_split |
full.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'recipe_engine/buildbucket',
'recipe_engine/context',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recip... | api.test('can_fail_build') +
api.step_data('git status can_fail_build', retcode=1)
)
yield (
api.test('cannot_fail_build') +
api.step_data('git status cannot_fail_build', retcode=1)
)
yield (
api.test('set_got_revision') +
api.properties(set_got_revision=True)
)
yield (
api.te... | yield api.test('basic')
yield api.test('basic_tags') + api.properties(tags=True)
yield api.test('basic_ref') + api.buildbucket.ci_build(git_ref='refs/foo/bar')
yield api.test('basic_branch') + api.buildbucket.ci_build(
git_ref='refs/heads/testing')
yield api.test('basic_hash') + api.buildbucket.ci_build(
... | identifier_body |
helpers.tsx | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not u... | : columnProps;
} | random_line_split | |
helpers.tsx | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not u... |
/**
* A given array of column names returns an array of properties
* necessary to display the columns. If the given indexPattern
* has a timefield, a time column is prepended
* @param columns
* @param indexPattern
* @param hideTimeField
* @param isShortDots
*/
export function getDisplayedColumns(
columns: st... | {
return {
name: timeFieldName,
displayName: 'Time',
isSortable: true,
isRemoveable: false,
colLeftIdx: -1,
colRightIdx: -1,
};
} | identifier_body |
helpers.tsx | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not u... | (
columns: string[],
indexPattern: IndexPattern,
hideTimeField: boolean,
isShortDots: boolean
) {
if (!Array.isArray(columns) || typeof indexPattern !== 'object' || !indexPattern.getFieldByName) {
return [];
}
const columnProps = columns.map((column, idx) => {
const field = indexPattern.getFieldBy... | getDisplayedColumns | identifier_name |
helpers.tsx | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not u... |
const columnProps = columns.map((column, idx) => {
const field = indexPattern.getFieldByName(column);
return {
name: column,
displayName: isShortDots ? shortenDottedString(column) : column,
isSortable: field && field.sortable ? true : false,
isRemoveable: column !== '_source' || colum... | {
return [];
} | conditional_block |
bvlist.rs | use bap::high::bitvector::BitVector;
use holmes::pg::dyn::values::{ValueT, ToValue};
use holmes::pg::dyn::types::TypeT;
use postgres::types::{ToSql, IsNull};
use postgres_array::Array;
use holmes::pg::RowIter;
use holmes::pg::dyn::{Type, Value};
use bit_vec::BitVec;
use std::any::Any;
use std::sync::Arc;
#[derive(Debu... |
}
#[derive(Debug, Clone, Hash, PartialEq)]
pub struct BVListType;
impl TypeT for BVListType {
fn name(&self) -> Option<&'static str> {
Some("bvlist")
}
fn extract(&self, rows: &mut RowIter) -> Option<Value> {
let raw: Array<BitVec> = rows.next().unwrap();
Some(Arc::new(
... | {
use std::fmt::Debug;
self.0.fmt(f)
} | identifier_body |
bvlist.rs | use bap::high::bitvector::BitVector;
use holmes::pg::dyn::values::{ValueT, ToValue};
use holmes::pg::dyn::types::TypeT;
use postgres::types::{ToSql, IsNull};
use postgres_array::Array;
use holmes::pg::RowIter;
use holmes::pg::dyn::{Type, Value};
use bit_vec::BitVec;
use std::any::Any;
use std::sync::Arc;
#[derive(Debu... | vec![self]
}
valuet_boiler!();
}
impl ToSql for BVList {
accepts!(::postgres::types::VARBIT_ARRAY);
to_sql_checked!();
fn to_sql(
&self,
ty: &::postgres::types::Type,
out: &mut Vec<u8>,
) -> ::std::result::Result<IsNull, Box<::std::error::Error + Send + Sync>> {
... | }
fn to_sql(&self) -> Vec<&ToSql> { | random_line_split |
bvlist.rs | use bap::high::bitvector::BitVector;
use holmes::pg::dyn::values::{ValueT, ToValue};
use holmes::pg::dyn::types::TypeT;
use postgres::types::{ToSql, IsNull};
use postgres_array::Array;
use holmes::pg::RowIter;
use holmes::pg::dyn::{Type, Value};
use bit_vec::BitVec;
use std::any::Any;
use std::sync::Arc;
#[derive(Debu... | (&self) -> Type {
Arc::new(BVListType)
}
fn get(&self) -> &Any {
self as &Any
}
fn to_sql(&self) -> Vec<&ToSql> {
vec![self]
}
valuet_boiler!();
}
impl ToSql for BVList {
accepts!(::postgres::types::VARBIT_ARRAY);
to_sql_checked!();
fn to_sql(
&self,
... | type_ | identifier_name |
test.rs | use std::collections::VecDeque;
use super::{parse, BinaryOperator, Expression, Operand, Statement, Type};
use scanner::Scanner;
#[test]
fn example_program_2() {
let source = r#" var nTimes : int := 0;
print "How many times?";
read nTimes;
var x : int;
for x in 0..nTimes-1 do
print x;
print " : Hello, World... | Statement::Read("nTimes".to_string()),
Statement::Declaration("x".to_string(), Type::Int, None),
Statement::For(
"x".to_string(),
Expression::Singleton(Operand::Int(0.into())),
Expression::Binary(
Operand::Identifier("nTimes".to_string()),
... | random_line_split | |
test.rs | use std::collections::VecDeque;
use super::{parse, BinaryOperator, Expression, Operand, Statement, Type};
use scanner::Scanner;
#[test]
fn example_program_2() | Statement::Print(Expression::Singleton(Operand::StringLiteral(
"How many times?".to_string(),
))),
Statement::Read("nTimes".to_string()),
Statement::Declaration("x".to_string(), Type::Int, None),
Statement::For(
"x".to_string(),
Expression::Sin... | {
let source = r#" var nTimes : int := 0;
print "How many times?";
read nTimes;
var x : int;
for x in 0..nTimes-1 do
print x;
print " : Hello, World!\n";
end for;
assert (x = nTimes);"#;
let mut scanner = Scanner::new();
let mut tokens = VecDeque::new();
scanner.scan(source, &mut tokens);
... | identifier_body |
test.rs | use std::collections::VecDeque;
use super::{parse, BinaryOperator, Expression, Operand, Statement, Type};
use scanner::Scanner;
#[test]
fn | () {
let source = r#" var nTimes : int := 0;
print "How many times?";
read nTimes;
var x : int;
for x in 0..nTimes-1 do
print x;
print " : Hello, World!\n";
end for;
assert (x = nTimes);"#;
let mut scanner = Scanner::new();
let mut tokens = VecDeque::new();
scanner.scan(source, &mut tokens);
... | example_program_2 | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.