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 |
|---|---|---|---|---|
blob.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 dom::bindings::codegen::InheritTypes::FileDerived;
use dom::bindings::global::GlobalRef;
use dom::bindings::js... | {
BlobTypeId,
FileTypeId
}
#[dom_struct]
pub struct Blob {
reflector_: Reflector,
type_: BlobType
}
impl Blob {
pub fn new_inherited() -> Blob {
Blob {
reflector_: Reflector::new(),
type_: BlobTypeId
}
}
pub fn new(global: &GlobalRef) -> Temporary<... | BlobType | identifier_name |
blob.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 dom::bindings::codegen::InheritTypes::FileDerived;
use dom::bindings::global::GlobalRef;
use dom::bindings::js... |
#[dom_struct]
pub struct Blob {
reflector_: Reflector,
type_: BlobType
}
impl Blob {
pub fn new_inherited() -> Blob {
Blob {
reflector_: Reflector::new(),
type_: BlobTypeId
}
}
pub fn new(global: &GlobalRef) -> Temporary<Blob> {
reflect_dom_object(b... | random_line_split | |
config_personal.py | import os.path as osp
import os
USE_GPU = False
AWS_REGION_NAME = 'us-east-2'
if USE_GPU:
DOCKER_IMAGE = 'dementrock/rllab3-shared-gpu'
else:
# DOCKER_IMAGE = 'dwicke/jump:docker'
DOCKER_IMAGE = 'dwicke/parameterized:latest'
DOCKER_LOG_DIR = '/tmp/expt'
AWS_S3_PATH = 's3://pytorchrl/pytorchrl/experiment... | AWS_IMAGE_ID = ALL_REGION_AWS_IMAGE_IDS[AWS_REGION_NAME]
if USE_GPU:
AWS_INSTANCE_TYPE = 'g2.2xlarge'
else:
AWS_INSTANCE_TYPE = 'c4.2xlarge'
ALL_REGION_AWS_KEY_NAMES = {
"us-east-2": "pytorchrl-us-east-2",
"us-east-1": "pytorchrl-us-east-1"
}
AWS_KEY_NAME = ALL_REGION_AWS_KEY_NAMES[AWS_REGION_NAME]
... | random_line_split | |
config_personal.py |
import os.path as osp
import os
USE_GPU = False
AWS_REGION_NAME = 'us-east-2'
if USE_GPU:
DOCKER_IMAGE = 'dementrock/rllab3-shared-gpu'
else:
# DOCKER_IMAGE = 'dwicke/jump:docker'
|
DOCKER_LOG_DIR = '/tmp/expt'
AWS_S3_PATH = 's3://pytorchrl/pytorchrl/experiments'
AWS_CODE_SYNC_S3_PATH = 's3://pytorchrl/pytorchrl/code'
ALL_REGION_AWS_IMAGE_IDS = {
'ap-northeast-1': 'ami-002f0167',
'ap-northeast-2': 'ami-590bd937',
'ap-south-1': 'ami-77314318',
'ap-southeast-1': 'ami-1610a975',
... | DOCKER_IMAGE = 'dwicke/parameterized:latest' | conditional_block |
equal-to-validator.directive.ts | import { Directive } from '@angular/core';
import { forwardRef } from '@angular/core';
import { Attribute } from '@angular/core';
import { Validator } from '@angular/forms';
import { AbstractControl } from '@angular/forms';
import { NG_VALIDATORS } from '@angular/forms';
@Directive({
selector: '[appEqualTo][formCont... | implements Validator {
constructor(
@Attribute('appEqualTo') public appEqualTo: string,
@Attribute('appForwardErrors') public appForwardErrors: string
) {}
private get shouldForwardErrors() {
if (!this.appForwardErrors) { return false; }
return this.appForwardErrors === 'true' ? true : false;
... | EqualToValidator | identifier_name |
equal-to-validator.directive.ts | import { Directive } from '@angular/core';
import { forwardRef } from '@angular/core';
import { Attribute } from '@angular/core';
import { Validator } from '@angular/forms';
import { AbstractControl } from '@angular/forms';
import { NG_VALIDATORS } from '@angular/forms';
@Directive({
selector: '[appEqualTo][formCont... | }
validate(c: AbstractControl): { [key: string]: any } {
const current_value = c.value;
const desired_control = c.root.get(this.appEqualTo);
if (desired_control && current_value !== desired_control.value && !this.shouldForwardErrors) {
return {
appEqualTo: false
};
... | return this.appForwardErrors === 'true' ? true : false; | random_line_split |
equal-to-validator.directive.ts | import { Directive } from '@angular/core';
import { forwardRef } from '@angular/core';
import { Attribute } from '@angular/core';
import { Validator } from '@angular/forms';
import { AbstractControl } from '@angular/forms';
import { NG_VALIDATORS } from '@angular/forms';
@Directive({
selector: '[appEqualTo][formCont... |
if (desired_control && current_value === desired_control.value && this.shouldForwardErrors) {
delete desired_control.errors['appEqualTo'];
if (!Object.keys(desired_control.errors).length) { desired_control.setErrors(null); }
}
if (desired_control && current_value !== desired_control... | {
return {
appEqualTo: false
};
} | conditional_block |
equal-to-validator.directive.ts | import { Directive } from '@angular/core';
import { forwardRef } from '@angular/core';
import { Attribute } from '@angular/core';
import { Validator } from '@angular/forms';
import { AbstractControl } from '@angular/forms';
import { NG_VALIDATORS } from '@angular/forms';
@Directive({
selector: '[appEqualTo][formCont... | }
}
| {
const current_value = c.value;
const desired_control = c.root.get(this.appEqualTo);
if (desired_control && current_value !== desired_control.value && !this.shouldForwardErrors) {
return {
appEqualTo: false
};
}
if (desired_control && current_value === desired_... | identifier_body |
htmlsourceelement.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 dom::bindings::codegen::Bindings::HTMLSourceElementBinding;
use dom::bindings::js::Root;
use dom::document::Do... |
}
| {
let element = HTMLSourceElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLSourceElementBinding::Wrap)
} | identifier_body |
htmlsourceelement.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 dom::bindings::codegen::Bindings::HTMLSourceElementBinding;
use dom::bindings::js::Root;
use dom::document::Do... | }
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLSourceElement> {
let element = HTMLSourceElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLSo... | document: &Document) -> HTMLSourceElement {
HTMLSourceElement {
htmlelement:
HTMLElement::new_inherited(localName, prefix, document)
} | random_line_split |
htmlsourceelement.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 dom::bindings::codegen::Bindings::HTMLSourceElementBinding;
use dom::bindings::js::Root;
use dom::document::Do... | {
htmlelement: HTMLElement
}
impl HTMLSourceElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLSourceElement {
HTMLSourceElement {
htmlelement:
HTMLElement::new_inherited(localName, pr... | HTMLSourceElement | identifier_name |
state.ts | /////////////////////
import { Random, MT19937 } from '@offirmo/random'
import * as deepFreeze from 'deep-freeze-strict'
import { LIB_ID, SCHEMA_VERSION } from './consts'
import {
State,
} from './types'
/////////////////////
const DEFAULT_SEED = 987
function create(): State {
return {
schema_version: SCHEMA_... |
if (cached_prng.getUseCount() !== state.use_count) {
// should never happen
if (cached_prng.getUseCount() !== 0)
throw new Error(`state-prng get_prng() unexpected case: cached implementation need to be fast forwarded!`)
cached_prng.discard(state.use_count)
cached_prng_updated = true
}
if (cached_prng_... | {
cached_prng.seed(state.seed)
cached_prng._seed = state.seed // maintain this extra property TODO improve the lib instead
cached_prng_updated = true
} | conditional_block |
state.ts | /////////////////////
import { Random, MT19937 } from '@offirmo/random'
import * as deepFreeze from 'deep-freeze-strict'
import { LIB_ID, SCHEMA_VERSION } from './consts'
import {
State,
} from './types'
/////////////////////
const DEFAULT_SEED = 987
function create(): State {
return {
schema_version: SCHEMA_... | () {
cached_prng = Random.engines.mt19937().seed(DEFAULT_SEED)
cached_prng._seed = DEFAULT_SEED
cached_prng_was_updated_once = false
}
/////////////////////
// needed to test migrations, both here and in composing parents
// a full featured, non-trivial demo state
// needed for demos
const DEMO_STATE: State = dee... | xxx_internal_reset_prng_cache | identifier_name |
state.ts | /////////////////////
import { Random, MT19937 } from '@offirmo/random'
import * as deepFreeze from 'deep-freeze-strict'
import { LIB_ID, SCHEMA_VERSION } from './consts'
import {
State,
} from './types'
/////////////////////
const DEFAULT_SEED = 987
function create(): State {
return {
schema_version: SCHEMA_... |
function xxx_internal_reset_prng_cache() {
cached_prng = Random.engines.mt19937().seed(DEFAULT_SEED)
cached_prng._seed = DEFAULT_SEED
cached_prng_was_updated_once = false
}
/////////////////////
// needed to test migrations, both here and in composing parents
// a full featured, non-trivial demo state
// needed... | {
const rng: MTEngineWithSeed = Random.engines.mt19937().autoSeed()
return Random.integer(-2147483646, 2147483647)(rng) // doc is unclear about allowed bounds...
} | identifier_body |
state.ts | /////////////////////
import { Random, MT19937 } from '@offirmo/random'
import * as deepFreeze from 'deep-freeze-strict'
import { LIB_ID, SCHEMA_VERSION } from './consts'
import {
State,
} from './types'
/////////////////////
const DEFAULT_SEED = 987
function create(): State {
return {
schema_version: SCHEMA_... | })
// some hints may be needed to migrate to demo state
const MIGRATION_HINTS_FOR_TESTS: any = deepFreeze({
to_v1: {
revision: 108,
},
})
/////////////////////
export {
State,
DEFAULT_SEED,
create,
set_seed,
update_use_count,
get_prng,
generate_random_seed,
// exposed for testability, do not use !
xx... | const OLDEST_LEGACY_STATE_FOR_TESTS: any = deepFreeze({
// no schema_version = 0
seed: 1234,
use_count: 107, | random_line_split |
responses.py | #!/usr/bin/env python
"""
@package ion.agents.platform.responses
@file ion/agents/platform/responses.py
@author Carlos Rueda
@brief Some constants for responses from platform agents/drivers.
"""
from ion.agents.instrument.common import BaseEnum
__author__ = 'Carlos Rueda'
__license__ = 'Apache 2.0'
| class NormalResponse(BaseEnum):
PORT_TURNED_ON = 'OK_PORT_TURNED_ON'
PORT_ALREADY_ON = 'OK_PORT_ALREADY_ON'
PORT_TURNED_OFF = 'OK_PORT_TURNED_OFF'
PORT_ALREADY_OFF = 'OK_PORT_ALREADY_OFF'
PORT_SET_OVER_CURRENT = 'OK_PORT_SET_OVER_CURREN... | random_line_split | |
responses.py | #!/usr/bin/env python
"""
@package ion.agents.platform.responses
@file ion/agents/platform/responses.py
@author Carlos Rueda
@brief Some constants for responses from platform agents/drivers.
"""
from ion.agents.instrument.common import BaseEnum
__author__ = 'Carlos Rueda'
__license__ = 'Apache 2.0'
class Nor... | (BaseEnum):
PLATFORM_ID = 'ERROR_INVALID_PLATFORM_ID'
ATTRIBUTE_ID = 'ERROR_INVALID_ATTRIBUTE_ID'
ATTRIBUTE_VALUE_OUT_OF_RANGE = 'ERROR_ATTRIBUTE_VALUE_OUT_OF_RANGE'
ATTRIBUTE_NOT_WRITABLE = 'ERROR_ATTRIBUTE_NOT_WRITABLE'
PORT_ID = 'ER... | InvalidResponse | identifier_name |
responses.py | #!/usr/bin/env python
"""
@package ion.agents.platform.responses
@file ion/agents/platform/responses.py
@author Carlos Rueda
@brief Some constants for responses from platform agents/drivers.
"""
from ion.agents.instrument.common import BaseEnum
__author__ = 'Carlos Rueda'
__license__ = 'Apache 2.0'
class Nor... |
class InvalidResponse(BaseEnum):
PLATFORM_ID = 'ERROR_INVALID_PLATFORM_ID'
ATTRIBUTE_ID = 'ERROR_INVALID_ATTRIBUTE_ID'
ATTRIBUTE_VALUE_OUT_OF_RANGE = 'ERROR_ATTRIBUTE_VALUE_OUT_OF_RANGE'
ATTRIBUTE_NOT_WRITABLE = 'ERROR_ATTRIBUTE_NOT_WRITABLE'
PORT_ID ... | PORT_TURNED_ON = 'OK_PORT_TURNED_ON'
PORT_ALREADY_ON = 'OK_PORT_ALREADY_ON'
PORT_TURNED_OFF = 'OK_PORT_TURNED_OFF'
PORT_ALREADY_OFF = 'OK_PORT_ALREADY_OFF'
PORT_SET_OVER_CURRENT = 'OK_PORT_SET_OVER_CURRENT' | identifier_body |
setup.py | """ Script for building the Pieman package. """
from setuptools import setup
try:
import pypandoc
LONG_DESCRIPTION = pypandoc.convert('README.md', 'rst')
except (ImportError, OSError):
# OSError is raised when pandoc is not installed.
LONG_DESCRIPTION = ('Utilities written in Python which are used by ... | 'bin/bsc.py',
'bin/bscd.py',
'bin/check_mutually_exclusive_params.py',
'bin/check_redis.py',
'bin/check_wpa_passphrase.py',
'bin/depend_on.py',
'bin/du.py',
'bin/image_attrs.py',
'bin/preprocessor.py',
'bin/render.py',
... | maintainer='Evgeny Golyshev',
maintainer_email='eugulixes@gmail.com',
license='https://gnu.org/licenses/gpl-3.0.txt',
scripts=[
'bin/apk_tools_version.py', | random_line_split |
trumail.js | $('.ui.dropdown').dropdown();
$(document).ready(function() {
$('#test-form').on('submit', function(e) {
e.preventDefault();
var format = document.getElementsByName('test-format')[0].value;
var email = document.getElementsByName('test-email')[0].value;
// Verify the parameters were ... |
document.getElementsByName('test-results')[0].textContent = results;
$('.ui.modal').modal({
closable: false,
transition: 'flip vertical'
}).modal('show');
$('#test-button').removeClass('loading');
};
xhr.onerror = function(... | {
results = vkbeautify.xml(xhr.responseText, 4);
} | conditional_block |
trumail.js | $('.ui.dropdown').dropdown();
$(document).ready(function() {
$('#test-form').on('submit', function(e) {
e.preventDefault();
var format = document.getElementsByName('test-format')[0].value;
var email = document.getElementsByName('test-email')[0].value;
// Verify the parameters were ... | console.error(xhr.statusText);
};
xhr.send(null);
});
}); | xhr.onerror = function(e) { | random_line_split |
no-invalid-html.js | "use strict";
/**
* @fileoverview Disallows invalid HTML in templates
* @author James Garbutt <https://github.com/43081j>
*/
const template_analyzer_1 = require("../template-analyzer");
//------------------------------------------------------------------------------
// Rule Definition
//-----------------------------... | if (loc) {
context.report({
loc: loc,
messageId: 'parseError',
data: { err: err.code }
});
}
}
... | {
const source = context.getSourceCode();
//----------------------------------------------------------------------
// Helpers
//----------------------------------------------------------------------
//----------------------------------------------------------------------
... | identifier_body |
no-invalid-html.js | "use strict";
/**
* @fileoverview Disallows invalid HTML in templates
* @author James Garbutt <https://github.com/43081j>
*/
const template_analyzer_1 = require("../template-analyzer");
//------------------------------------------------------------------------------
// Rule Definition
//-----------------------------... |
}
}
}
};
}
};
module.exports = rule;
| {
context.report({
loc: loc,
messageId: 'parseError',
data: { err: err.code }
});
} | conditional_block |
no-invalid-html.js | "use strict";
/**
* @fileoverview Disallows invalid HTML in templates
* @author James Garbutt <https://github.com/43081j>
*/
const template_analyzer_1 = require("../template-analyzer");
//------------------------------------------------------------------------------
// Rule Definition
//-----------------------------... | (context) {
const source = context.getSourceCode();
//----------------------------------------------------------------------
// Helpers
//----------------------------------------------------------------------
//---------------------------------------------------------------------... | create | identifier_name |
no-invalid-html.js | "use strict";
/**
* @fileoverview Disallows invalid HTML in templates
* @author James Garbutt <https://github.com/43081j>
*/
const template_analyzer_1 = require("../template-analyzer");
//------------------------------------------------------------------------------
// Rule Definition
//-----------------------------... | data: { err: err.code }
});
}
}
}
}
};
}
};
module.exports = rule; | const loc = analyzer.resolveLocation(err, source);
if (loc) {
context.report({
loc: loc,
messageId: 'parseError', | random_line_split |
JSDistance.py | # -*- coding: utf-8 -*-
# '''
# Author: Eachen Kuang
# Date: 2017.10.20
# Goal: 将文件转化为字典
# Other:
# '''
import string
from math import log
import numpy as np
def KLD(p,q):
p,q=zip(*filter(lambda (x,y): x!=0 or y!=0, zip(p,q))) #去掉二者都是0的概率值
p=p+np.spacing(1)
q=q+np.spacing(1)
print p, q
return su... | return 0.5 * KLD(p, M) + 0.5 * KLD(q, M)
reg = lambda x: [x.count(i) for i in string.lowercase] # 频数分布
rate = lambda y: [round(i * 1.0 / sum(reg(y)), 4) for i in reg(y)] # 概率分布
s1 = 'KuangYichen1raf'
s2 = 'YichenKuang2'
print JSD_core(rate(s1), rate(s2)) | q = q + np.spacing(1)
M = M + np.spacing(1)
# print p,q,M | random_line_split |
JSDistance.py | # -*- coding: utf-8 -*-
# '''
# Author: Eachen Kuang
# Date: 2017.10.20
# Goal: 将文件转化为字典
# Other:
# '''
import string
from math import log
import numpy as np
def KLD(p,q):
p, | ip(*filter(lambda (x,y): x!=0 or y!=0, zip(p,q))) #去掉二者都是0的概率值
p=p+np.spacing(1)
q=q+np.spacing(1)
print p, q
return sum([_p * log(_p/_q,2) for (_p,_q) in zip(p,q)])
# p=np.ones(5)/5.0
# q=[0,0,0.5,0.2,0.3]
# print KLD(p,q)
def JSD_core(p, q):
p, q = zip(*filter(lambda[x,y]: x != 0 or y != 0, zip(p... | q=z | identifier_name |
JSDistance.py | # -*- coding: utf-8 -*-
# '''
# Author: Eachen Kuang
# Date: 2017.10.20
# Goal: 将文件转化为字典
# Other:
# '''
import string
from math import log
import numpy as np
def KLD(p,q):
p,q=zip(*filter( | ,0.3]
# print KLD(p,q)
def JSD_core(p, q):
p, q = zip(*filter(lambda[x,y]: x != 0 or y != 0, zip(p, q))) # 去掉二者都是0的概率值
M = [0.5 * (_p + _q) for _p, _q in zip(p, q)]
p = p + np.spacing(1)
q = q + np.spacing(1)
M = M + np.spacing(1)
# print p,q,M
return 0.5 * KLD(p, M) + 0.5 * KLD(q, M)
... | lambda (x,y): x!=0 or y!=0, zip(p,q))) #去掉二者都是0的概率值
p=p+np.spacing(1)
q=q+np.spacing(1)
print p, q
return sum([_p * log(_p/_q,2) for (_p,_q) in zip(p,q)])
# p=np.ones(5)/5.0
# q=[0,0,0.5,0.2 | identifier_body |
syllabifier.py | yllabify/syllabifier.py
# on 2014-09-05.
#
# According to https://www.ling.upenn.edu/phonetics/p2tk/, this is licensed
# under MIT.
#
# This is the P2TK automated syllabifier. Given a string of phonemes,
# it automatically divides the phonemes into syllables.
#
# By Joshua Tauberer, based on code originally written by... | onset = internuclei[split:]
# If we are looking at a valid onset, or if we're at the start of the word
# (in which case an invalid onset is better than a coda that doesn't follow
# a nucleus), or if we've gone through all of the onsets and we didn't find
# any that are valid, then split the no... | coda = internuclei[:split] | random_line_split |
syllabifier.py | this is licensed
# under MIT.
#
# This is the P2TK automated syllabifier. Given a string of phonemes,
# it automatically divides the phonemes into syllables.
#
# By Joshua Tauberer, based on code originally written by Charles Yang.
#
# The syllabifier requires a language configuration which specifies
# the set of pho... | if line[0] == "#" :
sys.stdout.write(line)
continue
line = line.strip()
s = stringify(syllabify(L, line))
sys.stdout.write(s + "\n") | conditional_block | |
syllabifier.py | yllabify/syllabifier.py
# on 2014-09-05.
#
# According to https://www.ling.upenn.edu/phonetics/p2tk/, this is licensed
# under MIT.
#
# This is the P2TK automated syllabifier. Given a string of phonemes,
# it automatically divides the phonemes into syllables.
#
# By Joshua Tauberer, based on code originally written by... |
# If this module was run directly, syllabify the words on standard input
# into standard output. Hashed lines are printed back untouched.
if __name__ == "__main__" :
import sys
if len(sys.argv) != 2 :
print("Usage: python syllabifier.py english.cfg < textfile.txt > outfile.txt")
else :
L = loadLanguage(sys.arg... | '''This function takes a syllabification returned by syllabify and
turns it into a string, with phonemes spearated by spaces and
syllables spearated by periods.'''
ret = []
for syl in syllables :
stress, onset, nucleus, coda = syl
if stress != None and len(nucleus) != 0 :
nucleus[0] += str(stress)
re... | identifier_body |
syllabifier.py | yllabify/syllabifier.py
# on 2014-09-05.
#
# According to https://www.ling.upenn.edu/phonetics/p2tk/, this is licensed
# under MIT.
#
# This is the P2TK automated syllabifier. Given a string of phonemes,
# it automatically divides the phonemes into syllables.
#
# By Joshua Tauberer, based on code originally written by... | (syllables) :
'''This function takes a syllabification returned by syllabify and
turns it into a string, with phonemes spearated by spaces and
syllables spearated by periods.'''
ret = []
for syl in syllables :
stress, onset, nucleus, coda = syl
if stress != None and len(nucleus) != 0 :
nucleus[0] += s... | stringify | identifier_name |
base.js | /*
Copyright 2014, KISSY v1.49
MIT Licensed
build time: May 22 12:15
*/
/*
Combined processedModules by KISSY Module Compiler:
base
*/
KISSY.add("base", ["attribute"], function(S, require) {
var Attribute = require("attribute");
var ucfirst = S.ucfirst, ON_SET = "_onSet", noop = S.noop;
function __getHook(me... | return Base
}); | }
}
S.Base = Base; | random_line_split |
base.js | /*
Copyright 2014, KISSY v1.49
MIT Licensed
build time: May 22 12:15
*/
/*
Combined processedModules by KISSY Module Compiler:
base
*/
KISSY.add("base", ["attribute"], function(S, require) {
var Attribute = require("attribute");
var ucfirst = S.ucfirst, ON_SET = "_onSet", noop = S.noop;
function __getHook(me... | (method) {
var len, self = this, plugins = self.get("plugins");
if(len = plugins.length) {
for(var i = 0;i < len;i++) {
if(plugins[i][method]) {
plugins[i][method](self)
}
}
}
}
function callExtensionsMethod(self, extensions, method, args) {
var len;
if(len ... | callPluginsMethod | identifier_name |
base.js | /*
Copyright 2014, KISSY v1.49
MIT Licensed
build time: May 22 12:15
*/
/*
Combined processedModules by KISSY Module Compiler:
base
*/
KISSY.add("base", ["attribute"], function(S, require) {
var Attribute = require("attribute");
var ucfirst = S.ucfirst, ON_SET = "_onSet", noop = S.noop;
function __getHook(me... | else {
if(p !== plugin) {
plugins.push(p);
keep = 1
}
}
}
if(!keep) {
p.pluginDestructor(self)
}
});
self.setInternal("plugins", plugins);
return self
}, getPlugin:function(id) {
var plugin = null;
S.each(this.get("plugi... | {
pluginId = p.get && p.get("pluginId") || p.pluginId;
if(pluginId !== plugin) {
plugins.push(p);
keep = 1
}
} | conditional_block |
base.js | /*
Copyright 2014, KISSY v1.49
MIT Licensed
build time: May 22 12:15
*/
/*
Combined processedModules by KISSY Module Compiler:
base
*/
KISSY.add("base", ["attribute"], function(S, require) {
var Attribute = require("attribute");
var ucfirst = S.ucfirst, ON_SET = "_onSet", noop = S.noop;
function __getHook(me... | }
}
var Base = Attribute.extend({constructor:function() {
var self = this;
self.callSuper.apply(self, arguments);
var listeners = self.get("listeners");
for(var n in listeners) {
self.on(n, listeners[n])
}
self.initializer();
constructPlugins(self);
callPluginsMethod.call(... | {
return function(origFn) {
return function wrap() {
var self = this;
if(reverse) {
origFn.apply(self, arguments)
}else {
self.callSuper.apply(self, arguments)
}
var extensions = arguments.callee.__owner__.__extensions__ || [];
if(reverse) {
... | identifier_body |
utils.py | from nose.tools import ok_
def fail(msg):
raise AssertionError(msg)
def assert_in(thing, seq, msg=None):
msg = msg or "'%s' not found in %s" % (thing, seq)
ok_(thing in seq, msg)
def | (thing, seq, msg=None):
msg = msg or "unexpected '%s' found in %s" % (thing, seq)
ok_(thing not in seq, msg)
def assert_has_keys(dict, required=[], optional=[]):
keys = dict.keys()
for k in required:
assert_in(k, keys, "required key %s missing from %s" % (k, dict))
allowed_keys = set(requi... | assert_not_in | identifier_name |
utils.py | from nose.tools import ok_
def fail(msg):
raise AssertionError(msg)
def assert_in(thing, seq, msg=None):
msg = msg or "'%s' not found in %s" % (thing, seq)
ok_(thing in seq, msg)
def assert_not_in(thing, seq, msg=None):
msg = msg or "unexpected '%s' found in %s" % (thing, seq)
ok_(thing not in... |
def assert_isinstance(thing, kls):
ok_(isinstance(thing, kls), "%s is not an instance of %s" % (thing, kls))
| fail("found unexpected keys: %s" % list(extra_keys)) | conditional_block |
utils.py | from nose.tools import ok_
def fail(msg):
raise AssertionError(msg)
def assert_in(thing, seq, msg=None):
msg = msg or "'%s' not found in %s" % (thing, seq)
ok_(thing in seq, msg)
def assert_not_in(thing, seq, msg=None):
msg = msg or "unexpected '%s' found in %s" % (thing, seq)
ok_(thing not in... |
def assert_isinstance(thing, kls):
ok_(isinstance(thing, kls), "%s is not an instance of %s" % (thing, kls)) | random_line_split | |
utils.py | from nose.tools import ok_
def fail(msg):
|
def assert_in(thing, seq, msg=None):
msg = msg or "'%s' not found in %s" % (thing, seq)
ok_(thing in seq, msg)
def assert_not_in(thing, seq, msg=None):
msg = msg or "unexpected '%s' found in %s" % (thing, seq)
ok_(thing not in seq, msg)
def assert_has_keys(dict, required=[], optional=[]):
key... | raise AssertionError(msg) | identifier_body |
block_holder.py | from biicode.common.model.cells import SimpleCell
from biicode.common.model.dependency_set import DependencySet
from biicode.common.model.brl.block_name import BlockName
from biicode.common.model.symbolic.block_version_table import BlockVersionTable
from biicode.common.model.blob import Blob
from biicode.common.model.r... |
return self._config
@property
def mains(self):
return self.config.mains
@property
def tests(self):
return self.config.tests
@property
def data(self):
return self.config.data
@property
def paths(self):
return self.config.paths
@property
... | try:
res = self._resources[BIICODE_FILE]
content = res.content.load.bytes
except KeyError:
content = None
try:
self._config = BiiConfig(content)
except ConfigurationFileError as e:
raise ConfigurationFile... | conditional_block |
block_holder.py | from biicode.common.model.cells import SimpleCell
from biicode.common.model.dependency_set import DependencySet
from biicode.common.model.brl.block_name import BlockName
from biicode.common.model.symbolic.block_version_table import BlockVersionTable
from biicode.common.model.blob import Blob
from biicode.common.model.r... | @property
def parent(self):
if self.config.parent:
if self.config.parent.block_name != self.block_name:
raise BiiException("A block should have same BlockName as it's parent.\n"
"%s's parent is %s"
% (self.... | def requirements(self):
return self.config.requirements
| random_line_split |
block_holder.py | from biicode.common.model.cells import SimpleCell
from biicode.common.model.dependency_set import DependencySet
from biicode.common.model.brl.block_name import BlockName
from biicode.common.model.symbolic.block_version_table import BlockVersionTable
from biicode.common.model.blob import Blob
from biicode.common.model.r... | (self):
""" return CellNames
"""
return set(self._resources.keys())
@property
def block_cell_names(self):
""" return BlockCellNames
"""
return {self.block_name + name for name in self._resources}
def __getitem__(self, key):
return self._resources[key... | cell_names | identifier_name |
block_holder.py | from biicode.common.model.cells import SimpleCell
from biicode.common.model.dependency_set import DependencySet
from biicode.common.model.brl.block_name import BlockName
from biicode.common.model.symbolic.block_version_table import BlockVersionTable
from biicode.common.model.blob import Blob
from biicode.common.model.r... |
def deps(self, files=None):
deps = DependencySet()
for name, (cell, _) in self._resources.iteritems():
if files is None or self.block_name + name in files:
if isinstance(cell, SimpleCell):
deps.update(cell.dependencies)
return deps
| '''Handles pointing to virtual targets instead contained ones'''
result = set()
for block_cell_name in block_cell_names:
assert block_cell_name.block_name == self.block_name, "%s != %s" % (block_cell_name,
self.b... | identifier_body |
readFileOrUrl.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Callback } from './callback';
import { ReadFileOrUrl } from './readFileOrUrl';
class MockFileReader{
callError: boolean;
constructor(callError: boolean = false) {
this.callError = callError;
// console.log('mock file reader... |
beforeEach(() => {
errorOccured=false;
successOccured =false;
});
it('should handleclick success', (done) => {
spyOn(window,"FileReader").and.returnValue(new MockFileReader(false));
ReadFileOrUrl.readAsync({},Callback.from((data)=>onSuccess(data)));
setTimeout(()=>{
while(!suc... | {
successOccured = true;
} | identifier_body |
readFileOrUrl.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Callback } from './callback';
import { ReadFileOrUrl } from './readFileOrUrl';
class MockFileReader{
callError: boolean;
| (callError: boolean = false) {
this.callError = callError;
// console.log('mock file reader called');
}
onerror(err:any){
//console.log('wrong onerror');
}
onload(data:any){
//console.log('yaanlis onload');
}
readAsArrayBuffer(data:any){
if(this.callError)
this.onerror('err');
els... | constructor | identifier_name |
readFileOrUrl.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Callback } from './callback';
import { ReadFileOrUrl } from './readFileOrUrl';
class MockFileReader{
callError: boolean;
constructor(callError: boolean = false) {
this.callError = callError;
// console.log('mock file reader... | },100);
}); | random_line_split | |
table.rs | use std::fs::{File, OpenOptions, metadata};
use std::path::{Path, PathBuf};
use bincode::SizeLimit;
use bincode::rustc_serialize::{encode, encode_into, decode_from};
use super::Error;
use super::database::Database;
use super::column::Column;
use super::rows::Rows;
use super::super::identifier::Identifier;
pub struc... | impl<'a> Table<'a> {
/// Create table in database
pub fn create<'b>(name: &str,
engine_id: u8,
columns: Vec<Column>,
db: &'b Database)
-> Result<Table<'b>, Error> {
info!("creating table: {}", name);
// TODO... | /// Table representation | random_line_split |
table.rs | use std::fs::{File, OpenOptions, metadata};
use std::path::{Path, PathBuf};
use bincode::SizeLimit;
use bincode::rustc_serialize::{encode, encode_into, decode_from};
use super::Error;
use super::database::Database;
use super::column::Column;
use super::rows::Rows;
use super::super::identifier::Identifier;
pub struc... |
pub fn get_table_header_offset(&self) -> u32 {
let bytes: Vec<u8> = encode(&self.meta_data, SizeLimit::Infinite).unwrap();
bytes.len() as u32
}
pub fn get_cols_offset(&self) -> u32 {
let mut size = 0;
for v in &self.meta_data.columns {
size += v.size();
... | {
let mut column_sizes = Vec::<u32>::new();
for v in &self.meta_data.columns {
column_sizes.push(v.size());
}
column_sizes
} | identifier_body |
table.rs | use std::fs::{File, OpenOptions, metadata};
use std::path::{Path, PathBuf};
use bincode::SizeLimit;
use bincode::rustc_serialize::{encode, encode_into, decode_from};
use super::Error;
use super::database::Database;
use super::column::Column;
use super::rows::Rows;
use super::super::identifier::Identifier;
pub struc... | (&self) -> u8 {
self.meta_data.engine_id
}
}
#[cfg(test)]
mod test {
use super::Table;
use super::super::database::*;
use std::fs::metadata;
use super::super::column::Column;
use super::super::types::Types;
#[test]
fn create_table() {
let path = "/tmp/test1/";
l... | get_engine_id | identifier_name |
table.rs | use std::fs::{File, OpenOptions, metadata};
use std::path::{Path, PathBuf};
use bincode::SizeLimit;
use bincode::rustc_serialize::{encode, encode_into, decode_from};
use super::Error;
use super::database::Database;
use super::column::Column;
use super::rows::Rows;
use super::super::identifier::Identifier;
pub struc... | else {
error!("could not load table: {} at {}",
&name,
&path.to_str().unwrap());
Err(Error::LoadTable)
}
}
// TODO: write table delete static function
/// Returns a vector of the sizes of the columns
pub fn get_cols_sizes(&self) ->... | {
let mut file = try!(OpenOptions::new()
.read(true)
.open(&path));
let metadata: TableMetadata = try!(decode_from(&mut file, SizeLimit::Infinite));
info!("loaded table: {}", &name);
Ok(Table {
... | conditional_block |
gruntfile.js | /***********************************************
gruntfile.js for jquery-bootstrap
https://github.com/fcoo/jquery-bootstrap
***********************************************/
module.exports = function(grunt) {
"use strict";
//***********************************************
grunt.initConfig({
"fco... | "haveGhPages" : true, //true if there is a branch "gh-pages" used for demos
"beforeProdCmd": "", //Cmd to be run at the start of prod-task. Multi cmd can be seperated by "&"
"beforeDevCmd" : "", //Cmd to be run at the start of dev-task
"afterPr... | "haveJavaScript": true, //true if the packages have js-files
"haveStyleSheet": true, //true if the packages have css and/or scss-files | random_line_split |
notificator.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... |
}
}
| {
let mut n = RustNotification::new();
n.appname("imag");
n.summary(&self.0.summary);
n.urgency(self.0.urgency.clone().into());
n.body(&format!("{}: {:?}", &self.0.message, item));
let _ = n.finalize().show(); // Ignoring error here
Ok(... | identifier_body |
notificator.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | fn into(self) -> NotificationUrgency {
match self {
Urgency::Low => NotificationUrgency::Low,
Urgency::Normal => NotificationUrgency::Normal,
Urgency::High => NotificationUrgency::Critical,
}
}
}
#[derive(Debug, Defau... |
impl Into<NotificationUrgency> for Urgency {
| random_line_split |
notificator.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | (Notification);
impl From<Notification> for DebugNotification {
fn from(n: Notification) -> DebugNotification {
DebugNotification(n)
}
}
impl<T: Debug> Notificator<T> for DebugNotification {
/// A default implementation for all Types that implement Display
fn n... | DebugNotification | identifier_name |
TrayNotifierCore.py | # coding=utf-8
#####################################
# Imports
#####################################
# Python native imports
from PyQt5 import QtCore, QtWidgets, QtGui
import logging
#####################################
# Global Variables
#####################################
UI_LOGO = "logo_small.jpg"
############... |
def on_kill_threads__slot(self):
pass
def setup_signals(self):
self.core_signals["kill"].connect(self.on_kill_threads__slot)
self.core_signals["connect_signals_and_slots"].connect(self.connect_signals_and_slots)
self.system_tray_icon.activated.connect(self.on_tray_menu_item_c... | self.system_tray_icon.hide()
self.main_screen.exit_requested_signal.emit() | conditional_block |
TrayNotifierCore.py | # coding=utf-8
#####################################
# Imports
#####################################
# Python native imports
from PyQt5 import QtCore, QtWidgets, QtGui
import logging
#####################################
# Global Variables
#####################################
UI_LOGO = "logo_small.jpg"
############... | (self):
pass
def show_informational_message(self, message, time=2000):
self.system_tray_icon.showMessage("Zebrafish Scan Processor", message, QtWidgets.QSystemTrayIcon.Information,
time)
def show_failure_message(self, message, time=10000):
self... | connect_signals_and_slots | identifier_name |
TrayNotifierCore.py | # coding=utf-8
#####################################
# Imports
#####################################
# Python native imports
from PyQt5 import QtCore, QtWidgets, QtGui
import logging
#####################################
# Global Variables
#####################################
UI_LOGO = "logo_small.jpg"
############... |
def on_tray_menu_item_clicked(self, event):
if event == QtWidgets.QSystemTrayIcon.Context: # Happens on right-click, ignore for tray menu instead
pass
elif event in [QtWidgets.QSystemTrayIcon.Trigger, QtWidgets.QSystemTrayIcon.DoubleClick]:
self.main_screen.show()
... | self.system_tray_icon.showMessage("Zebrafish Scan Processor", message, QtWidgets.QSystemTrayIcon.Critical,
time) | identifier_body |
TrayNotifierCore.py | # coding=utf-8
#####################################
# Imports
#####################################
# Python native imports
from PyQt5 import QtCore, QtWidgets, QtGui
import logging
#####################################
# Global Variables
#####################################
UI_LOGO = "logo_small.jpg"
############... | time)
def on_tray_menu_item_clicked(self, event):
if event == QtWidgets.QSystemTrayIcon.Context: # Happens on right-click, ignore for tray menu instead
pass
elif event in [QtWidgets.QSystemTrayIcon.Trigger, QtWidgets.QSystemTrayIcon.DoubleClick... | self.system_tray_icon.showMessage("Zebrafish Scan Processor", message, QtWidgets.QSystemTrayIcon.Information,
time)
def show_failure_message(self, message, time=10000):
self.system_tray_icon.showMessage("Zebrafish Scan Processor", message, QtWidgets.QSystem... | random_line_split |
emmet_css_from_one_line.py | import sublime, sublime_plugin, re
class EmmetCssFromOneLineCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
line_region = view.line(view.sel()[0])
line_str = view.substr(line_region)
left_padding = re.findall(r'^(\s+)', line_str)[0]
... | view.insert(edit, view.sel()[0].end(), '\n' + left_padding + props_array[i])
runEmmet()
i += 1 | conditional_block | |
emmet_css_from_one_line.py | import sublime, sublime_plugin, re
class EmmetCssFromOneLineCommand(sublime_plugin.TextCommand):
def | (self, edit):
view = self.view
line_region = view.line(view.sel()[0])
line_str = view.substr(line_region)
left_padding = re.findall(r'^(\s+)', line_str)[0]
# find commands in line
props_array = re.findall(r'([a-zA-Z0-9:!;().,?/\-+#]+)', line_str)
... | run | identifier_name |
emmet_css_from_one_line.py | import sublime, sublime_plugin, re
class EmmetCssFromOneLineCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view | line_region = view.line(view.sel()[0])
line_str = view.substr(line_region)
left_padding = re.findall(r'^(\s+)', line_str)[0]
# find commands in line
props_array = re.findall(r'([a-zA-Z0-9:!;().,?/\-+#]+)', line_str)
# Delete long string
view.replace(edit... | random_line_split | |
emmet_css_from_one_line.py | import sublime, sublime_plugin, re
class EmmetCssFromOneLineCommand(sublime_plugin.TextCommand):
| i = 1
while i < len(props_array):
view.insert(edit, view.sel()[0].end(), '\n' + left_padding + props_array[i])
runEmmet()
i += 1
| def run(self, edit):
view = self.view
line_region = view.line(view.sel()[0])
line_str = view.substr(line_region)
left_padding = re.findall(r'^(\s+)', line_str)[0]
# find commands in line
props_array = re.findall(r'([a-zA-Z0-9:!;().,?/\-+#]+)', line_str)
... | identifier_body |
jquery.ui.datepicker-hr.js | /* Croatian i18n for the jQuery UI date picker plugin. */
/* Written by Vjekoslav Nesek. */
jQuery(function($){
$.datepicker.regional['hr'] = {
clearText: 'izbriši', clearStatus: 'Izbriši trenutni datum',
closeText: 'Zatvori', closeStatus: 'Zatvori kalendar',
prevText: '<', prevStatus: 'Prikaži prethodni mj... | dateFormat: 'dd.mm.yy.', firstDay: 1,
initStatus: 'Odaberi datum', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['hr']);
}); | dayNamesShort: ['Ned','Pon','Uto','Sri','Čet','Pet','Sub'],
dayNamesMin: ['Ne','Po','Ut','Sr','Če','Pe','Su'],
dayStatus: 'Odaber DD za prvi dan tjedna', dateStatus: '\'Datum\' D, M d', | random_line_split |
apl.js | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("distfs/codemirror/lib/codemirror"));
else if (typeof define == "function" && defi... | Comment.test(ch)) {
stream.skipToEnd();
return "comment";
}
if (ch === "∘" && stream.peek() === ".") {
stream.next();
return "function jot-dot";
}
stream.eatWhile(/[\w\$_]/);
word = stream.current();
state.prev = true;
return "keyword";
}
}... | return "function " + funcName;
}
if (is | conditional_block |
apl.js | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("distfs/codemirror/lib/codemirror"));
else if (typeof define == "function" && defi... | prev: false,
func: false,
op: false,
string: false,
escape: false
};
},
token: function(stream, state) {
var ch, funcName, word;
if (stream.eatSpace()) {
return null;
}
ch = stream.next();
if (ch === '"' || ch === "'") {
... | startState: function() {
return { | random_line_split |
venues.js | const {
GraphQLList,
GraphQLObjectType,
GraphQLInt,
GraphQLFloat,
GraphQLString,
GraphQLNonNull,
} = require('graphql');
const co = require('co');
const {getFields, needMoreFields} = require('../../utils/getGraphQLSelection');
const TaskType = require('./tasks');
const TaskService = require('../../servic... | type: GraphQLString,
},
categories: {
type: new GraphQLList(CategoryType),
},
tasks: {
type: new GraphQLList(TaskType),
resolve: (parent, params, source, fields) => {
const fieldsNames = getFields(fields, Object);
if (needMoreFields(fieldsNames, parent.tasks)) {
... | },
address: {
type: AddressType,
},
website: { | random_line_split |
venues.js | const {
GraphQLList,
GraphQLObjectType,
GraphQLInt,
GraphQLFloat,
GraphQLString,
GraphQLNonNull,
} = require('graphql');
const co = require('co');
const {getFields, needMoreFields} = require('../../utils/getGraphQLSelection');
const TaskType = require('./tasks');
const TaskService = require('../../servic... |
return parent.tasks;
},
},
nbTasks: {
type: GraphQLInt,
},
nbOpenTasks: {
type: GraphQLInt,
resolve: (parent) => {
return co(VenueService.getNbOpenTask(parent));
},
},
picture: {
type: GraphQLString,
args: {
size: {
typ... | {
const ids = parent.tasks.map(task => task._id);
return co(TaskService.getTasksByIds(ids, fieldsNames));
} | conditional_block |
sw.js | var dataCacheName = 'Jblog-v1';
var cacheName = 'Jblog-1';
var filesToCache = [
'/',
'/index.html'
];
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName).then(function(cache) {
console.log('[ServiceWorker] Cachin... |
}));
})
);
return self.clients.claim();
});
self.addEventListener('fetch', function(e) {
console.log('[Service Worker] Fetch', e.request.url);
e.respondWith(
caches.match(e.request).then(function(response) {
return response || fetch(e.request);
})
);... | {
console.log('[ServiceWorker] Removing old cache', key);
return caches.delete(key);
} | conditional_block |
sw.js | var dataCacheName = 'Jblog-v1';
var cacheName = 'Jblog-1';
var filesToCache = [
'/',
'/index.html' | caches.open(cacheName).then(function(cache) {
console.log('[ServiceWorker] Caching app shell');
return cache.addAll(filesToCache);
})
);
});
self.addEventListener('activate', function(e) {
console.log('[ServiceWorker] Activate');
e.waitUntil(
caches.keys().th... | ];
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil( | random_line_split |
pand.py | #http://pandas.pydata.org/pandas-docs/stable/tutorials.html
#file='pand.py'
#exec(compile(open(file).read(), file, 'exec'))
from pandas import DataFrame, read_csv
import matplotlib.pyplot as plt
import pandas as pd
#import sys
#import matplotlib
names = ['Bob','Jessica','Mary','John','Mel']
births = [968, 155, 77, ... | wait = input("PRESS ENTER TO CONTINUE.")
#Create a graph object
print('Create a graph object')
df['Births'].plot()
# Text to display on graph
print('Construct a string to display on the graph')
Text = str(MaxValue) + " - " + MaxName
print(Text)
# Add text to graph
print('Annonate the graph')
plt.annotate(Text, xy=(1... | print('Find the name associated with the maximum value')
MaxName = df['Names'][mask].values
print('Name at Max Value is ',MaxName) | random_line_split |
bookmarksbar.py | popup menu not initialized.')
# Show/hide bookmarks.
self.uistate.setdefault('show_bar', True)
self.toggle_show_bookmarks(self.uistate['show_bar'])
# Init preferences in self.widget.
self.widget.on_preferences_changed(plugin.preferences)
self.widget.connectto(plugin.preferences, 'changed',
lambd... |
# Toggle between full/short page names.
self.uistate.setdefault('show_full_page_name', False)
# Save path to use later in Copy/Paste menu.
self._saved_bookmark = None
self.paths = [] # list of bookmarks as string objects
self.uistate.setdefault('bookmarks', [])
# Add pages from config to the bar.
fo... | def __init__(self, ui, uistate, get_page_func):
gtk.HBox.__init__(self)
self.ui = ui
self.uistate = uistate
self.save_flag = False # if True save bookmarks in config
self.add_bookmarks_to_beginning = False # add new bookmarks to the end of the bar
self.max_bookmarks = False # maximum number of bookmarks
... | identifier_body |
bookmarksbar.py | popup menu not initialized.')
# Show/hide bookmarks.
self.uistate.setdefault('show_bar', True)
self.toggle_show_bookmarks(self.uistate['show_bar'])
# Init preferences in self.widget.
self.widget.on_preferences_changed(plugin.preferences)
self.widget.connectto(plugin.preferences, 'changed',
lambd... |
else:
_delete_all()
def change_bookmark(self, old_path, new_path = None):
'''
Change path in bookmark from 'old_path' to 'new_path'.
:param new_path, old_path: strings corresponding to Path.name.
If 'new_path' == None takes currently opened page.
'''
if not new_path:
page = self._get_page()
if... | menu = gtk.Menu()
item = gtk.MenuItem(_('Do you want to delete all bookmarks?')) # T: message for bookmark plugin
item.connect('activate', lambda o: _delete_all())
menu.append(item)
menu.show_all()
menu.popup(None, None, None, 3, 0) | conditional_block |
bookmarksbar.py | popup menu not initialized.')
# Show/hide bookmarks.
self.uistate.setdefault('show_bar', True)
self.toggle_show_bookmarks(self.uistate['show_bar'])
# Init preferences in self.widget.
self.widget.on_preferences_changed(plugin.preferences)
self.widget.connectto(plugin.preferences, 'changed',
lambd... | (self, first, second, direction):
'''
Move bookmark 'first' to the place near the bookmark 'second'.
:param first, second: strings corresponding to Path.name.
:param direction: move | move_bookmark | identifier_name |
bookmarksbar.py | , page = None):
'''
Add new page as bookmark to the bar.
:param page: L{Page}, if None takes currently opened page,
'''
if not page:
page = self._get_page()
if page.exists():
return self._add_new(page.name, self.add_bookmarks_to_beginning)
def _add_new(self, path, add_bookmarks_to_beginning = False... | button.show() | random_line_split | |
__init__.py | import logging
from emitter import Send
"""
log.io logging handler
======================
Handler for the python logging framework for log.io stateless TCP API
http://logio.org/
Usage:
::
from log_io_handler import LogIOHandler
Logger.addHandler(LogIOHandler)
#or dict_config
'handlers'
'log_io': {
... | (self, record):
message = self.format(record)
msg_string = "+log|%s|%s|info|%s\r\n" %\
(self.logstream, self.node, message)
Send.config_dict = {'host': self.host, 'port': self.port}
Send(msg_string)
| emit | identifier_name |
__init__.py | import logging
from emitter import Send
"""
log.io logging handler
======================
Handler for the python logging framework for log.io stateless TCP API
http://logio.org/
Usage:
::
from log_io_handler import LogIOHandler
Logger.addHandler(LogIOHandler)
#or dict_config
'handlers'
'log_io': {
... | Send.config_dict = {'host': self.host, 'port': self.port}
Send(msg_string)
| """A log handler that transmits log entries to log.io server.
If the request is passed as the first argument to the log record,
request data will be provided in the report.
"""
def __init__(self, logstream='PythonStream',
node='PythonNode',
host='localhost',
... | identifier_body |
__init__.py | import logging
from emitter import Send
"""
log.io logging handler
======================
Handler for the python logging framework for log.io stateless TCP API
http://logio.org/
Usage:
::
from log_io_handler import LogIOHandler
Logger.addHandler(LogIOHandler)
#or dict_config
'handlers'
'log_io': {
... | self.node = node
self.host = host
self.port = port
def emit(self, record):
message = self.format(record)
msg_string = "+log|%s|%s|info|%s\r\n" %\
(self.logstream, self.node, message)
Send.config_dict = {'host': self.host, 'port': self.port}
Send(m... | host='localhost',
port=28777):
logging.Handler.__init__(self)
self.logstream = logstream | random_line_split |
cluster_provider.py | import logging
from abc import abstractmethod
from string import Template
from parsl.providers.error import SchedulerMissingArgs, ScriptPathError
from parsl.launchers.error import BadLauncher
from parsl.providers.provider_base import ExecutionProvider
logger = logging.getLogger(__name__)
class ClusterProvider(Execu... | return self._label | identifier_body | |
cluster_provider.py | import logging
from abc import abstractmethod
from string import Template
from parsl.providers.error import SchedulerMissingArgs, ScriptPathError
from parsl.launchers.error import BadLauncher
from parsl.providers.provider_base import ExecutionProvider
logger = logging.getLogger(__name__)
class ClusterProvider(Execu... | (self, template, script_filename, job_name, configs):
"""Generate submit script and write it to a file.
Args:
- template (string) : The template string to be used for the writing submit script
- script_filename (string) : Name of the submit script
- job_name (s... | _write_submit_script | identifier_name |
cluster_provider.py | import logging
from abc import abstractmethod
from string import Template
from parsl.providers.error import SchedulerMissingArgs, ScriptPathError
from parsl.launchers.error import BadLauncher
from parsl.providers.provider_base import ExecutionProvider
logger = logging.getLogger(__name__)
class ClusterProvider(Execu... |
return self.channel.execute_wait(cmd, t)
def _write_submit_script(self, template, script_filename, job_name, configs):
"""Generate submit script and write it to a file.
Args:
- template (string) : The template string to be used for the writing submit script
- s... | t = timeout | conditional_block |
cluster_provider.py | import logging
from abc import abstractmethod
from string import Template
from parsl.providers.error import SchedulerMissingArgs, ScriptPathError
from parsl.launchers.error import BadLauncher
from parsl.providers.provider_base import ExecutionProvider
logger = logging.getLogger(__name__)
class ClusterProvider(Execu... | self.cmd_timeout = cmd_timeout
if not callable(self.launcher):
raise(BadLauncher(self.launcher,
"Launcher for executor: {} is of type: {}. Expects a parsl.launcher.launcher.Launcher or callable".format(
label, type(self.launcher... | self.min_blocks = min_blocks
self.max_blocks = max_blocks
self.parallelism = parallelism
self.launcher = launcher
self.walltime = walltime | random_line_split |
query15.rs | use timely::dataflow::*;
use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::AsCollection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use ::Collections;
use ::types::create_date;
// -- $ID$
// -- TPC-... | // do a hierarchical min, to improve update perf.
.map(|key| ((key % 1000) as u16, key))
.group_u(|_k, s, t| {
let max = s.iter().map(|x| x.1).max().unwrap();
t.extend(s.iter().filter(|x| x.1 == max));
})
.map(|(_,key)| ((key % ... | .as_collection();
// suppliers with maximum revenue
let top_suppliers =
revenue | random_line_split |
query15.rs | use timely::dataflow::*;
use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::AsCollection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use ::Collections;
use ::types::create_date;
// -- $ID$
// -- TPC-... | // do a hierarchical min, to improve update perf.
.map(|key| ((key % 1000) as u16, key))
.group_u(|_k, s, t| {
let max = s.iter().map(|x| x.1).max().unwrap();
t.extend(s.iter().filter(|x| x.1 == max));
})
.map(|(_,key)| ((key % ... | {
println!("TODO: query 15 takes a global aggregate with key 0u8, instead of ().");
// revenue by supplier
let revenue =
collections
.lineitems()
.inner
.flat_map(|(item, time, diff)|
if create_date(1996, 1, 1) <= item.ship_date && item.ship_da... | identifier_body |
query15.rs | use timely::dataflow::*;
use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::AsCollection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use ::Collections;
use ::types::create_date;
// -- $ID$
// -- TPC-... |
else { None }
)
.as_collection();
// suppliers with maximum revenue
let top_suppliers =
revenue
// do a hierarchical min, to improve update perf.
.map(|key| ((key % 1000) as u16, key))
.group_u(|_k, s, t| {
let... | {
Some((item.supp_key, time, (item.extended_price * (100 - item.discount) / 100) as isize * diff))
} | conditional_block |
query15.rs | use timely::dataflow::*;
use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::AsCollection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use ::Collections;
use ::types::create_date;
// -- $ID$
// -- TPC-... | <G: Scope>(collections: &mut Collections<G>) -> ProbeHandle<G::Timestamp>
where G::Timestamp: Lattice+Ord {
println!("TODO: query 15 takes a global aggregate with key 0u8, instead of ().");
// revenue by supplier
let revenue =
collections
.lineitems()
.inner
.... | query | identifier_name |
editorTestServices.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
public read(): string {
return this.rules.join('\n');
}
}
export class TestCommandService implements ICommandService {
declare readonly _serviceBrand: undefined;
private readonly _instantiationService: IInstantiationService;
private readonly _onWillExecuteCommand = new Emitter<ICommandEvent>();
public r... | {
if (this.rules[i].indexOf(ruleName) >= 0) {
this.rules.splice(i, 1);
i--;
}
} | conditional_block |
editorTestServices.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | implements ICommandService {
declare readonly _serviceBrand: undefined;
private readonly _instantiationService: IInstantiationService;
private readonly _onWillExecuteCommand = new Emitter<ICommandEvent>();
public readonly onWillExecuteCommand: Event<ICommandEvent> = this._onWillExecuteCommand.event;
private re... | TestCommandService | identifier_name |
editorTestServices.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | import { CommandsRegistry, ICommandEvent, ICommandService } from 'vs/platform/commands/common/commands';
import { IResourceEditorInput } from 'vs/platform/editor/common/editor';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
export class TestCodeEditorService extends AbstractCo... | random_line_split | |
editorTestServices.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
public override insertRule(rule: string, index?: number): void {
this.rules.unshift(rule);
}
public override removeRulesContainingSelector(ruleName: string): void {
for (let i = 0; i < this.rules.length; i++) {
if (this.rules[i].indexOf(ruleName) >= 0) {
this.rules.splice(i, 1);
i--;
}
}
}
... | {
super(null!);
} | identifier_body |
marked.js | import Marked from 'marked'
import hljs from 'highlight.js'
const renderer = new Marked.Renderer()
export const toc = []
renderer.heading = function(text, level) {
var slug = text.toLowerCase().replace(/\s+/g, '-')
toc.push({
level: level,
slug: slug,
title: text
})
return `<h${level}><a href='#${... |
},
renderer
})
export const marked = text => {
var tok = Marked.lexer(text)
text = Marked.parser(tok).replace(/<pre>/ig, '<pre class="hljs">')
return text
}
| {
return hljs.highlightAuto(code).value
} | conditional_block |
marked.js | import Marked from 'marked'
import hljs from 'highlight.js'
const renderer = new Marked.Renderer()
export const toc = []
renderer.heading = function(text, level) {
var slug = text.toLowerCase().replace(/\s+/g, '-')
toc.push({
level: level,
slug: slug,
title: text
})
return `<h${level}><a href='#${... | }
},
renderer
})
export const marked = text => {
var tok = Marked.lexer(text)
text = Marked.parser(tok).replace(/<pre>/ig, '<pre class="hljs">')
return text
} | if (hljs.getLanguage(lang)) {
return hljs.highlight(lang, code).value
} else {
return hljs.highlightAuto(code).value | random_line_split |
rs_stepdown.rs | /* Copyright 2013 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writi... |
};
}
let x = val.unwrap();
if x as f32 != t as f32 { // possible round-off err
fail!("expected %?, found %?", t, x);
}
}
Err(e) => println(fmt!("%?", e)),
}
debug!("requesting status until good");
let mut don... | {
match ptr {
&Double(ref value) => Some(*value),
_ => None,
}
} | conditional_block |
rs_stepdown.rs | /* Copyright 2013 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writi... | i += 1;
debug!("switching primary");
let time = MONGO_TIMEOUT_SECS + 10;
// freeze everything...
match rs.get_config() {
Ok(conf) => {
let mut hosts = ~[];
for conf.members.iter().advance |&member| {
hosts.push(member.host);
}
... | {
let mut i = 0;
let client = @Client::new();
let seed = [(~"127.0.0.1", 27018),
(~"127.0.0.1", 27019),
(~"127.0.0.1", 27020)];
debug!("connecting");
match client.connect_to_rs(seed) {
Ok(_) => (),
Err(e) => fail!("%s", e.to_str()),
}
let rs ... | identifier_body |
rs_stepdown.rs | /* Copyright 2013 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writi... | fail!("expected %?, found %?", t, x);
}
}
Err(e) => println(fmt!("%?", e)),
}
debug!("requesting status until good");
let mut done = false;
while !done {
debug!(fmt!("___status (%?)___", i));
debug!(fmt!("%s\n________________",
mat... | let x = val.unwrap();
if x as f32 != t as f32 { // possible round-off err | random_line_split |
rs_stepdown.rs | /* Copyright 2013 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writi... | () {
let mut i = 0;
let client = @Client::new();
let seed = [(~"127.0.0.1", 27018),
(~"127.0.0.1", 27019),
(~"127.0.0.1", 27020)];
debug!("connecting");
match client.connect_to_rs(seed) {
Ok(_) => (),
Err(e) => fail!("%s", e.to_str()),
}
let ... | test_rs_stepdown | identifier_name |
personDetailComponent.ts | import { Input, Component, OnInit } from '@angular/core';
import { RouteParams, Router } from '@angular/router-deprecated';
import { PersonService } from './personService'
import { PersonModel } from './personModel'
@Component({
selector: 'person-detail',
templateUrl: 'dist/components/person/personDetailTempla... | }
public save() {
console.log('PersonDetailComponent save person', this.person);
this.personService.add(this.person);
this.router.navigate(['PeopleList']);
}
public goBack() {
this.router.navigate(['PeopleList']);
}
} | random_line_split | |
personDetailComponent.ts |
import { Input, Component, OnInit } from '@angular/core';
import { RouteParams, Router } from '@angular/router-deprecated';
import { PersonService } from './personService'
import { PersonModel } from './personModel'
@Component({
selector: 'person-detail',
templateUrl: 'dist/components/person/personDetailTempl... | () {
console.log('PersonDetailComponent ngOnInit');
this.id = parseInt(this.routeParams.get('id'));
this.title = this.id > 0 ? 'Editando pessoa: ' + this.id : 'Novo';
this.person = this.id > 0 ? this.personService.get(this.id) : new PersonModel();
}
constructor(private personSer... | ngOnInit | identifier_name |
personDetailComponent.ts |
import { Input, Component, OnInit } from '@angular/core';
import { RouteParams, Router } from '@angular/router-deprecated';
import { PersonService } from './personService'
import { PersonModel } from './personModel'
@Component({
selector: 'person-detail',
templateUrl: 'dist/components/person/personDetailTempl... |
public save() {
console.log('PersonDetailComponent save person', this.person);
this.personService.add(this.person);
this.router.navigate(['PeopleList']);
}
public goBack() {
this.router.navigate(['PeopleList']);
}
} | {
console.log('PersonDetailComponent ctor');
} | identifier_body |
ad_src_tf_phase_misfit.py | (t, data, synthetic, min_period, max_period,
plot=False, max_criterion=7.0):
"""
:rtype: dictionary
:returns: Return a dictionary with three keys:
* adjoint_source: The calculated adjoint source as a numpy array
* misfit: The misfit value
* messages: A list ... | adsrc_tf_phase_misfit | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.