file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
index_spec.js | import {
cachedData,
getCurrentHoverElement,
setCurrentHoverElement,
addInteractionClass,
} from '~/code_navigation/utils';
afterEach(() => {
if (cachedData.has('current')) {
cachedData.delete('current');
}
});
describe('getCurrentHoverElement', () => {
it.each`
value
${'test'}
${undefin... | });
describe('setCurrentHoverElement', () => {
it('sets cached current key', () => {
setCurrentHoverElement('test');
expect(getCurrentHoverElement()).toEqual('test');
});
});
describe('addInteractionClass', () => {
beforeEach(() => {
setFixtures(
'<div data-path="index.js"><div class="blob-co... |
expect(getCurrentHoverElement()).toEqual(value);
}); | random_line_split |
ark.py | # Author: Krist Jin
# Reviewer: Michael Lissner
# Date created: 2013-08-03
from datetime import datetime
from lxml import html
from juriscraper.OpinionSite import OpinionSite
from juriscraper.lib.string_utils import titlecase
class Site(OpinionSite):
def __init__(self, *args, **kwargs):
sup... | (self):
docket_numbers = []
for e in self.html.xpath('//tr/td[@class="DocumentBrowserCell"][4][../*[4]//text()]//nobr'):
s = html.tostring(e, method='text', encoding='unicode')
docket_numbers.append(s)
return docket_numbers
def _get_judges(self):
path... | _get_docket_numbers | identifier_name |
ark.py | # Author: Krist Jin
# Reviewer: Michael Lissner
# Date created: 2013-08-03
from datetime import datetime
from lxml import html
from juriscraper.OpinionSite import OpinionSite
from juriscraper.lib.string_utils import titlecase
class Site(OpinionSite):
def __init__(self, *args, **kwargs):
sup... |
return docket_numbers
| s = html.tostring(e, method='text', encoding='unicode')
docket_numbers.append(titlecase(s)) | conditional_block |
ark.py | # Author: Krist Jin
# Reviewer: Michael Lissner
# Date created: 2013-08-03
from datetime import datetime
from lxml import html
from juriscraper.OpinionSite import OpinionSite
from juriscraper.lib.string_utils import titlecase
class Site(OpinionSite):
def __init__(self, *args, **kwargs):
sup... | return [t for t in self.html.xpath(path)]
def _get_case_names(self):
path = '//*[@class="DocumentBrowserNameLink"][../../*[4]//text()]/nobr/span[1]/text()'
return [t for t in self.html.xpath(path)]
def _get_case_dates(self):
path = '//tr/td[@class="DocumentBrowserCell"][... | def _get_download_urls(self):
path = '//*[@class="DocumentBrowserNameLink"][../../*[4]//text()]/@href'
| random_line_split |
ark.py | # Author: Krist Jin
# Reviewer: Michael Lissner
# Date created: 2013-08-03
from datetime import datetime
from lxml import html
from juriscraper.OpinionSite import OpinionSite
from juriscraper.lib.string_utils import titlecase
class Site(OpinionSite):
def __init__(self, *args, **kwargs):
sup... |
def _get_case_names(self):
path = '//*[@class="DocumentBrowserNameLink"][../../*[4]//text()]/nobr/span[1]/text()'
return [t for t in self.html.xpath(path)]
def _get_case_dates(self):
path = '//tr/td[@class="DocumentBrowserCell"][5][../*[4]//text()]//nobr/text()'
return... | path = '//*[@class="DocumentBrowserNameLink"][../../*[4]//text()]/@href'
return [t for t in self.html.xpath(path)] | identifier_body |
Entity.js | /**
* @constructor
* @param {Object} entity JSON of a WD entity
*/
WD.Entity = function(entity) {
this.entity = entity;
}
/**
* Gets the array of property's values. If not found, returns undefined.
* @private
* @param {String} prop a property PID (like 'P279')
* @return {Array<object>|undefined} Array of JSON... |
// TODO: if there is a preferred statement, use it
// TODO: else pick first normal ranked statement
var statement = claim[0];
var type = statement.mainsnak.snaktype;
switch(type) {
case 'value':
return statement.mainsnak.datavalue.value;
default:
// TODO: Add other cases
return sta... | WD.Entity.prototype.getClaimValue = function(prop) {
var claim = this.entity.claims[prop];
if(!claim) return undefined; | random_line_split |
radio.tsx | import * as React from 'react';
import RcCheckbox from 'rc-checkbox';
import classNames from 'classnames';
import { composeRef } from 'rc-util/lib/ref';
import { RadioProps, RadioChangeEvent } from './interface';
import { ConfigContext } from '../config-provider';
import RadioGroupContext from './context';
import devWa... |
};
const { prefixCls: customizePrefixCls, className, children, style, ...restProps } = props;
const prefixCls = getPrefixCls('radio', customizePrefixCls);
const radioProps: RadioProps = { ...restProps };
if (context) {
radioProps.name = context.name;
radioProps.onChange = onChange;
radioProps.ch... | {
context.onChange(e);
} | conditional_block |
radio.tsx | import * as React from 'react';
import RcCheckbox from 'rc-checkbox';
import classNames from 'classnames';
import { composeRef } from 'rc-util/lib/ref';
import { RadioProps, RadioChangeEvent } from './interface';
import { ConfigContext } from '../config-provider';
import RadioGroupContext from './context';
import devWa... | export default Radio; | Radio.defaultProps = {
type: 'radio',
};
| random_line_split |
mapfield.js | "use strict";
module.exports = MapField;
// extends Field
var Field = require("./field");
((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField";
var types = require("./types"),
util = require("./util");
/**
* Constructs a new map field instance.
* @classdesc... | (name, id, keyType, type, options) {
Field.call(this, name, id, type, options);
/* istanbul ignore if */
if (!util.isString(keyType))
throw TypeError("keyType must be a string");
/**
* Key type.
* @type {string}
*/
this.keyType = keyType; // toJSON, marker
/**
* Re... | MapField | identifier_name |
mapfield.js | "use strict";
module.exports = MapField;
// extends Field
var Field = require("./field");
((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField";
var types = require("./types"),
util = require("./util");
/**
* Constructs a new map field instance.
* @classdesc... | this.map = true;
}
/**
* Map field descriptor.
* @interface IMapField
* @extends {IField}
* @property {string} keyType Key type
*/
/**
* Extension map field descriptor.
* @interface IExtensionMapField
* @extends IMapField
* @property {string} extend Extended type
*/
/**
* Constructs a map field from ... | {
Field.call(this, name, id, type, options);
/* istanbul ignore if */
if (!util.isString(keyType))
throw TypeError("keyType must be a string");
/**
* Key type.
* @type {string}
*/
this.keyType = keyType; // toJSON, marker
/**
* Resolved key type if not a basic type... | identifier_body |
mapfield.js | "use strict";
module.exports = MapField;
// extends Field
var Field = require("./field");
((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField";
var types = require("./types"),
util = require("./util");
/**
* Constructs a new map field instance.
* @classdesc... | "id" , this.id,
"extend" , this.extend,
"options" , this.options
]);
};
/**
* @override
*/
MapField.prototype.resolve = function resolve() {
if (this.resolved)
return this;
// Besides a value type, map fields have a key type that may be "any scalar type except for f... | random_line_split | |
models.py | from django.db import models
from django.contrib.auth.models import User, Group
from django.utils.translation import ugettext_lazy as _
from django.core.validators import RegexValidator
from django.conf import settings
class Repository(models.Model):
| on_delete=models.SET_NULL,
verbose_name=_('user'),
help_text=_('Owner of the repository. Repository path will be prefixed by owner\'s username.'),
)
# access control
users = models.ManyToManyField(
User,
blank=True,
verbose_name=_('users'),
help_text=... | """
Git repository
"""
# basic info
name = models.CharField(
max_length=64,
validators=[RegexValidator(regex=r'^[^\x00-\x2c\x2f\x3a-\x40\x5b-\x5e\x60\x7b-\x7f\s]+$')],
verbose_name=_('name'),
help_text=_('Name of the repository, cannot contain special characters other th... | identifier_body |
models.py | from django.db import models
from django.contrib.auth.models import User, Group
from django.utils.translation import ugettext_lazy as _
from django.core.validators import RegexValidator
from django.conf import settings
class Repository(models.Model):
"""
Git repository
"""
# basic info
name = mode... | (self):
if self.user:
return u'%s/%s' % (self.user.username, self.name)
return u'./%s' % (self.name)
def can_read(self, user):
if not user and settings.PROTECTED:
return False
if not self.is_private:
return True
return self.can_write(user)... | __unicode__ | identifier_name |
models.py | from django.db import models
from django.contrib.auth.models import User, Group
from django.utils.translation import ugettext_lazy as _
from django.core.validators import RegexValidator
from django.conf import settings
class Repository(models.Model):
"""
Git repository
"""
# basic info
name = mode... |
return u'./%s' % (self.name)
def can_read(self, user):
if not user and settings.PROTECTED:
return False
if not self.is_private:
return True
return self.can_write(user)
def can_write(self, user):
if not user:
return False
if u... | return u'%s/%s' % (self.user.username, self.name) | conditional_block |
models.py | from django.db import models
from django.contrib.auth.models import User, Group
from django.utils.translation import ugettext_lazy as _
from django.core.validators import RegexValidator
from django.conf import settings
class Repository(models.Model):
"""
Git repository
"""
# basic info
name = mode... | # meta
created = models.DateTimeField(auto_now_add=True, verbose_name=_('created'))
modified = models.DateTimeField(auto_now=True, verbose_name=_('modified'))
class Meta:
verbose_name = _('repository')
verbose_name_plural = _('repositories')
ordering = ['user', 'name']
u... | default=True,
verbose_name=_('is private'),
help_text=_('Restrict read access to specified users and groups.'),
)
| random_line_split |
multi_rnn_cell_test.ts | the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific ... | const lstmBias2: tf.Tensor1D = tf.zeros([4]);
const forgetBias = tf.scalar(1.0);
const lstm1 = (data: Tensor2D, c: Tensor2D, h: Tensor2D) =>
tf.basicLSTMCell(forgetBias, lstmKernel1, lstmBias1, data, c, h);
const lstm2 = (data: Tensor2D, c: Tensor2D, h: Tensor2D) =>
tf.basicLSTMCell(for... | random_line_split | |
test_views.py | from django.utils.timezone import get_fixed_timezone
from zerver.lib.test_classes import ZulipTestCase
from analytics.lib.counts import CountStat
from analytics.views import time_range
from datetime import datetime, timedelta
class | (ZulipTestCase):
def test_time_range(self):
# type: () -> None
HOUR = timedelta(hours=1)
DAY = timedelta(days=1)
TZINFO = get_fixed_timezone(-100) # 100 minutes west of UTC
# Using 22:59 so that converting to UTC and applying ceiling_to_{hour,day} do not commute
a_ti... | TestTimeRange | identifier_name |
test_views.py | from django.utils.timezone import get_fixed_timezone
from zerver.lib.test_classes import ZulipTestCase
from analytics.lib.counts import CountStat
from analytics.views import time_range
from datetime import datetime, timedelta
class TestTimeRange(ZulipTestCase):
| [ceiling_hour, ceiling_hour+HOUR])
self.assertEqual(time_range(ceiling_day, ceiling_day+DAY, CountStat.DAY, None),
[ceiling_day, ceiling_day+DAY])
# test min_length
self.assertEqual(time_range(ceiling_hour, ceiling_hour+HOUR, CountStat.HOUR, 4),
... | def test_time_range(self):
# type: () -> None
HOUR = timedelta(hours=1)
DAY = timedelta(days=1)
TZINFO = get_fixed_timezone(-100) # 100 minutes west of UTC
# Using 22:59 so that converting to UTC and applying ceiling_to_{hour,day} do not commute
a_time = datetime(2016, 3... | identifier_body |
test_views.py | from django.utils.timezone import get_fixed_timezone
from zerver.lib.test_classes import ZulipTestCase
from analytics.lib.counts import CountStat
from analytics.views import time_range
from datetime import datetime, timedelta
class TestTimeRange(ZulipTestCase):
def test_time_range(self):
# type: () -> No... | # test start == end == boundary, and min_length == 0
self.assertEqual(time_range(ceiling_hour, ceiling_hour, CountStat.HOUR, 0), [ceiling_hour])
self.assertEqual(time_range(ceiling_day, ceiling_day, CountStat.DAY, 0), [ceiling_day])
# test start and end on different boundaries
se... | self.assertEqual(time_range(a_time, a_time, CountStat.HOUR, None), [ceiling_hour])
self.assertEqual(time_range(a_time, a_time, CountStat.DAY, None), [ceiling_day]) | random_line_split |
controls.py | # -*- coding: utf-8 -*-
# Copyright 2010 Trever Fischer <tdfischer@fedoraproject.org>
#
# This file is part of modulation. | # (at your option) any later version.
#
# modulation is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a cop... | #
# modulation is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or | random_line_split |
controls.py | # -*- coding: utf-8 -*-
# Copyright 2010 Trever Fischer <tdfischer@fedoraproject.org>
#
# This file is part of modulation.
#
# modulation is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3... |
class Seek(ControlPacket):
"""Uses the 'location' data element"""
pass
class Exit(ControlPacket):
"""Indicates a plugin upstream has exited and is no longer part of the graph"""
pass
class PacketDelay(Plugin):
"""PacketDelays are used to wait until a packet of some type has been recieved"""
... | """Uses the 'uri' data element to indicate loading of data"""
pass | identifier_body |
controls.py | # -*- coding: utf-8 -*-
# Copyright 2010 Trever Fischer <tdfischer@fedoraproject.org>
#
# This file is part of modulation.
#
# modulation is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3... |
def wait():
self.__lock.wait() | self.__lock.set() | conditional_block |
controls.py | # -*- coding: utf-8 -*-
# Copyright 2010 Trever Fischer <tdfischer@fedoraproject.org>
#
# This file is part of modulation.
#
# modulation is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3... | (ControlPacket):
"""Skip the current operation"""
pass
class Prev(ControlPacket):
"""Go back to the previous operation"""
pass
class Enqueue(ControlPacket):
"""Passes along a source to enqueue"""
pass
class Load(ControlPacket):
"""Uses the 'uri' data element to indicate loading of data"""... | Next | identifier_name |
step.js | layui.define(['layer', 'carousel'], function (exports) {
var $ = layui.jquery;
var layer = layui.layer;
var carousel = layui.carousel;
// 添加步骤条dom节点
var renderDom = function (elem, stepItems, postion) {
var stepDiv = '<div class="lay-step">';
for (var i = 0; i < stepItems.length; i+... | n) {
stepDiv += '<div class="step-item-head"><i class="layui-icon layui-icon-ok"></i></div>';
} else {
stepDiv += '<div class="step-item-head "><i class="layui-icon">' + number + '</i></div>';
}
// 标题和描述
var title = stepItems[i].title;
... | epDiv += '<div class="step-item-head step-item-head-active"><i class="layui-icon">' + number + '</i></div>';
} else if (i < postio | conditional_block |
step.js | layui.define(['layer', 'carousel'], function (exports) {
var $ = layui.jquery;
var layer = layui.layer;
var carousel = layui.carousel;
// 添加步骤条dom节点
var renderDom = function (elem, stepItems, postion) {
var stepDiv = '<div class="lay-step">';
for (var i = 0; i < stepItems.length; i+... | // 渲染轮播图
carousel.render(param);
// 渲染步骤条
var stepItems = param.stepItems;
renderDom(param.elem, stepItems, 0);
$('.lay-step').css('width', param.stepWidth);
//监听轮播切换事件
carousel.on('change(' + param.filter + ')', function ... | random_line_split | |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
//! Test infrastructure for the Diem VM.
//!
//! This crate contains helpers for executing tests against the Diem VM.
use diem_types::{transaction::TransactionStatus, vm_status::KeptVMStatus};
pub mod account;... | #[macro_export]
macro_rules! assert_prologue_parity {
($e1:expr, $e2:expr, $e3:expr) => {
assert_eq!($e1.unwrap(), $e3);
assert!(transaction_status_eq($e2, &TransactionStatus::Discard($e3)));
};
}
#[macro_export]
macro_rules! assert_prologue_disparity {
($e1:expr => $e2:expr, $e3:expr => $e... | }
| random_line_split |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
//! Test infrastructure for the Diem VM.
//!
//! This crate contains helpers for executing tests against the Diem VM.
use diem_types::{transaction::TransactionStatus, vm_status::KeptVMStatus};
pub mod account;... | (t1: &TransactionStatus, t2: &TransactionStatus) -> bool {
match (t1, t2) {
(TransactionStatus::Discard(s1), TransactionStatus::Discard(s2)) => {
assert_eq!(s1, s2);
true
}
(TransactionStatus::Keep(s1), TransactionStatus::Keep(s2)) => {
assert_eq!(s1, s2);... | transaction_status_eq | identifier_name |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
//! Test infrastructure for the Diem VM.
//!
//! This crate contains helpers for executing tests against the Diem VM.
use diem_types::{transaction::TransactionStatus, vm_status::KeptVMStatus};
pub mod account;... |
#[macro_export]
macro_rules! assert_prologue_parity {
($e1:expr, $e2:expr, $e3:expr) => {
assert_eq!($e1.unwrap(), $e3);
assert!(transaction_status_eq($e2, &TransactionStatus::Discard($e3)));
};
}
#[macro_export]
macro_rules! assert_prologue_disparity {
($e1:expr => $e2:expr, $e3:expr => ... | {
match (t1, t2) {
(TransactionStatus::Discard(s1), TransactionStatus::Discard(s2)) => {
assert_eq!(s1, s2);
true
}
(TransactionStatus::Keep(s1), TransactionStatus::Keep(s2)) => {
assert_eq!(s1, s2);
true
}
_ => false,
}
} | identifier_body |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
//! Test infrastructure for the Diem VM.
//!
//! This crate contains helpers for executing tests against the Diem VM.
use diem_types::{transaction::TransactionStatus, vm_status::KeptVMStatus};
pub mod account;... |
_ => false,
}
}
#[macro_export]
macro_rules! assert_prologue_parity {
($e1:expr, $e2:expr, $e3:expr) => {
assert_eq!($e1.unwrap(), $e3);
assert!(transaction_status_eq($e2, &TransactionStatus::Discard($e3)));
};
}
#[macro_export]
macro_rules! assert_prologue_disparity {
($e1:ex... | {
assert_eq!(s1, s2);
true
} | conditional_block |
options.js | $(()=>{
$('#save').click(()=>{
saveData();
});
for(let website in data){
for(let coin in data[website]){
const idOpen = `${website}.${coin}.warn.open`;
const idLow = `${website}.${coin}.warn.low`;
const idHeight = `${website}.${coin}.warn.height`;
const html =
`<li>`+
| `<input id="${idLow}" placeholder="低 ${coin}" value="${data[website][coin].warn.low}" type="number"/>`+
`<input id="${idHeight}" placeholder="高 ${coin}" value="${data[website][coin].warn.height}" type="number"/>`+
`<input id="${idOpen}" value="true" type="checkbox" ${data[website][coin].warn.open ?'checke... | `<label>${website}</label>`+
`<label>${coin}</label>`+
`<label>${data[website][coin].mark}</label>`+
| random_line_split |
Path.ts | /*--------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2013 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"... |
public static relativeToAbsolute (absolute_parent_path:string, relative_path:string) : string
{
if( Path.isRelative(relative_path) )
{
var absolute_parent_directory = node.path.dirname(absolute_parent_path);
return node.path.join(absolute_parent_directory, relative_path);
}
re... | return path.replace(/\\/gi, "/");
}
| identifier_body |
Path.ts | /*--------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2013 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"... |
return relative_path;
}
public static makeAbsolute(path:string) : string {
if(!magnum.util.Path.isAbsolute(path)) {
return node.path.resolve('./', path);
}
return path;
}
}
} | var absolute_parent_directory = node.path.dirname(absolute_parent_path);
return node.path.join(absolute_parent_directory, relative_path);
}
| conditional_block |
Path.ts | /*--------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2013 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"... | ath:string) : boolean {
if(!magnum.util.Path.isAbsoluteUrl(path)) {
if(!magnum.util.Path.isAbsoluteUrn(path)) {
return false;
}
}
return true;
}
public static isRelative(path:... | Absolute(p | identifier_name |
Path.ts | /*--------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2013 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"... | }
}
}
return false;
}
public static toForwardSlashes(path:string) : string
{
return path.replace(/\\/gi, "/");
}
public static relativeToAbsolute (absolute_parent_path:string, relative_path:string) : string
{
if( Path.isRelative(relative_path) )
{
var absolute_par... | if(!(path.indexOf('/') == 0))
{
return true; | random_line_split |
BooleanNode.js | 'use strict';
var isA = require("Espresso/oop").isA;
var oop = require("Espresso/oop").oop;
var init = require("Espresso/oop").init;
var trim = require("Espresso/trim").trim;
var isA = require("Espresso/oop").isA;
var oop = require("Espresso/oop").oop;
var ScalarNode = require("Espresso/Config/Definition/ScalarNode"... | ($value)
{
// a boolean value cannot be empty
return false;
}
BooleanNode.prototype = Object.create( ScalarNode.prototype );
BooleanNode.prototype.validateType = validateType;
BooleanNode.prototype.isValueEmpty = isValueEmpty;
module.exports = BooleanNode;
| isValueEmpty | identifier_name |
BooleanNode.js | 'use strict';
var isA = require("Espresso/oop").isA;
var oop = require("Espresso/oop").oop;
var init = require("Espresso/oop").init;
var trim = require("Espresso/trim").trim;
var isA = require("Espresso/oop").isA;
var oop = require("Espresso/oop").oop;
var ScalarNode = require("Espresso/Config/Definition/ScalarNode"... |
$ex.setPath(this.getPath());
throw $ex;
}
}
/**
* {@inheritdoc}
*/
function isValueEmpty($value)
{
// a boolean value cannot be empty
return false;
}
BooleanNode.prototype = Object.create( ScalarNode.prototype );
BooleanNode.prototype.validateType = validateType;
BooleanNode.prototype.... | {
$ex.addHint($hint);
} | conditional_block |
BooleanNode.js | 'use strict';
var isA = require("Espresso/oop").isA;
var oop = require("Espresso/oop").oop;
var init = require("Espresso/oop").init;
var trim = require("Espresso/trim").trim;
var isA = require("Espresso/oop").isA;
var oop = require("Espresso/oop").oop;
var ScalarNode = require("Espresso/Config/Definition/ScalarNode"... |
BooleanNode.prototype = Object.create( ScalarNode.prototype );
BooleanNode.prototype.validateType = validateType;
BooleanNode.prototype.isValueEmpty = isValueEmpty;
module.exports = BooleanNode;
| {
// a boolean value cannot be empty
return false;
} | identifier_body |
BooleanNode.js | 'use strict';
var isA = require("Espresso/oop").isA;
var oop = require("Espresso/oop").oop;
var init = require("Espresso/oop").init;
var trim = require("Espresso/trim").trim;
var isA = require("Espresso/oop").isA;
var oop = require("Espresso/oop").oop;
var ScalarNode = require("Espresso/Config/Definition/ScalarNode"... | */
function isValueEmpty($value)
{
// a boolean value cannot be empty
return false;
}
BooleanNode.prototype = Object.create( ScalarNode.prototype );
BooleanNode.prototype.validateType = validateType;
BooleanNode.prototype.isValueEmpty = isValueEmpty;
module.exports = BooleanNode; | /**
* {@inheritdoc} | random_line_split |
iterables.py | """
Functions and decorators for making sure the parameters they work on are of
iterable types.
Copyright 2014-2015, Outernet Inc.
Some rights reserved.
This software is free software licensed under the terms of GPLv3. See COPYING
file that comes with the source code, or http://www.gnu.org/licenses/gpl.txt.
"""
impor... |
def is_iterable(obj):
"""
Determine if the passed in object is an iterable, but not a string or dict.
"""
return (hasattr(obj, '__iter__') and
not isinstance(obj, dict) and
not is_string(obj))
def as_iterable(params=None):
"""
Make sure the marked parameters are iter... | """
Determine if the passed in object is a string.
"""
try:
return isinstance(obj, basestring)
except NameError:
return isinstance(obj, str) | identifier_body |
iterables.py | """
Functions and decorators for making sure the parameters they work on are of
iterable types.
Copyright 2014-2015, Outernet Inc.
Some rights reserved.
This software is free software licensed under the terms of GPLv3. See COPYING
file that comes with the source code, or http://www.gnu.org/licenses/gpl.txt.
"""
impor... |
# invoke ``fn`` with patched parameters
return fn(*args, **kwargs)
return wrapper
return decorator
| for key in keys:
if not is_iterable(kwargs[key]):
kwargs[key] = [kwargs[key]] | conditional_block |
iterables.py | """
Functions and decorators for making sure the parameters they work on are of
iterable types.
Copyright 2014-2015, Outernet Inc.
Some rights reserved.
This software is free software licensed under the terms of GPLv3. See COPYING
file that comes with the source code, or http://www.gnu.org/licenses/gpl.txt.
"""
impor... | (obj):
"""
Determine whether the passed in object is a number of integral type.
"""
return isinstance(obj, numbers.Integral)
def is_string(obj):
"""
Determine if the passed in object is a string.
"""
try:
return isinstance(obj, basestring)
except NameError:
return i... | is_integral | identifier_name |
iterables.py | """
Functions and decorators for making sure the parameters they work on are of
iterable types.
Copyright 2014-2015, Outernet Inc.
Some rights reserved.
| file that comes with the source code, or http://www.gnu.org/licenses/gpl.txt.
"""
import functools
import numbers
def is_integral(obj):
"""
Determine whether the passed in object is a number of integral type.
"""
return isinstance(obj, numbers.Integral)
def is_string(obj):
"""
Determine if t... | This software is free software licensed under the terms of GPLv3. See COPYING | random_line_split |
utility.rs | use std::sync::Arc;
| /// [`ArenaSet`]: struct.ArenaSet.html
pub fn string_arena_set() -> ArenaSet<String> {
builder().hash().unwrap()
}
/// Create an [`ArenaSet`] for `Vec<u8>` with a `HashMap` and an ID of `usize`.
/// [`ArenaSet`]: struct.ArenaSet.html
pub fn byte_arena_set() -> ArenaSet<Vec<u8>> {
builder().hash().unwrap()
}
/... | use builder::builder;
use arena_set::{ArenaSet, StadiumSet};
/// Create an [`ArenaSet`] for `String` with a `HashMap` and an ID of `usize`. | random_line_split |
utility.rs | use std::sync::Arc;
use builder::builder;
use arena_set::{ArenaSet, StadiumSet};
/// Create an [`ArenaSet`] for `String` with a `HashMap` and an ID of `usize`.
/// [`ArenaSet`]: struct.ArenaSet.html
pub fn string_arena_set() -> ArenaSet<String> {
builder().hash().unwrap()
}
/// Create an [`ArenaSet`] for `Vec<u8... |
/// Create a [`StadiumSet`] for `Arc<String>` with a `HashMap` and an ID of `usize`.
/// [`StadiumSet`]: struct.StadiumSet.html
pub fn string_stadium_set() -> StadiumSet<Arc<String>> {
builder().stadium_set_hash().unwrap()
}
/// Create a [`StadiumSet`] for `Arc<Vec<u8>>` with a `HashMap` and an ID of `usize`.
//... | {
builder().hash().unwrap()
} | identifier_body |
utility.rs | use std::sync::Arc;
use builder::builder;
use arena_set::{ArenaSet, StadiumSet};
/// Create an [`ArenaSet`] for `String` with a `HashMap` and an ID of `usize`.
/// [`ArenaSet`]: struct.ArenaSet.html
pub fn string_arena_set() -> ArenaSet<String> {
builder().hash().unwrap()
}
/// Create an [`ArenaSet`] for `Vec<u8... | () -> StadiumSet<Arc<Vec<u8>>> {
builder().stadium_set_hash().unwrap()
}
| byte_stadium_set | identifier_name |
drupal.js | object containing settings for the current context. If none given, the
* global Drupal.settings object is used.
*/
Drupal.attachBehaviors = function (context, settings) {
context = context || document;
settings = settings || Drupal.settings;
// Execute all of them.
$.each(Drupal.behaviors, function () {
... | * @param str
* A string containing the English string to translate.
* @param args
* An object of replacements pairs to make after translation. Incidences
* of any key in this array are replaced with the corresponding value.
* See Drupal.formatString().
* @return
* The translated string.
*/
Drupal.t =... | * Translate strings to the page language or a given language.
*
* See the documentation of the server-side t() function for further details.
* | random_line_split |
langcode.ts | import zhTW from '@opentranslate/languages/locales/zh-TW.json'
import { locale as _locale } from '../zh-CN/langcode' | ara: '阿拉伯語',
'bs-Latn': '波斯尼亞語',
bul: '保加利亞語',
cht: '中文(繁體)',
dan: '丹麥語',
est: '愛沙尼亞語',
fin: '芬蘭語',
fra: '法語',
iw: '希伯來語',
jp: '日語',
kor: '韓語',
kr: '韓語',
pt_BR: '巴西語',
rom: '羅馬尼亞語',
slo: '斯洛維尼亞語',
spa: '西班牙語',
swe: '瑞典語',
tl: '他加祿語(菲律賓語)',
vie: '越南語',
zh: '中文(簡體)',
'zh-CHS': '中... |
export const locale: typeof _locale = {
...zhTW,
default: '同介面語言', | random_line_split |
fps.rs | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang
//
// 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, c... | () -> Fps {
Fps {
frames: 0.,
cur_frames: 0.,
frame_start: time::precise_time_s()
}
}
}
impl PerfHandler for Fps {
fn reset(&mut self) -> () {
self.frames = 0.;
self.cur_frames = 0.;
self.frame_start = time::precise_time_s();
}
fn frame_begin(&mut self) -> () {
}
fn frame_end(&mut self)... | new | identifier_name |
fps.rs | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang
//
// 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, c... | fn frame_end(&mut self) -> () {
self.cur_frames += 1.;
if time::precise_time_s() - self.frame_start >= 1. {
self.frame_start = time::precise_time_s();
self.frames = self.cur_frames;
self.cur_frames = 0.;
}
}
fn get_value(&self) -> Option<f64> {
Some(self.frames)
}
} | fn frame_begin(&mut self) -> () {
}
| random_line_split |
fps.rs | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang
//
// 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, c... |
}
fn get_value(&self) -> Option<f64> {
Some(self.frames)
}
} | {
self.frame_start = time::precise_time_s();
self.frames = self.cur_frames;
self.cur_frames = 0.;
} | conditional_block |
fps.rs | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang
//
// 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, c... |
fn frame_end(&mut self) -> () {
self.cur_frames += 1.;
if time::precise_time_s() - self.frame_start >= 1. {
self.frame_start = time::precise_time_s();
self.frames = self.cur_frames;
self.cur_frames = 0.;
}
}
fn get_value(&self) -> Option<f64> {
Some(self.frames)
}
} | {
} | identifier_body |
host.py | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2012 VMware, 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/lic... | data["disk_total"] = capacity / units.Gi
data["disk_available"] = freespace / units.Gi
data["disk_used"] = data["disk_total"] - data["disk_available"]
data["host_memory_total"] = stats['mem']['total']
data["host_memory_free"] = stats['mem']['free']
data["hypervisor_type"]... | {'node': self._host_name, 'error': ex})
self._set_host_enabled(False)
return data
data["vcpus"] = stats['cpu']['vcpus'] | random_line_split |
host.py | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2012 VMware, 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/lic... |
def update_status(self):
"""Update the current state of the cluster."""
data = {}
try:
capacity, freespace = _get_ds_capacity_and_freespace(self._session,
self._cluster, self._datastore_regex)
# Get cpu, memory stats from the cluster
sta... | """Return the current state of the cluster. If 'refresh' is
True, run the update first.
"""
if refresh or not self._stats:
self.update_status()
return self._stats | identifier_body |
host.py | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2012 VMware, 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/lic... | (self, refresh=False):
"""Return the current state of the cluster. If 'refresh' is
True, run the update first.
"""
if refresh or not self._stats:
self.update_status()
return self._stats
def update_status(self):
"""Update the current state of the cluster."... | get_host_stats | identifier_name |
host.py | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2012 VMware, 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/lic... |
return self._stats
def update_status(self):
"""Update the current state of the cluster."""
data = {}
try:
capacity, freespace = _get_ds_capacity_and_freespace(self._session,
self._cluster, self._datastore_regex)
# Get cpu, memory stats from ... | self.update_status() | conditional_block |
CreateOrgOverlay.tsx | // Libraries
import React, {PureComponent, ChangeEvent} from 'react'
import {connect, ConnectedProps} from 'react-redux'
import {RouteComponentProps, withRouter} from 'react-router-dom'
import {sample, startCase} from 'lodash'
// Components
import {Form, Input, Button, Overlay} from '@influxdata/clockface'
// Types
... | (props) {
super(props)
this.state = {
org: {name: ''},
bucket: {name: '', retentionRules: [], readableRetention: 'forever'},
orgNameInputStatus: ComponentStatus.Default,
bucketNameInputStatus: ComponentStatus.Default,
orgErrorMessage: '',
bucketErrorMessage: '',
}
}
... | constructor | identifier_name |
CreateOrgOverlay.tsx | // Libraries
import React, {PureComponent, ChangeEvent} from 'react'
import {connect, ConnectedProps} from 'react-redux'
import {RouteComponentProps, withRouter} from 'react-router-dom'
import {sample, startCase} from 'lodash'
// Components
import {Form, Input, Button, Overlay} from '@influxdata/clockface'
// Types
... | })
}
private handleChangeBucketInput = (e: ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
const key = e.target.name
const bucket = {...this.state.bucket, [key]: value}
if (!value) {
return this.setState({
bucket,
bucketNameInputStatus: ComponentStatus.Er... |
this.setState({
org,
orgNameInputStatus: ComponentStatus.Valid,
orgErrorMessage: '', | random_line_split |
CreateOrgOverlay.tsx | // Libraries
import React, {PureComponent, ChangeEvent} from 'react'
import {connect, ConnectedProps} from 'react-redux'
import {RouteComponentProps, withRouter} from 'react-router-dom'
import {sample, startCase} from 'lodash'
// Components
import {Form, Input, Button, Overlay} from '@influxdata/clockface'
// Types
... |
this.setState({
bucket,
bucketNameInputStatus: ComponentStatus.Valid,
bucketErrorMessage: '',
})
}
private randomErrorMessage = (key: string, resource: string): string => {
const messages = [
`Imagine that! ${startCase(resource)} without a ${key}`,
`${startCase(resource)... | {
return this.setState({
bucket,
bucketNameInputStatus: ComponentStatus.Error,
bucketErrorMessage: this.randomErrorMessage(key, 'bucket'),
})
} | conditional_block |
test.js | appReady,
focusWindow,
minimizeWindow,
restoreWindow,
windowVisible
} = require('.');
let win;
test('exports an appReady function', async t => {
t.is(typeof appReady, 'function');
});
test('appReady return a promise that resolve when electron app is ready', async t => {
await appReady();
// We could create a... | 'use strict';
const {BrowserWindow, app} = require('electron');
const test = require('tape-async');
const delay = require('delay');
const { | random_line_split | |
index.test.js | /**
* Testing our link component
*/ |
import React from 'react';
import { shallow } from 'enzyme';
import A from '../index';
const href = 'http://mxstbr.com/';
const children = <h1>Test</h1>;
const renderComponent = (props = {}) =>
shallow(
<A href={href} {...props}>
{children}
</A>,
);
describe('<A />', () => {
it('should render an... | random_line_split | |
paulo-consolidation.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import paulo
import getopt
import sys
import os.path
# usage:
# export PYTHONUNBUFFERED=1
# ./paulo-consolidation.py -c backup-titres.csv -i /media/jm/Elements/backup/musique/ -o /mnt/paulo/home/sound/ -I 0.4 | tee -a log-copy.txt
def | ():
print "Usage: paulo-consolidation.py [options]"
print "Required ptions:"
print " -c, --csv FILENAME The input CSV file"
print " -i, --input-dir DIR A directory with mp3 files"
print " -o, --output-dir DIR A directory where the files will be stored"
print " -I, --i... | usage | identifier_name |
paulo-consolidation.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import paulo
import getopt
import sys
import os.path
# usage:
# export PYTHONUNBUFFERED=1
# ./paulo-consolidation.py -c backup-titres.csv -i /media/jm/Elements/backup/musique/ -o /mnt/paulo/home/sound/ -I 0.4 | tee -a log-copy.txt
def usage():
|
def main(argv):
csvFile=""
inputDir=""
outputDir=""
interactiveThresold=None
negativeAnswersFile=""
similarity=False
try:
opts, args = getopt.getopt(argv, "hc:i:o:I:n:s", ["help", "csv=", "input-dir=", "output-dir=", "interactive=", "negative-an... | print "Usage: paulo-consolidation.py [options]"
print "Required ptions:"
print " -c, --csv FILENAME The input CSV file"
print " -i, --input-dir DIR A directory with mp3 files"
print " -o, --output-dir DIR A directory where the files will be stored"
print " -I, --interacti... | identifier_body |
paulo-consolidation.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import paulo
import getopt
import sys
import os.path
# usage:
# export PYTHONUNBUFFERED=1
# ./paulo-consolidation.py -c backup-titres.csv -i /media/jm/Elements/backup/musique/ -o /mnt/paulo/home/sound/ -I 0.4 | tee -a log-copy.txt
def usage():
print "Usage: paulo-co... |
if entry in result:
matchCount += 1
if bestScore > 0.8:
autoMovedCount += 1
print "Automatic copy (" + str(bestScore) + "): " + outputDir + "/" + entry.getTargetFile() + " from " + result[entry][1].filename
paulo.copy(outputDir + "/" + en... | e_meta = entry.getMetaData()
es_mp3file = mp3file.getMetaDatas()
for e_mp3file in es_mp3file:
score = e_meta.similarity(e_mp3file)
if score > bestScore:
result[entry] = [score, mp3file]
... | conditional_block |
paulo-consolidation.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import paulo
import getopt
import sys
import os.path
# usage:
# export PYTHONUNBUFFERED=1
# ./paulo-consolidation.py -c backup-titres.csv -i /media/jm/Elements/backup/musique/ -o /mnt/paulo/home/sound/ -I 0.4 | tee -a log-copy.txt
def usage():
print "Usage: paulo-co... | paulo.setTags(outputDir + "/" + entry.getTargetFile(), entry)
log.append(entry.toCSVLine())
else:
if interactiveThresold != None:
print "Score: " + str(bestScore) + "\n" + str(entry) + "\n" + str(result[entry][1])
if pa... | if bestScore > 0.8:
autoMovedCount += 1
print "Automatic copy (" + str(bestScore) + "): " + outputDir + "/" + entry.getTargetFile() + " from " + result[entry][1].filename
paulo.copy(outputDir + "/" + entry.getTargetFile(), result[entry][1].filename) | random_line_split |
app.js | var internApplication = (function(){
var currentLat,
currentLong,
responseData,
currentRestaurant,
currentRestaurantNum,
initialSearchFinished;
var options = {};
// set options based on filters chosen by user
var setOptions = function(){
var radiusValu... |
navigator.geolocation.getCurrentPosition(getPosition);
// use freegeoip.net as a fallback
} else {
console.log('using freegeoip.net...');
var georequestOptions = {
method: 'GET',
url: 'http://www.freegeoip.net/json/'
};... | {
currentLat = position.coords.latitude.toFixed(8);
currentLong = position.coords.longitude.toFixed(8);
callback();
} | identifier_body |
app.js | var internApplication = (function(){
var currentLat,
currentLong,
responseData,
currentRestaurant,
currentRestaurantNum,
initialSearchFinished;
var options = {};
// set options based on filters chosen by user
var setOptions = function(){
var radiusValu... | (position){
currentLat = position.coords.latitude.toFixed(8);
currentLong = position.coords.longitude.toFixed(8);
callback();
}
navigator.geolocation.getCurrentPosition(getPosition);
// use freegeoip.net as a fallback
} else {
... | getPosition | identifier_name |
app.js | var internApplication = (function(){
var currentLat,
currentLong, | responseData,
currentRestaurant,
currentRestaurantNum,
initialSearchFinished;
var options = {};
// set options based on filters chosen by user
var setOptions = function(){
var radiusValue = document.getElementById('distanceFilter').querySelector('.selected').getAtt... | random_line_split | |
app.js | var internApplication = (function(){
var currentLat,
currentLong,
responseData,
currentRestaurant,
currentRestaurantNum,
initialSearchFinished;
var options = {};
// set options based on filters chosen by user
var setOptions = function(){
var radiusValu... | }
}
var reroll = function(){
console.log('rerolling...');
// get random restaurant number based on current search
randomRestaurant(responseData);
// get the chosen restaurant data
getZomatoData(currentRestaurantNum, 1, function(){
currentRestaur... | {
getLocation(function(){
var geoRequestRes = JSON.parse(this.response);
currentLat = geoRequestRes.latitude;
currentLong = geoRequestRes.longitude;
console.log(currentLat + ', ' + currentLong);
// get data based on current... | conditional_block |
test_api.py | # Copyright 2015 Mirantis Inc.
# All Rights Reserved.
#
# 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 a... | self.mock_object(manila_api.log, 'setup')
self.mock_object(manila_api.log, 'register_options')
self.mock_object(manila_api.utils, 'monkey_patch')
self.mock_object(manila_api.service, 'process_launcher')
self.mock_object(manila_api.service, 'WSGIService')
manila_api.main()
... | identifier_body | |
test_api.py | # Copyright 2015 Mirantis Inc.
# All Rights Reserved.
#
# 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 a... | (self):
super(ManilaCmdApiTestCase, self).setUp()
sys.argv = ['manila-api']
def test_main(self):
self.mock_object(manila_api.log, 'setup')
self.mock_object(manila_api.log, 'register_options')
self.mock_object(manila_api.utils, 'monkey_patch')
self.mock_object(manila_... | setUp | identifier_name |
test_api.py | # Copyright 2015 Mirantis Inc.
# All Rights Reserved.
#
# 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 a... | CONF = manila_api.CONF
class ManilaCmdApiTestCase(test.TestCase):
def setUp(self):
super(ManilaCmdApiTestCase, self).setUp()
sys.argv = ['manila-api']
def test_main(self):
self.mock_object(manila_api.log, 'setup')
self.mock_object(manila_api.log, 'register_options')
se... | from manila import version
| random_line_split |
pycomparisons.py | ###
# Copyright 2011 Diamond Light Source Ltd. | #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing ... | #
# 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 | random_line_split |
util.ts | "use strict";
import * as child from "child_process";
import * as path from "path";
import * as shelljs from "shelljs";
import {ExecOutputReturnValue} from "shelljs";
import {SpawnSyncOptionsWithStringEncoding} from "child_process";
import * as childProcess from "child_process";
export class Util {
public cd(absol... | if (shelljs.test("-e", filePath)) {
throw new Error("rm -r failed for " + filePath);
}
}
} | return;
}
shelljs.rm("-r", filePath);
| random_line_split |
util.ts | "use strict";
import * as child from "child_process";
import * as path from "path";
import * as shelljs from "shelljs";
import {ExecOutputReturnValue} from "shelljs";
import {SpawnSyncOptionsWithStringEncoding} from "child_process";
import * as childProcess from "child_process";
export class Util {
public cd(absol... | (dirName: string): string[] {
let dir = dirName;
const testContext = [];
while (/test/.test(dir)) {
testContext.push(path.basename(dir));
dir = path.dirname(dir);
}
testContext.reverse();
return testContext;
}
private rmFile(file: string): void {
if (!shelljs.test("-e", f... | initializeTestContext | identifier_name |
util.ts | "use strict";
import * as child from "child_process";
import * as path from "path";
import * as shelljs from "shelljs";
import {ExecOutputReturnValue} from "shelljs";
import {SpawnSyncOptionsWithStringEncoding} from "child_process";
import * as childProcess from "child_process";
export class Util {
public cd(absol... |
shelljs.rm("-r", filePath);
if (shelljs.test("-e", filePath)) {
throw new Error("rm -r failed for " + filePath);
}
}
}
| {
return;
} | conditional_block |
TcamView.py | ""
self.file_location = "/tmp"
self.caps = None
self.state = None
self.videosaver = None
self.imagesaver = None
self.window_id = self.container.winId()
self.displaysink = None
def get_caps_desc(self):
"""
Returns a CapsDesc describing the cap... |
def video_saved_callback(self, video_path: str):
"""
SLOT for videosaver callback for successfull saving
"""
self.video_saved.emit(video_path)
def start_recording_video(self, video_type: str):
"""
"""
if self.videosaver:
log.error("A video ... | pass | identifier_body |
TcamView.py | _gst_state() == Gst.State.PLAYING:
log.debug("Setting state to NULL")
# Set to NULL to ensure that buffers,
# etc are destroyed.
# do this by calling stop
# so that additional steps like fps.stop()
# are taken
self.stop()
se... | is_trigger_mode_on | identifier_name | |
TcamView.py | def __init__(self, serial: str, dev_type: str, parent=None):
super(TcamView, self).__init__(parent)
self.layout = QHBoxLayout()
self.container = TcamScreen(self)
self.container.new_pixel_under_mouse.connect(self.new_pixel_under_mouse_slot)
self.fullscreen_container = None # ... | new_pixel_under_mouse = pyqtSignal(bool, int, int, QtGui.QColor)
current_fps = pyqtSignal(float)
format_selected = pyqtSignal(str, str, str) # format, widthxheight, framerate
first_image = pyqtSignal()
| random_line_split | |
TcamView.py | log.info("Setting format to {}".format(video_format))
caps = self.pipeline.get_by_name("bin")
caps.set_property("device-caps",
video_format)
if self.state and self.settings.apply_property_cache:
log.info("Property state found.")
... | if value == "On":
return True | conditional_block | |
import_mr_sessions_stroop.py | #!/usr/bin/env python
##
## See COPYING file distributed along with the ncanda-data-integration package
## for the copyright and license terms
##
from __future__ import print_function
from builtins import str
import os
import re
import tempfile
import shutil
from sibispy import sibislogger as slog
from sibispy impo... |
experiment.resources[stroop_resource].files[stroop_file].download( stroop_file_path, verbose=False )
except IOError as e:
details = "Error: import_mr_sessions_stroop: unable to get copy resource {0} file {1} to {2}".format(stroop_resource, stroop_file, stroop_file_path)
slog.info(str(redca... | os.makedirs(stroop_dir_path) | conditional_block |
import_mr_sessions_stroop.py | #!/usr/bin/env python
##
## See COPYING file distributed along with the ncanda-data-integration package
## for the copyright and license terms
##
from __future__ import print_function
from builtins import str
import os
import re
import tempfile
import shutil
from sibispy import sibislogger as slog
from sibispy impo... | return (None, None, None)
# Get first file from list, warn if more files
if len( stroop_files ) > 1:
error = "ERROR: experiment have/has more than one Stroop .txt file. Please make sure there is exactly one per session."
for xnat_eid in xnat_eid_list:
slog.info(xnat_eid,erro... | # No matching files - nothing to do
if len( stroop_files ) == 0:
if verbose :
print("check_for_stroop: no stroop") | random_line_split |
import_mr_sessions_stroop.py | #!/usr/bin/env python
##
## See COPYING file distributed along with the ncanda-data-integration package
## for the copyright and license terms
##
from __future__ import print_function
from builtins import str
import os
import re
import tempfile
import shutil
from sibispy import sibislogger as slog
from sibispy impo... | ( xnat, stroop_eid, stroop_resource, stroop_file, \
redcap_key, verbose=False, no_upload=False, post_to_github=False, time_log_dir=None):
if verbose:
print("Importing Stroop data from file %s:%s" % ( stroop_eid, stroop_file ))
# Download Stroop file from XNAT into temporary... | import_stroop_to_redcap | identifier_name |
import_mr_sessions_stroop.py | #!/usr/bin/env python
##
## See COPYING file distributed along with the ncanda-data-integration package
## for the copyright and license terms
##
from __future__ import print_function
from builtins import str
import os
import re
import tempfile
import shutil
from sibispy import sibislogger as slog
from sibispy impo... | (ecode,sout, serr) = sutils.call_shell_program(cmd)
if ecode:
slog.info(str(redcap_key[0]) + "-" + str(redcap_key[1]), "Error: import_stroop_to_redcap: failed to run stroop2csv!", cmd = str(cmd), stderr = str(serr), stdout = str(sout))
added_files = sout
if len( added_files ):
if not... | if verbose:
print("Importing Stroop data from file %s:%s" % ( stroop_eid, stroop_file ))
# Download Stroop file from XNAT into temporary directory
experiment = xnat.select.experiments[stroop_eid]
tempdir = tempfile.mkdtemp()
try:
stroop_file_path = os.path.join( tempdir, stroop_file )
... | identifier_body |
validators.js | import { isBlank, isPresent, CONST_EXPR, isString } from 'angular2/src/facade/lang';
import { PromiseWrapper } from 'angular2/src/facade/promise';
import { ObservableWrapper } from 'angular2/src/facade/async';
import { StringMapWrapper } from 'angular2/src/facade/collection';
import { OpaqueToken } from 'angular2/c... | * var loginControl = new Control("", Validators.required)
* ```
*/
export class Validators {
/**
* Validator that requires controls to have a non-empty value.
*/
static required(control) {
return isBlank(control.value) || (isString(control.value) && control.value == "") ?
... | * ### Example
*
* ```typescript
| random_line_split |
validators.js | import { isBlank, isPresent, CONST_EXPR, isString } from 'angular2/src/facade/lang';
import { PromiseWrapper } from 'angular2/src/facade/promise';
import { ObservableWrapper } from 'angular2/src/facade/async';
import { StringMapWrapper } from 'angular2/src/facade/collection';
import { OpaqueToken } from 'angular2/c... | (control) {
return isBlank(control.value) || (isString(control.value) && control.value == "") ?
{ "required": true } :
null;
}
/**
* Validator that requires controls to have a value of a minimum length.
*/
static minLength(minLength) {
return (contr... | required | identifier_name |
validators.js | import { isBlank, isPresent, CONST_EXPR, isString } from 'angular2/src/facade/lang';
import { PromiseWrapper } from 'angular2/src/facade/promise';
import { ObservableWrapper } from 'angular2/src/facade/async';
import { StringMapWrapper } from 'angular2/src/facade/collection';
import { OpaqueToken } from 'angular2/c... |
}
function _convertToPromise(obj) {
return PromiseWrapper.isPromise(obj) ? obj : ObservableWrapper.toPromise(obj);
}
function _executeValidators(control, validators) {
return validators.map(v => v(control));
}
function _mergeErrors(arrayOfErrors) {
var res = arrayOfErrors.reduce((res, errors) => {... | {
if (isBlank(validators))
return null;
var presentValidators = validators.filter(isPresent);
if (presentValidators.length == 0)
return null;
return function (control) {
let promises = _executeValidators(control, presentValidators).map(_convertT... | identifier_body |
properties_b.js | var searchData=
[
['queue_351',['Queue',['../interface_n_a_t_s_1_1_client_1_1_i_subscription.html#a3e505b346b8dc6339e84059441d9b1f4',1,'NATS.Client.ISubscription.Queue()'],['../class_n_a_t_s_1_1_client_1_1_subscription.html#ad275b73355ef820f9ce461689170c028',1,'NATS.Client.Subscription.Queue()']]], | ['queuedmessagecount_352',['QueuedMessageCount',['../interface_n_a_t_s_1_1_client_1_1_i_subscription.html#ab474bbe759abcb118e92890918b78fb8',1,'NATS.Client.ISubscription.QueuedMessageCount()'],['../class_n_a_t_s_1_1_client_1_1_subscription.html#a9ec19bba2b4606d7791a0db697baf962',1,'NATS.Client.Subscription.QueuedMess... | random_line_split | |
class_mesh_info_v_o.js | var class_mesh_info_v_o =
[ | [ "getMeshFileName", "dd/d2b/class_mesh_info_v_o.html#a39483391c6c960085d70899d4b547736", null ],
[ "getMeshPath", "dd/d2b/class_mesh_info_v_o.html#a60e430e3d4576a765bda8eed227791a5", null ],
[ "initializeVariables", "dd/d2b/class_mesh_info_v_o.html#a599e902d91c51d84af8436cc707b59c4", null ],
[ "is3DMes... | [ "MeshInfoVO", "dd/d2b/class_mesh_info_v_o.html#afe2d8a9830ec908b600090dc212838cb", null ],
[ "clear", "dd/d2b/class_mesh_info_v_o.html#ac654ec77dcb43760be93d6deed1ae72f", null ],
[ "getBoundaryNameList", "dd/d2b/class_mesh_info_v_o.html#a22d9df6fdd5f31aa190cc5044b992af3", null ],
[ "getBoundaryNameLis... | random_line_split |
unboxed-closures-extern-fn.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let z = call_it_once(square, 22);
assert_eq!(x, square(22));
assert_eq!(y, square(22));
assert_eq!(z, square(22));
} |
fn main() {
let x = call_it(&square, 22);
let y = call_it_mut(&mut square, 22); | random_line_split |
unboxed-closures-extern-fn.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <F:Fn(isize)->isize>(f: &F, x: isize) -> isize {
f(x)
}
fn call_it_mut<F:FnMut(isize)->isize>(f: &mut F, x: isize) -> isize {
f(x)
}
fn call_it_once<F:FnOnce(isize)->isize>(f: F, x: isize) -> isize {
f(x)
}
fn main() {
let x = call_it(&square, 22);
let y = call_it_mut(&mut square, 22);
let z ... | call_it | identifier_name |
unboxed-closures-extern-fn.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = call_it(&square, 22);
let y = call_it_mut(&mut square, 22);
let z = call_it_once(square, 22);
assert_eq!(x, square(22));
assert_eq!(y, square(22));
assert_eq!(z, square(22));
} | identifier_body | |
combine-latest.js | import assert from 'assert';
import { parse } from './parse.js';
import { combineLatest } from '../../src/extras.js';
describe('extras/combineLatest', () => {
it('should emit arrays containing the most recent values', async () => {
let output = [];
await combineLatest(
parse('a-b-c-d'),
parse('-A... | 'dD',
]);
});
}); | 'bC',
'cC',
'cD', | random_line_split |
_marker.rs | pub fn _marker() {
phantom_data_struct();
copy_trait();
// send_trait
// sync_trait
// unsize_trait
}
fn phantom_data_struct() {
use std::marker::PhantomData;
struct Slice<'a, T: 'a> {
start: *const T,
end: *const T,
phantom: PhantomData<&'a T>,
}
fn | <'a, T>(vec: &'a Vec<T>) -> Slice<'a, T> {
let ptr = vec.as_ptr();
Slice {
start: ptr,
end: unsafe { ptr.offset(vec.len() as isize) },
phantom: PhantomData,
}
}
}
fn copy_trait() {
#[derive(Copy, Clone)]
struct MyStructOne;
struct MyStructTwo... | borrow_vec | identifier_name |
_marker.rs | // sync_trait
// unsize_trait
}
fn phantom_data_struct() {
use std::marker::PhantomData;
struct Slice<'a, T: 'a> {
start: *const T,
end: *const T,
phantom: PhantomData<&'a T>,
}
fn borrow_vec<'a, T>(vec: &'a Vec<T>) -> Slice<'a, T> {
let ptr = vec.as_ptr();
... | pub fn _marker() {
phantom_data_struct();
copy_trait();
// send_trait | random_line_split | |
_marker.rs | pub fn _marker() |
fn phantom_data_struct() {
use std::marker::PhantomData;
struct Slice<'a, T: 'a> {
start: *const T,
end: *const T,
phantom: PhantomData<&'a T>,
}
fn borrow_vec<'a, T>(vec: &'a Vec<T>) -> Slice<'a, T> {
let ptr = vec.as_ptr();
Slice {
start: ptr,
... | {
phantom_data_struct();
copy_trait();
// send_trait
// sync_trait
// unsize_trait
} | identifier_body |
font_face.rs | `UrlSource` represents a font-face source that has been specified with a
/// `url()` function.
///
/// <https://drafts.csswg.org/css-fonts/#src-desc>
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct UrlSource {
/// The specified url.
pub url: Spec... |
}
}
rule
}
/// A @font-face rule that is known to have font-family and src declarations.
#[cfg(feature = "servo")]
pub struct FontFace<'a>(&'a FontFaceRuleData);
/// A list of effective sources that we send over through IPC to the font cache.
#[cfg(feature = "servo")]
#[derive(Clone, Debug)]
#[cfg_at... | {
let location = error.location;
let error = ContextualParseError::UnsupportedFontFaceDescriptor(slice, error);
context.log_css_error(error_context, location, error)
} | conditional_block |
font_face.rs | A `UrlSource` represents a font-face source that has been specified with a
/// `url()` function.
///
/// <https://drafts.csswg.org/css-fonts/#src-desc>
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct UrlSource {
/// The specified url.
pub url: Sp... | <W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
self.url.to_css(dest)
}
}
/// A font-display value for a @font-face rule.
/// The font-display descriptor determines how a font face is displayed based
/// on whether and when it is downloaded and ready to use.
define_css_keyword_en... | to_css | identifier_name |
font_face.rs | use selectors::parser::SelectorParseErrorKind;
use shared_lock::{SharedRwLockReadGuard, ToCssWithGuard};
use std::fmt;
use style_traits::{Comma, OneOrMoreSeparated, ParseError, StyleParseErrorKind, ToCss};
use values::computed::font::FamilyName;
use values::specified::url::SpecifiedUrl;
/// A source for a font-face ru... | use properties::longhands::font_language_override; | random_line_split | |
bip65-cltv-p2p.py | #!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import start_nodes
from test_framework.mininode import CTran... |
def setup_network(self):
self.nodes = start_nodes(1, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1']],
binary=[self.options.testbinary])
self.is_network_split = False
def run_test(self):
test = TestM... | self.num_nodes = 1 | identifier_body |
bip65-cltv-p2p.py | #!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import start_nodes
from test_framework.mininode import CTran... | BIP65Test().main() | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.