file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
p2p_disconnect_ban.py | #!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test node disconnect and ban behavior"""
import time
from test_framework.test_framework import GuldenT... |
if __name__ == '__main__':
DisconnectBanTest().main()
| self.log.info("Test setban and listbanned RPCs")
self.log.info("setban: successfully ban single IP address")
assert_equal(len(self.nodes[1].getpeerinfo()), 2) # node1 should have 2 connections to node0 at this point
self.nodes[1].setban(subnet="127.0.0.1", command="add")
wait_until(lam... | identifier_body |
SurveyForm.js | import React, {Component, PropTypes} from 'react';
import {connectReduxForm} from 'redux-form';
import surveyValidation from '../validation/surveyValidation';
import mapProps from 'map-props';
function asyncValidator(data) {
// TODO: figure out a way to move this to the server. need an instance of ApiClient
if (!d... | isDirty,
valid,
invalid,
pristine,
dirty
} = this.props;
return (
<div>
<form className="form-horizontal" onSubmit={handleSubmit}>
<div className={'form-group' + (nameError && nameTouched ? ' has-error' : '')}>
<label htmlFor="name" className="... | handleChange,
handleSubmit, | random_line_split |
SurveyForm.js | import React, {Component, PropTypes} from 'react';
import {connectReduxForm} from 'redux-form';
import surveyValidation from '../validation/surveyValidation';
import mapProps from 'map-props';
function asyncValidator(data) {
// TODO: figure out a way to move this to the server. need an instance of ApiClient
if (!d... |
resolve(errors);
}, 1000);
});
}
@connectReduxForm('survey', ['name','email','occupation'], surveyValidation).async(asyncValidator, 'email')
export default
class SurveyForm extends Component {
static propTypes = {
asyncValidating: PropTypes.bool.isRequired,
data: PropTypes.object.isRequired,
... | {
errors.email = 'Email address already used';
errors.valid = false;
} | conditional_block |
SurveyForm.js | import React, {Component, PropTypes} from 'react';
import {connectReduxForm} from 'redux-form';
import surveyValidation from '../validation/surveyValidation';
import mapProps from 'map-props';
function | (data) {
// TODO: figure out a way to move this to the server. need an instance of ApiClient
if (!data.email) {
return Promise.resolve({valid: true});
}
return new Promise((resolve) => {
setTimeout(() => {
const errors = {valid: true};
if (~['bobby@gmail.com', 'timmy@microsoft.com'].indexOf(... | asyncValidator | identifier_name |
ex_dates.py | """
Using dates with timeseries models
"""
import statsmodels.api as sm
import numpy as np
import pandas
# Getting started
# ---------------
data = sm.datasets.sunspots.load()
# Right now an annual date series must be datetimes at the end of the year.
from datetime import datetime
dates = sm.tsa.datetools.dates_fro... | #..TODO: should this be attached to the results instance? | # This attribute only exists if predict has been called. It holds the dates
# associated with the last call to predict. | random_line_split |
request.js | import fetch from 'dva/fetch';
const parseJSON = (response) => {
return response.json();
}
const checkStatus = (response) => {
if (response.status >= 200 && response.status < 300) {
return response;
}
| throw error;
}
/**
* Requests a URL, returning a promise.
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
* @return {object} An object containing either "data" or "err"
*/
// export default function request(url, options) {
... | const error = new Error(response.statusText);
error.response = response; | random_line_split |
request.js | import fetch from 'dva/fetch';
const parseJSON = (response) => {
return response.json();
}
const checkStatus = (response) => {
if (response.status >= 200 && response.status < 300) {
return response;
}
const error = new Error(response.statusText);
error.response = response;
throw error;
}
/**
* Requ... | {
const response = await fetch(url, options);
checkStatus(response);
const data = await response.json();
const ret = {
data,
headers: {},
};
if (response.headers.get('x-total-count')) {
ret.headers['x-total-count'] = response.headers.get('x-total-count');
}
return ret;
} | identifier_body | |
request.js | import fetch from 'dva/fetch';
const parseJSON = (response) => {
return response.json();
}
const checkStatus = (response) => {
if (response.status >= 200 && response.status < 300) {
return response;
}
const error = new Error(response.statusText);
error.response = response;
throw error;
}
/**
* Requ... |
return ret;
} | {
ret.headers['x-total-count'] = response.headers.get('x-total-count');
} | conditional_block |
request.js | import fetch from 'dva/fetch';
const parseJSON = (response) => {
return response.json();
}
const checkStatus = (response) => {
if (response.status >= 200 && response.status < 300) {
return response;
}
const error = new Error(response.statusText);
error.response = response;
throw error;
}
/**
* Requ... | (url, options) {
const response = await fetch(url, options);
checkStatus(response);
const data = await response.json();
const ret = {
data,
headers: {},
};
if (response.headers.get('x-total-count')) {
ret.headers['x-total-count'] = response.headers.get('x-total-count');
}
return ret;
} | request | identifier_name |
cxx.py | #! /usr/bin/env python
# encoding: utf-8
import sys
if sys.hexversion < 0x020400f0: from sets import Set as set
import TaskGen,Task,Utils
from Logs import debug
import ccroot
from TaskGen import feature,before,extension,after
g_cxx_flag_vars=['CXXDEPS','FRAMEWORK','FRAMEWORKPATH','STATICLIB','LIB','LIBPATH','LINKFLAGS'... | (self):
if not'cc'in self.features:
self.mappings['.c']=TaskGen.task_gen.mappings['.cxx']
self.p_flag_vars=set(self.p_flag_vars).union(g_cxx_flag_vars)
self.p_type_vars=set(self.p_type_vars).union(g_cxx_type_vars)
if not self.env['CXX_NAME']:
raise Utils.WafError("At least one compiler (g++, ..) must be selecte... | init_cxx | identifier_name |
cxx.py | #! /usr/bin/env python
# encoding: utf-8
import sys
if sys.hexversion < 0x020400f0: from sets import Set as set
import TaskGen,Task,Utils
from Logs import debug
import ccroot
from TaskGen import feature,before,extension,after
g_cxx_flag_vars=['CXXDEPS','FRAMEWORK','FRAMEWORKPATH','STATICLIB','LIB','LIBPATH','LINKFLAGS'... | if getattr(self,'obj_ext',None):
obj_ext=self.obj_ext
else:
obj_ext='_%d.o'%self.idx
task.inputs=[node]
task.outputs=[node.change_ext(obj_ext)]
try:
self.compiled_tasks.append(task)
except AttributeError:
raise Utils.WafError('Have you forgotten to set the feature "cxx" on %s?'%str(self))
return task
cxx... | self.env['DEFLINES']=["%s %s"%(x[0],Utils.trimquotes('='.join(x[1:])))for x in[y.split('=')for y in milst]]
y=self.env['CXXDEFINES_ST']
self.env['_CXXDEFFLAGS']=[y%x for x in milst]
def cxx_hook(self,node):
task=self.create_task('cxx') | random_line_split |
cxx.py | #! /usr/bin/env python
# encoding: utf-8
import sys
if sys.hexversion < 0x020400f0: from sets import Set as set
import TaskGen,Task,Utils
from Logs import debug
import ccroot
from TaskGen import feature,before,extension,after
g_cxx_flag_vars=['CXXDEPS','FRAMEWORK','FRAMEWORKPATH','STATICLIB','LIB','LIBPATH','LINKFLAGS'... |
def apply_defines_cxx(self):
self.defines=getattr(self,'defines',[])
lst=self.to_list(self.defines)+self.to_list(self.env['CXXDEFINES'])
milst=[]
for defi in lst:
if not defi in milst:
milst.append(defi)
libs=self.to_list(self.uselib)
for l in libs:
val=self.env['CXXDEFINES_'+l]
if val:milst+=self.to_li... | app('_CXXINCFLAGS',cxxpath_st%i) | conditional_block |
cxx.py | #! /usr/bin/env python
# encoding: utf-8
import sys
if sys.hexversion < 0x020400f0: from sets import Set as set
import TaskGen,Task,Utils
from Logs import debug
import ccroot
from TaskGen import feature,before,extension,after
g_cxx_flag_vars=['CXXDEPS','FRAMEWORK','FRAMEWORKPATH','STATICLIB','LIB','LIBPATH','LINKFLAGS'... |
def apply_defines_cxx(self):
self.defines=getattr(self,'defines',[])
lst=self.to_list(self.defines)+self.to_list(self.env['CXXDEFINES'])
milst=[]
for defi in lst:
if not defi in milst:
milst.append(defi)
libs=self.to_list(self.uselib)
for l in libs:
val=self.env['CXXDEFINES_'+l]
if val:milst+=self.to_li... | env=self.env
app=env.append_unique
cxxpath_st=env['CPPPATH_ST']
for i in env['INC_PATHS']:
app('_CXXINCFLAGS',cxxpath_st%i.bldpath(env))
app('_CXXINCFLAGS',cxxpath_st%i.srcpath(env))
for i in env['CPPPATH']:
app('_CXXINCFLAGS',cxxpath_st%i) | identifier_body |
test_utils.py | # -*- coding: utf-8 -*-
from datetime import datetime, timezone, timedelta
import pytest
class TestStr2Datetime(object):
@pytest.fixture
def target_func(self):
from poco.utils import str2datetime
return str2datetime
@pytest.mark.parametrize(
's,expected',
[ | ('', None),
],
)
def test_call(self, target_func, s, expected):
assert target_func(s) == expected
@pytest.mark.parametrize('non_str_value', [None, 1, object])
def test_type_error(self, target_func, non_str_value):
with pytest.raises(TypeError):
target_fun... | ('2016-01-01 00:00:00 +0900',
datetime(2016, 1, 1, 0, 0, 0, tzinfo=timezone(timedelta(0, 32400)))), | random_line_split |
test_utils.py | # -*- coding: utf-8 -*-
from datetime import datetime, timezone, timedelta
import pytest
class TestStr2Datetime(object):
@pytest.fixture
def target_func(self):
from poco.utils import str2datetime
return str2datetime
@pytest.mark.parametrize(
's,expected',
[
('... | (self, target_func, s, expected):
assert target_func(s) == expected
@pytest.mark.parametrize('non_str_value', [None, 1, object])
def test_type_error(self, target_func, non_str_value):
with pytest.raises(TypeError):
target_func(non_str_value)
class TestForceInt(object):
@pytest... | test_call | identifier_name |
test_utils.py | # -*- coding: utf-8 -*-
from datetime import datetime, timezone, timedelta
import pytest
class TestStr2Datetime(object):
@pytest.fixture
def target_func(self):
from poco.utils import str2datetime
return str2datetime
@pytest.mark.parametrize(
's,expected',
[
('... |
@pytest.mark.parametrize('non_str_value', [None, 1, object])
def test_type_error(self, target_func, non_str_value):
with pytest.raises(TypeError):
target_func(non_str_value)
class TestForceInt(object):
@pytest.fixture
def target_func(self):
from poco.utils import force_in... | assert target_func(s) == expected | identifier_body |
SutController.ts | import ActionDto from "./api/dto/ActionDto";
import AuthenticationDto from "./api/dto/AuthenticationDto";
import ProblemInfo from "./api/dto/problem/ProblemInfo";
import {OutputFormat} from "./api/dto/SutInfoDto";
import UnitsInfoDto from "./api/dto/UnitsInfoDto";
import SutHandler from "./SutHandler";
import Additiona... |
list.push(info);
});
/*
* If new targets were found, we add them even if not requested by EM
*/
ObjectiveRecorder.getTargetsSeenFirstTime().forEach(s => {
const mappedId = ObjectiveRecorder.getMappedId(s);
const info = objectives.get(s)... | {
info = info.withMappedId(id).withNoDescriptiveId();
} | conditional_block |
SutController.ts | import ActionDto from "./api/dto/ActionDto";
import AuthenticationDto from "./api/dto/AuthenticationDto";
import ProblemInfo from "./api/dto/problem/ProblemInfo";
import {OutputFormat} from "./api/dto/SutInfoDto";
import UnitsInfoDto from "./api/dto/UnitsInfoDto";
import SutHandler from "./SutHandler";
import Additiona... |
public getUnitsInfoDto(): UnitsInfoDto {
const dto = new UnitsInfoDto();
dto.unitNames = Array.from(UnitsInfoRecorder.getUnitNames());
dto.numberOfLines = UnitsInfoRecorder.getNumberOfLines();
dto.numberOfBranches = UnitsInfoRecorder.getNumberOfBranches();
return dto;
... | {
return [...ExecutionTracer.exposeAdditionalInfoList()];
} | identifier_body |
SutController.ts | import ActionDto from "./api/dto/ActionDto";
import AuthenticationDto from "./api/dto/AuthenticationDto";
import ProblemInfo from "./api/dto/problem/ProblemInfo";
import {OutputFormat} from "./api/dto/SutInfoDto";
import UnitsInfoDto from "./api/dto/UnitsInfoDto";
import SutHandler from "./SutHandler";
import Additiona... | a GET on the targets, then all those newly encountered targets
would be lost, as EM will have no way to ask for them later, unless
we explicitly say to return ALL targets
*/
ObjectiveRecorder.clearFirstTimeEncountered();
}
public getTargetInfos(ids: Set<number>... |
/*
Note: it should be fine but, if for any reason EM did not do | random_line_split |
SutController.ts | import ActionDto from "./api/dto/ActionDto";
import AuthenticationDto from "./api/dto/AuthenticationDto";
import ProblemInfo from "./api/dto/problem/ProblemInfo";
import {OutputFormat} from "./api/dto/SutInfoDto";
import UnitsInfoDto from "./api/dto/UnitsInfoDto";
import SutHandler from "./SutHandler";
import Additiona... | (ids: Set<number>): Array<TargetInfo> {
const list = new Array<TargetInfo>();
const objectives = ExecutionTracer.getInternalReferenceToObjectiveCoverage();
ids.forEach(id => {
const descriptiveId = ObjectiveRecorder.getDescriptiveId(id);
let info = objectives.get(des... | getTargetInfos | identifier_name |
sparql_functions.js | /* Function: Javascript functions for the SPARQL query page */
$(document).ready(function () {
//initiate CodeMirror syntax highlighting for the SPARQL query textarea
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: "application/x-sparql-query",
matchBrackets: ... | }); | editor.setValue(newQuery);
editor.refresh();
return false;
}); | random_line_split |
sparql_functions.js | /* Function: Javascript functions for the SPARQL query page */
$(document).ready(function () {
//initiate CodeMirror syntax highlighting for the SPARQL query textarea
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: "application/x-sparql-query",
matchBrackets: ... |
});
});
$('.prefix-button').click(function () {
var uri = $(this).attr('uri');
var prefix = $(this).text();
var string = "PREFIX " + prefix + ":\t<" + uri + ">";
//refresh CodeMirror with value
//look for the line where the prefixes end
... | {
$(this).parent('li').addClass('hidden');
} | conditional_block |
Utils.ts | ///<reference path='../../typings/node/node.d.ts'/>
///<reference path='../../typings/underscore/underscore.d.ts'/>
import _ = require('underscore');
/**
* Utility functions for business rules purposes.
*
* + String functions
* + Number functions
*/
module Utils {
/*
It represents utility for string ... |
this.priorities.push(priority);
this.listeners.push(listener);
}
remove(listener: (parameter: T) => any): void {
var index = this.listeners.indexOf(listener);
if (index >= 0) {
this.priorities.splice(index, 1);
this.listen... | {
if (this.priorities[i] < priority) {
this.priorities.splice(i, 0, priority);
this.listeners.splice(i, 0, listener);
return;
}
} | conditional_block |
Utils.ts | ///<reference path='../../typings/node/node.d.ts'/>
///<reference path='../../typings/underscore/underscore.d.ts'/>
import _ = require('underscore');
/**
* Utility functions for business rules purposes.
*
* + String functions
* + Number functions
*/
module Utils {
/*
It represents utility for string ... | for (var i = 0, l = this.priorities.length; i < l; i++) {
if (this.priorities[i] < priority) {
this.priorities.splice(i, 0, priority);
this.listeners.splice(i, 0, listener);
return;
}
}
this.p... | } | random_line_split |
Utils.ts | ///<reference path='../../typings/node/node.d.ts'/>
///<reference path='../../typings/underscore/underscore.d.ts'/>
import _ = require('underscore');
/**
* Utility functions for business rules purposes.
*
* + String functions
* + Number functions
*/
module Utils {
/*
It represents utility for string ... | {
static GetNegDigits(value:string):number {
if (value === undefined) return 0;
var digits = value.toString().split('.');
if (digits.length > 1) {
var negDigitsLength = digits[1].length;
return negDigitsLength;
}
return... | NumberFce | identifier_name |
Utils.ts | ///<reference path='../../typings/node/node.d.ts'/>
///<reference path='../../typings/underscore/underscore.d.ts'/>
import _ = require('underscore');
/**
* Utility functions for business rules purposes.
*
* + String functions
* + Number functions
*/
module Utils {
/*
It represents utility for string ... |
dispatch(parameter: T): boolean {
var indexesToRemove: number[];
var hasBeenCanceled = this.listeners.every((listener: (parameter: T) => any) => {
var result = listener(parameter);
return result !== false;
});
return hasBeenCanc... | {
var index = this.listeners.indexOf(listener);
if (index >= 0) {
this.priorities.splice(index, 1);
this.listeners.splice(index, 1);
}
} | identifier_body |
vfs_fat_ramdisk.py | import sys
import uos
try:
uos.VfsFat
except AttributeError:
print("SKIP")
sys.exit()
class RAMFS:
SEC_SIZE = 512
def __init__(self, blocks):
self.data = bytearray(blocks * self.SEC_SIZE)
|
def writeblocks(self, n, buf):
#print("writeblocks(%s, %x)" % (n, id(buf)))
for i in range(len(buf)):
self.data[n * self.SEC_SIZE + i] = buf[i]
def ioctl(self, op, arg):
#print("ioctl(%d, %r)" % (op, arg))
if op == 4: # BP_IOCTL_SEC_COUNT
return len(sel... | def readblocks(self, n, buf):
#print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
for i in range(len(buf)):
buf[i] = self.data[n * self.SEC_SIZE + i] | random_line_split |
vfs_fat_ramdisk.py | import sys
import uos
try:
uos.VfsFat
except AttributeError:
print("SKIP")
sys.exit()
class RAMFS:
SEC_SIZE = 512
def __init__(self, blocks):
self.data = bytearray(blocks * self.SEC_SIZE)
def readblocks(self, n, buf):
#print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf)))... |
def ioctl(self, op, arg):
#print("ioctl(%d, %r)" % (op, arg))
if op == 4: # BP_IOCTL_SEC_COUNT
return len(self.data) // self.SEC_SIZE
if op == 5: # BP_IOCTL_SEC_SIZE
return self.SEC_SIZE
try:
bdev = RAMFS(48)
except MemoryError:
print("SKIP")
sys.exi... | for i in range(len(buf)):
self.data[n * self.SEC_SIZE + i] = buf[i] | identifier_body |
vfs_fat_ramdisk.py | import sys
import uos
try:
uos.VfsFat
except AttributeError:
print("SKIP")
sys.exit()
class RAMFS:
SEC_SIZE = 512
def | (self, blocks):
self.data = bytearray(blocks * self.SEC_SIZE)
def readblocks(self, n, buf):
#print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
for i in range(len(buf)):
buf[i] = self.data[n * self.SEC_SIZE + i]
def writeblocks(self, n, buf):
#print("writebloc... | __init__ | identifier_name |
vfs_fat_ramdisk.py | import sys
import uos
try:
uos.VfsFat
except AttributeError:
print("SKIP")
sys.exit()
class RAMFS:
SEC_SIZE = 512
def __init__(self, blocks):
self.data = bytearray(blocks * self.SEC_SIZE)
def readblocks(self, n, buf):
#print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf)))... |
def ioctl(self, op, arg):
#print("ioctl(%d, %r)" % (op, arg))
if op == 4: # BP_IOCTL_SEC_COUNT
return len(self.data) // self.SEC_SIZE
if op == 5: # BP_IOCTL_SEC_SIZE
return self.SEC_SIZE
try:
bdev = RAMFS(48)
except MemoryError:
print("SKIP")
sys.exi... | self.data[n * self.SEC_SIZE + i] = buf[i] | conditional_block |
lib.rs | // Copyright 2017-2019 Moritz Wanzenböck.
//
// Licensed under the MIT License <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
//! A library for exchanging paths
//!
//! This library provides a simple utility to swap files and/or... |
/// Exchange the content of the object pointed to by the two paths.
///
/// This can be used to swap the content of two files, but it also works with directories.
/// **This operation may not be atomic**. If available, it will try to use the platform specific,
/// atomic operations. If they are not implemented, this w... |
platform::xch(path1, path2)
}
| identifier_body |
lib.rs | // Copyright 2017-2019 Moritz Wanzenböck.
// | // Licensed under the MIT License <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
//! A library for exchanging paths
//!
//! This library provides a simple utility to swap files and/or directory content of two paths.
//! When pos... | random_line_split | |
lib.rs | // Copyright 2017-2019 Moritz Wanzenböck.
//
// Licensed under the MIT License <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
//! A library for exchanging paths
//!
//! This library provides a simple utility to swap files and/or... | A: AsRef<path::Path>, B: AsRef<path::Path>>(path1: A, path2: B) -> error::Result<()> {
let res = platform::xch(&path1, &path2);
if let Err(error::Error::NotImplemented) = res {
non_atomic::xch(&path1, &path2)
} else {
res
}
}
| ch_non_atomic< | identifier_name |
lib.rs | // Copyright 2017-2019 Moritz Wanzenböck.
//
// Licensed under the MIT License <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
//! A library for exchanging paths
//!
//! This library provides a simple utility to swap files and/or... | }
|
res
}
| conditional_block |
__init__.py | # -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
# file: $Id$
# auth: metagriffin <mg.github@uberdev.org>
# date: 2012/04/20
# copy: (C) Copyright 2012-EOT metagriffin -- see LICENSE.txt
#-----------------------------------------------------------------------------... |
#------------------------------------------------------------------------------
# end of $Id$
#------------------------------------------------------------------------------ | # along with this program. If not, see http://www.gnu.org/licenses/.
#------------------------------------------------------------------------------
from .tracker import *
from .merger import * | random_line_split |
index.ts | /* | * Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {
BASE_FILE_EXTENSION,
BASE_FILE_NAME,
Config,
DEFAULT_LOCALE,
Localization,
Message
} from '@salesforce/salesforcedx-apex-replay-debugger/n... | * Copyright (c) 2018, salesforce.com, inc.
* All rights reserved. | random_line_split |
index.ts | /*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {
BASE_FILE_EXTENSION,
BASE_FILE_NAME,
Config,
DEFAULT_LOCALE,
Localiza... |
}
export const nls = new Localization(
loadMessageBundle(
process.env.VSCODE_NLS_CONFIG
? JSON.parse(process.env.VSCODE_NLS_CONFIG!)
: undefined
)
);
| {
return base;
} | conditional_block |
index.ts | /*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {
BASE_FILE_EXTENSION,
BASE_FILE_NAME,
Config,
DEFAULT_LOCALE,
Localiza... |
export const nls = new Localization(
loadMessageBundle(
process.env.VSCODE_NLS_CONFIG
? JSON.parse(process.env.VSCODE_NLS_CONFIG!)
: undefined
)
);
| {
function resolveFileName(locale: string): string {
return locale === DEFAULT_LOCALE
? `${BASE_FILE_NAME}.${BASE_FILE_EXTENSION}`
: `${BASE_FILE_NAME}.${locale}.${BASE_FILE_EXTENSION}`;
}
const base = new Message(
require(`./${resolveFileName(DEFAULT_LOCALE)}`).messages
);
if (config &&... | identifier_body |
index.ts | /*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {
BASE_FILE_EXTENSION,
BASE_FILE_NAME,
Config,
DEFAULT_LOCALE,
Localiza... | (config?: Config): Message {
function resolveFileName(locale: string): string {
return locale === DEFAULT_LOCALE
? `${BASE_FILE_NAME}.${BASE_FILE_EXTENSION}`
: `${BASE_FILE_NAME}.${locale}.${BASE_FILE_EXTENSION}`;
}
const base = new Message(
require(`./${resolveFileName(DEFAULT_LOCALE)}`).mes... | loadMessageBundle | identifier_name |
deprecation.py | import asyncio
import inspect
import warnings
from asgiref.sync import sync_to_async
class RemovedInDjango41Warning(DeprecationWarning):
pass
class RemovedInDjango50Warning(PendingDeprecationWarning):
pass
RemovedInNextVersionWarning = RemovedInDjango41Warning
class warn_about_renamed_method:
def _... | (self, instance):
warnings.warn(
"`%s` is deprecated, use `%s` instead." % (self.__name__, self.alternative),
self.deprecation_warning, 2
)
return super().__instancecheck__(instance)
class MiddlewareMixin:
sync_capable = True
async_capable = True
def __init... | __instancecheck__ | identifier_name |
deprecation.py | import asyncio
import inspect
import warnings
from asgiref.sync import sync_to_async
class RemovedInDjango41Warning(DeprecationWarning):
pass
class RemovedInDjango50Warning(PendingDeprecationWarning):
pass
RemovedInNextVersionWarning = RemovedInDjango41Warning
class warn_about_renamed_method:
def _... |
self.get_response = get_response
self._async_check()
super().__init__()
def _async_check(self):
"""
If get_response is a coroutine function, turns us into async mode so
a thread is not consumed during a whole request.
"""
if asyncio.iscoroutinefuncti... | raise ValueError('get_response must be provided.') | conditional_block |
deprecation.py | import asyncio
import inspect
import warnings
from asgiref.sync import sync_to_async
class RemovedInDjango41Warning(DeprecationWarning):
pass
class RemovedInDjango50Warning(PendingDeprecationWarning):
pass
RemovedInNextVersionWarning = RemovedInDjango41Warning
class warn_about_renamed_method:
def _... |
def __new__(cls, name, bases, attrs):
new_class = super().__new__(cls, name, bases, attrs)
for base in inspect.getmro(new_class):
class_name = base.__name__
for renamed_method in cls.renamed_methods:
old_method_name = renamed_method[0]
old_me... |
renamed_methods = () | random_line_split |
deprecation.py | import asyncio
import inspect
import warnings
from asgiref.sync import sync_to_async
class RemovedInDjango41Warning(DeprecationWarning):
pass
class RemovedInDjango50Warning(PendingDeprecationWarning):
pass
RemovedInNextVersionWarning = RemovedInDjango41Warning
class warn_about_renamed_method:
def _... |
async def __acall__(self, request):
"""
Async version of __call__ that is swapped in when an async request
is running.
"""
response = None
if hasattr(self, 'process_request'):
response = await sync_to_async(
self.process_request,
... | if asyncio.iscoroutinefunction(self.get_response):
return self.__acall__(request)
response = None
if hasattr(self, 'process_request'):
response = self.process_request(request)
response = response or self.get_response(request)
if hasattr(self, 'process_response'):
... | identifier_body |
events.js | // This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by | // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/... | // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful, | random_line_split |
test-api.js | import test from 'ava';
import request from 'supertest';
import { checkArrayLength, checkFail, checkSuccess } from './helpers/general';
const PORT = process.env.PORT || 3500;
const api = request(`http://0.0.0.0:${PORT}`);
test('testing for failure on invalid height', async t => {
const res = await api
.get('/no... | checkArrayLength(t, res, 400);
});
test('testing options', async t => {
const res = await api
.get('/noise/2/2?octaveCount=5&litude=0.5&persistence=0.75')
.send();
checkSuccess(t, res);
checkArrayLength(t, res, 4);
}); | checkSuccess(t, res); | random_line_split |
debugger.rs | use crate::common::Config;
use crate::runtest::ProcRes;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
pub(super) struct | {
pub commands: Vec<String>,
pub check_lines: Vec<String>,
pub breakpoint_lines: Vec<usize>,
}
impl DebuggerCommands {
pub(super) fn parse_from(
file: &Path,
config: &Config,
debugger_prefixes: &[&str],
) -> Result<Self, String> {
let directives = debugger_prefixes
... | DebuggerCommands | identifier_name |
debugger.rs | use crate::common::Config;
use crate::runtest::ProcRes;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
pub(super) struct DebuggerCommands {
pub commands: Vec<String>,
pub check_lines: Vec<String>,
pub breakpoint_lines: Vec<usize>,
}
impl DebuggerCommands {
pub(super) fn pa... |
}
| { true } | conditional_block |
debugger.rs | use crate::common::Config;
use crate::runtest::ProcRes;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
pub(super) struct DebuggerCommands {
pub commands: Vec<String>,
pub check_lines: Vec<String>,
pub breakpoint_lines: Vec<usize>,
}
impl DebuggerCommands {
pub(super) fn pa... | {
// Allow check lines to leave parts unspecified (e.g., uninitialized
// bits in the wrong case of an enum) with the notation "[...]".
let line = line.trim();
let check_line = check_line.trim();
let can_start_anywhere = check_line.starts_with("[...]");
let can_end_anywhere = check_line.ends_wi... | identifier_body | |
debugger.rs | use crate::common::Config;
use crate::runtest::ProcRes;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
pub(super) struct DebuggerCommands {
pub commands: Vec<String>,
pub check_lines: Vec<String>,
pub breakpoint_lines: Vec<usize>,
}
impl DebuggerCommands {
pub(super) fn pa... | let can_start_anywhere = check_line.starts_with("[...]");
let can_end_anywhere = check_line.ends_with("[...]");
let check_fragments: Vec<&str> =
check_line.split("[...]").filter(|frag| !frag.is_empty()).collect();
if check_fragments.is_empty() {
return true;
}
let (mut rest, fi... | // Allow check lines to leave parts unspecified (e.g., uninitialized
// bits in the wrong case of an enum) with the notation "[...]".
let line = line.trim();
let check_line = check_line.trim(); | random_line_split |
test_oti.py | #! /usr/bin/env python
from peyotl.api import OTI
from peyotl.test.support.pathmap import get_test_ot_service_domains
from peyotl.utility import get_logger
import unittest
import os
_LOG = get_logger(__name__)
@unittest.skipIf('RUN_WEB_SERVICE_TESTS' not in os.environ,
'RUN_WEB_SERVICE_TESTS is not in ... |
def testBadNodeTerms(self):
if self.oti.use_v1:
qd = {'bogus key': 'Aponogeoton ulvaceus 1 2'}
self.assertRaises(ValueError, self.oti.find_nodes, qd)
def testTreeTerms(self):
qd = {'ot:ottTaxonName': 'Aponogeton ulvaceus'}
if self.oti.use_v1:
nl = sel... | t_set = self.oti.node_search_term_set
self.assertTrue('ot:ottId' in t_set)
nl = self.oti.find_nodes(ottId=990437)
self.assertTrue(len(nl) > 0)
f = nl[0]
self.assertTrue('matched_trees' in f)
t = f['matched_trees']
self.assertTrue(len(t)... | conditional_block |
test_oti.py | #! /usr/bin/env python
from peyotl.api import OTI
from peyotl.test.support.pathmap import get_test_ot_service_domains
from peyotl.utility import get_logger
import unittest
import os
_LOG = get_logger(__name__)
@unittest.skipIf('RUN_WEB_SERVICE_TESTS' not in os.environ,
'RUN_WEB_SERVICE_TESTS is not in ... |
def testBadTreeTerms(self):
qd = {'bogus key': 'Aponogeoton ulvaceus 1 2'}
self.assertRaises(ValueError, self.oti.find_trees, qd)
if __name__ == "__main__":
unittest.main(verbosity=5)
| qd = {'ot:ottTaxonName': 'Aponogeton ulvaceus'}
if self.oti.use_v1:
nl = self.oti.find_trees(qd)
self.assertTrue(len(nl) > 0)
f = nl[0]
self.assertTrue('matched_trees' in f)
t = f['matched_trees']
self.assertTrue(len(t) > 0) | identifier_body |
test_oti.py | #! /usr/bin/env python
from peyotl.api import OTI
from peyotl.test.support.pathmap import get_test_ot_service_domains
from peyotl.utility import get_logger
import unittest
import os
_LOG = get_logger(__name__)
@unittest.skipIf('RUN_WEB_SERVICE_TESTS' not in os.environ,
'RUN_WEB_SERVICE_TESTS is not in ... | n = tr['matched_nodes']
self.assertTrue(len(n) > 0)
def testBadNodeTerms(self):
if self.oti.use_v1:
qd = {'bogus key': 'Aponogeoton ulvaceus 1 2'}
self.assertRaises(ValueError, self.oti.find_nodes, qd)
def testTreeTerms(self):
qd = {'ot:ottTaxonNam... | tr = t[0]
self.assertTrue('matched_nodes' in tr) | random_line_split |
test_oti.py | #! /usr/bin/env python
from peyotl.api import OTI
from peyotl.test.support.pathmap import get_test_ot_service_domains
from peyotl.utility import get_logger
import unittest
import os
_LOG = get_logger(__name__)
@unittest.skipIf('RUN_WEB_SERVICE_TESTS' not in os.environ,
'RUN_WEB_SERVICE_TESTS is not in ... | (self):
if self.oti.use_v1:
t_set = self.oti.node_search_term_set
self.assertTrue('ot:ottId' in t_set)
nl = self.oti.find_nodes(ottId=990437)
self.assertTrue(len(nl) > 0)
f = nl[0]
self.assertTrue('matched_trees' in f)
t = f['ma... | testNodeTerms | identifier_name |
testRedirect.js | /* @noflow */
import React from 'react';
import Redirect from '../';
import {shallow, mount} from 'enzyme';
describe('<Redirect>', () => {
var context, navigate, serverResult;
beforeEach(() => {
serverResult = {};
navigate = jest.fn();
context = {
router: {
... |
},
listen: () => () => {},
serverResult
}
};
});
it('should redirect on mount', () => {
mount(<Redirect urlName="user:profile" params={{username: 'x'}} state={{statevar: 1}} />, {context});
expect(navigate).toBeCalledWith(jasm... | {
expect(location).toEqual({pathname: "/u/x/", search: "?a=b"});
return "/u/x/?a=b";
} | identifier_body |
testRedirect.js | /* @noflow */
import React from 'react';
import Redirect from '../';
import {shallow, mount} from 'enzyme';
describe('<Redirect>', () => {
var context, navigate, serverResult;
beforeEach(() => {
serverResult = {};
navigate = jest.fn();
context = {
router: {
... | makeLocation({urlName, params}) {
expect(urlName).toEqual('user:profile');
expect(params).toEqual({username: 'x'});
return {pathname: "/u/x/", search: '?a=b'};
},
match() {
... | random_line_split | |
testRedirect.js | /* @noflow */
import React from 'react';
import Redirect from '../';
import {shallow, mount} from 'enzyme';
describe('<Redirect>', () => {
var context, navigate, serverResult;
beforeEach(() => {
serverResult = {};
navigate = jest.fn();
context = {
router: {
... | () {
return {};
}
},
navigate,
history: {
createHref(location) {
expect(location).toEqual({pathname: "/u/x/", search: "?a=b"});
return "/u/x/?a=b";
... | match | identifier_name |
defines_d.js | var searchData=
[
['off_5fabs_5fflag_5fctx',['OFF_ABS_FLAG_CTX',['../contexts_8h.html#afb7adcbadcba955cca366b5b6341fd70',1,'contexts.h']]],
['off_5fadi_5fctx',['OFF_ADI_CTX',['../contexts_8h.html#a8e3ba8d9afec533dda645294862079e1',1,'contexts.h']]],
['off_5fchroma_5fpred_5fctx',['OFF_CHROMA_PRED_CTX',['../context... | ['off_5fctx_5flast_5fflag_5fy',['OFF_CTX_LAST_FLAG_Y',['../contexts_8h.html#a0a69c0e8de32c6e4268e46a90f3c50bd',1,'contexts.h']]],
['off_5fdelta_5fqp_5fctx',['OFF_DELTA_QP_CTX',['../contexts_8h.html#a766d596ee1b605d53288a9edc33d3397',1,'contexts.h']]],
['off_5finter_5fdir_5fctx',['OFF_INTER_DIR_CTX',['../contexts_... | ['off_5fctx_5flast_5fflag_5fx',['OFF_CTX_LAST_FLAG_X',['../contexts_8h.html#a530880ef5cb04b570d1078adc9d01924',1,'contexts.h']]], | random_line_split |
unbindnode.js | define([
'matreshka_dir/core/var/core',
'matreshka_dir/core/var/sym',
'matreshka_dir/core/initmk'
], function(core, sym, initMK) {
"use strict";
var unbindNode = core.unbindNode = function(object, key, node, evt) {
if (!object || typeof object != 'object') return object;
| $nodes,
keys,
special = object[sym].special[key],
i,
indexOfDot,
path,
listenKey,
_evt;
if (key instanceof Array) {
for (i = 0; i < key.length; i++) {
evt = node;
unbindNode(object, key[i][0], key[i][1] || evt, evt);
}
return object;
}
if (type == 'string') {
keys = ... | initMK(object);
var type = typeof key, | random_line_split |
unbindnode.js | define([
'matreshka_dir/core/var/core',
'matreshka_dir/core/var/sym',
'matreshka_dir/core/initmk'
], function(core, sym, initMK) {
"use strict";
var unbindNode = core.unbindNode = function(object, key, node, evt) {
if (!object || typeof object != 'object') return object;
initMK(object);
var type = typeof ... | else if (!special) {
return object;
}
$nodes = core._getNodes(object, node);
for (i = 0; i < $nodes.length; i++) {
core.domEvents.remove({
key: key,
node: $nodes[i],
instance: object
});
special.$nodes = special.$nodes.not($nodes[i]);
(function(node) {
core._removeListener(obje... | {
// It actually ignores binder. With such a syntax you can assign definite binders to some variable and then easily delete all at once using
return unbindNode(object, key, node[0], evt);
} | conditional_block |
generate_test_mask_image.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
***************************************************************************
generate_test_mask_image.py
---------------------
Date : February 2015
Copyright : (C) 2015 by Nyall Dawson
Email : nyall dot daws... |
def imageFromPath(path):
if (path[:7] == 'http://' or path[:7] == 'file://' or path[:8] == 'https://'):
#fetch remote image
data = urllib.request.urlopen(path).read()
image = QImage()
image.loadFromData(data)
else:
image = QImage(path)
return image
def getControl... | redDiff = abs(qRed(c1) - qRed(c2))
greenDiff = abs(qGreen(c1) - qGreen(c2))
blueDiff = abs(qBlue(c1) - qBlue(c2))
alphaDiff = abs(qAlpha(c1) - qAlpha(c2))
return max(redDiff, greenDiff, blueDiff, alphaDiff) | identifier_body |
generate_test_mask_image.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
***************************************************************************
generate_test_mask_image.py
---------------------
Date : February 2015
Copyright : (C) 2015 by Nyall Dawson
Email : nyall dot daws... |
#loop through pixels in rendered image and compare
mismatch_count = 0
linebytes = max_width * 4
for y in range(max_height):
control_scanline = control_image.constScanLine(y).asstring(linebytes)
rendered_scanline = rendered_image.constScanLine(y).asstring(linebytes)
mask_scanlin... | print('Mask image does not exist, creating {}'.format(mask_image_path))
mask_image = QImage(control_image.width(), control_image.height(), QImage.Format_ARGB32)
mask_image.fill(QColor(0, 0, 0)) | conditional_block |
generate_test_mask_image.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
***************************************************************************
generate_test_mask_image.py
---------------------
Date : February 2015
Copyright : (C) 2015 by Nyall Dawson
Email : nyall dot daws... | (path):
if (path[:7] == 'http://' or path[:7] == 'file://' or path[:8] == 'https://'):
#fetch remote image
data = urllib.request.urlopen(path).read()
image = QImage()
image.loadFromData(data)
else:
image = QImage(path)
return image
def getControlImagePath(path):
... | imageFromPath | identifier_name |
generate_test_mask_image.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
***************************************************************************
generate_test_mask_image.py
---------------------
Date : February 2015
Copyright : (C) 2015 by Nyall Dawson
Email : nyall dot daws... | image.loadFromData(data)
else:
image = QImage(path)
return image
def getControlImagePath(path):
if os.path.isfile(path):
return path
#else try and find matching test image
script_folder = os.path.dirname(os.path.realpath(sys.argv[0]))
control_images_folder = os.path.jo... | if (path[:7] == 'http://' or path[:7] == 'file://' or path[:8] == 'https://'):
#fetch remote image
data = urllib.request.urlopen(path).read()
image = QImage() | random_line_split |
Domoticz.js | // Domoticz Platform Shim for HomeBridge
// Written by Joep Verhaeg (http://www.joepverhaeg.nl)
//
// Revisions:
//
// 12 June 2015 [GizMoCuz]
// - Added support for RGB lights
// - Added support for Scenes
// - Sorting device names
//
// Domoticz JSON API required
// https://www.domoticz.com/wiki/Domoticz_API/JSON_URL... |
DomoticzAccessory.prototype = {
command: function(c,value) {
this.log(this.name + " sending command " + c + " with value " + value);
if (this.IsScene == false) {
//Lights
if (c == "On" || c == "Off") {
url = "http://" + this.server + ":" + this.port + "/json.htm?type=command¶m=switchlight&idx=" + t... | {
// device info
this.IsScene = IsScene;
this.idx = idx;
this.name = name;
this.HaveDimmer = HaveDimmer;
this.MaxDimLevel = MaxDimLevel;
this.HaveRGB = HaveRGB;
this.log = log;
this.server = server;
this.port = port;
} | identifier_body |
Domoticz.js | // Domoticz Platform Shim for HomeBridge
// Written by Joep Verhaeg (http://www.joepverhaeg.nl)
//
// Revisions:
//
// 12 June 2015 [GizMoCuz]
// - Added support for RGB lights
// - Added support for Scenes
// - Sorting device names
//
// Domoticz JSON API required
// https://www.domoticz.com/wiki/Domoticz_API/JSON_URL... | (log, server, port, IsScene, idx, name, HaveDimmer, MaxDimLevel, HaveRGB) {
// device info
this.IsScene = IsScene;
this.idx = idx;
this.name = name;
this.HaveDimmer = HaveDimmer;
this.MaxDimLevel = MaxDimLevel;
this.HaveRGB = HaveRGB;
this.log = log;
this.server = server;
this.port = por... | DomoticzAccessory | identifier_name |
Domoticz.js | // Domoticz Platform Shim for HomeBridge
// Written by Joep Verhaeg (http://www.joepverhaeg.nl)
//
// Revisions:
//
// 12 June 2015 [GizMoCuz]
// - Added support for RGB lights
// - Added support for Scenes
// - Sorting device names
//
// Domoticz JSON API required
// https://www.domoticz.com/wiki/Domoticz_API/JSON_URL... |
else if (value != undefined) {
this.log(this.name + " Unhandled Scene command! cmd=" + c + ", value=" + value);
}
}
var that = this;
request.put({ url: url }, function(err, response) {
if (err) {
that.log("There was a problem sending command " + c + " to" + that.name);
that.log(url);
}... | {
url = "http://" + this.server + ":" + this.port + "/json.htm?type=command¶m=switchscene&idx=" + this.idx + "&switchcmd=" + c;
} | conditional_block |
Domoticz.js | // Domoticz Platform Shim for HomeBridge
// Written by Joep Verhaeg (http://www.joepverhaeg.nl)
//
// Revisions:
//
// 12 June 2015 [GizMoCuz]
// - Added support for RGB lights
// - Added support for Scenes
// - Sorting device names
//
// Domoticz JSON API required
// https://www.domoticz.com/wiki/Domoticz_API/JSON_URL... | designedMaxLength: 255
},{
cType: types.SERIAL_NUMBER_CTYPE,
onUpdate: null,
perms: ["pr"],
format: "string",
initialValue: "A1S2NASF88EW",
supportEvents: false,
supportBonjour: false,
manfDescription: "SN",
designedMaxLength: 255
... | manfDescription: "Model", | random_line_split |
readSequenceElementImplicit.js | /**
* Internal helper functions for parsing DICOM elements
*/
var dicomParser = (function (dicomParser)
{
"use strict";
if(dicomParser === undefined)
{
dicomParser = {};
}
function readDicomDataSetImplicitUndefinedLength(byteStream)
{
var elements = {};
while(byteSt... |
// eof encountered - log a warning and return what we have for the element
byteStream.warnings.push('eof encountered before finding sequence item delimiter in sequence item of undefined length');
return new dicomParser.DataSet(byteStream.byteArrayParser, byteStream.byteArray, elements);
}
... | {
var element = dicomParser.readDicomElementImplicit(byteStream);
elements[element.tag] = element;
// we hit an item delimiter tag, return the current offset to mark
// the end of this sequence item
if(element.tag === 'xfffee00d')
{
... | conditional_block |
readSequenceElementImplicit.js | /**
* Internal helper functions for parsing DICOM elements
*/
var dicomParser = (function (dicomParser)
{
"use strict";
if(dicomParser === undefined)
{
dicomParser = {};
}
function readDicomDataSetImplicitUndefinedLength(byteStream)
{
var elements = {};
while(byteSt... | (byteStream, element)
{
while(byteStream.position < byteStream.byteArray.length)
{
// end reading this sequence if the next tag is the sequence delimitation item
var nextTag = dicomParser.readTag(byteStream);
byteStream.seek(-4);
if (nextTag === 'xfffee0dd') {... | readSQElementUndefinedLengthImplicit | identifier_name |
readSequenceElementImplicit.js | /**
* Internal helper functions for parsing DICOM elements
*/
var dicomParser = (function (dicomParser)
{
"use strict";
if(dicomParser === undefined)
{
dicomParser = {};
}
function readDicomDataSetImplicitUndefinedLength(byteStream)
{
var elements = {};
while(byteSt... |
function readSQElementUndefinedLengthImplicit(byteStream, element)
{
while(byteStream.position < byteStream.byteArray.length)
{
// end reading this sequence if the next tag is the sequence delimitation item
var nextTag = dicomParser.readTag(byteStream);
byteStream... | {
var item = dicomParser.readSequenceItem(byteStream);
if(item.length === 4294967295)
{
item.hadUndefinedLength = true;
item.dataSet = readDicomDataSetImplicitUndefinedLength(byteStream);
item.length = byteStream.position - item.dataOffset;
}
... | identifier_body |
readSequenceElementImplicit.js | /**
* Internal helper functions for parsing DICOM elements
*/
var dicomParser = (function (dicomParser)
{
"use strict";
if(dicomParser === undefined)
{
dicomParser = {};
}
function readDicomDataSetImplicitUndefinedLength(byteStream)
{
var elements = {};
while(byteSt... | dicomParser.parseDicomDataSetImplicit(item.dataSet, byteStream, byteStream.position + item.length);
}
return item;
}
function readSQElementUndefinedLengthImplicit(byteStream, element)
{
while(byteStream.position < byteStream.byteArray.length)
{
// end r... | {
item.dataSet = new dicomParser.DataSet(byteStream.byteArrayParser, byteStream.byteArray, {}); | random_line_split |
url.js | import { useMemo, useCallback } from "react";
import isString from "lodash/isString";
import queryString from "query-string";
import { useHistory } from "react-router-dom";
import useQueryParams from "../useQueryParams";
export function useParsedTags() {
const queryParams = useQueryParams();
const tags = useMemo... |
return value;
}
| {
return [value];
} | conditional_block |
url.js | import { useMemo, useCallback } from "react";
import isString from "lodash/isString";
import queryString from "query-string";
import { useHistory } from "react-router-dom";
import useQueryParams from "../useQueryParams";
export function useParsedTags() {
const queryParams = useQueryParams();
const tags = useMemo... | history.push({
search: queryString.stringify({
tag: tags,
excludedTag: excludedTags
})
});
},
[history]
);
}
function toArray(value) {
if (!value) {
return [];
}
if (isString(value)) {
return [value];
}
return value;
} | const history = useHistory();
return useCallback(
({ tags, excludedTags }) => { | random_line_split |
url.js | import { useMemo, useCallback } from "react";
import isString from "lodash/isString";
import queryString from "query-string";
import { useHistory } from "react-router-dom";
import useQueryParams from "../useQueryParams";
export function useParsedTags() {
const queryParams = useQueryParams();
const tags = useMemo... | () {
const history = useHistory();
return useCallback(
({ tags, excludedTags }) => {
history.push({
search: queryString.stringify({
tag: tags,
excludedTag: excludedTags
})
});
},
[history]
);
}
function toArray(value) {
if (!value) {
return [];
... | useNavigateToTags | identifier_name |
url.js | import { useMemo, useCallback } from "react";
import isString from "lodash/isString";
import queryString from "query-string";
import { useHistory } from "react-router-dom";
import useQueryParams from "../useQueryParams";
export function useParsedTags() |
export function useNavigateToTags() {
const history = useHistory();
return useCallback(
({ tags, excludedTags }) => {
history.push({
search: queryString.stringify({
tag: tags,
excludedTag: excludedTags
})
});
},
[history]
);
}
function toArray(value) ... | {
const queryParams = useQueryParams();
const tags = useMemo(() => toArray(queryParams.tag), [queryParams.tag]);
const excludedTags = useMemo(() => toArray(queryParams.excludedTag), [queryParams.excludedTag]);
return useMemo(() => {
return {
tags,
excludedTags
};
}, [tags, excludedTags])... | identifier_body |
tree.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/. */
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency
//! between layout and style.
use at... |
fn parent_element(&self) -> Option<Self>;
/// The parent of a given pseudo-element, after matching a pseudo-element
/// selector.
///
/// This is guaranteed to be called in a pseudo-element.
fn pseudo_element_originating_element(&self) -> Option<Self> {
self.parent_element()
}
... |
pub trait Element: Sized {
type Impl: SelectorImpl; | random_line_split |
tree.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/. */
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency
//! between layout and style.
use at... |
/// Skips non-element nodes
fn first_child_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn last_child_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn prev_sibling_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn next_sibling_element(&self)... | {
self.parent_element()
} | identifier_body |
tree.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/. */
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency
//! between layout and style.
use at... | (&self) -> Option<Self> {
self.parent_element()
}
/// Skips non-element nodes
fn first_child_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn last_child_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn prev_sibling_element(&self) -> Option<Self>;
/... | pseudo_element_originating_element | identifier_name |
Sentence_Terminal-code-points.js | // All code points with the `Sentence_Terminal` property as per Unicode v9.0.0:
[
0x21,
0x2E,
0x3F,
0x589,
0x61F,
0x6D4,
0x700,
0x701,
0x702,
0x7F9,
0x964,
0x965,
0x104A,
0x104B,
0x1362,
0x1367,
0x1368,
0x166E,
0x1735,
0x1736,
0x1803,
0x1809,
0x1944,
0x1945,
0x1AA8,
0x1AA9,
0x1AAA,
0x1AAB,
... | 0x1C7E,
0x1C7F,
0x203C,
0x203D,
0x2047,
0x2048,
0x2049,
0x2E2E,
0x2E3C,
0x3002,
0xA4FF,
0xA60E,
0xA60F,
0xA6F3,
0xA6F7,
0xA876,
0xA877,
0xA8CE,
0xA8CF,
0xA92F,
0xA9C8,
0xA9C9,
0xAA5D,
0xAA5E,
0xAA5F,
0xAAF0,
0xAAF1,
0xABEB,
0xFE52,
0xFE56,
0xFE57,
0xFF01,
0xFF0E,
0xFF1F,
0xFF61,
0x10... | 0x1C3C, | random_line_split |
extHostDiagnostics.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
};
return result;
}
forEach(callback: (collection: DiagnosticCollection) => any): void {
this._collections.forEach(callback);
}
}
| {
_collections.splice(idx, 1);
} | conditional_block |
extHostDiagnostics.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
has(uri: URI): boolean {
this._checkDisposed();
return Array.isArray(this._data[uri.toString()]);
}
private _checkDisposed() {
if (this._isDisposed) {
throw new Error('illegal state - object is disposed');
}
}
private static _toMarkerData(diagnostic: vscode.Diagnostic): IMarkerData {
let range ... | if (Array.isArray(result)) {
return <vscode.Diagnostic[]>Object.freeze(result.slice(0));
} | random_line_split |
extHostDiagnostics.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
dispose() {
super.dispose();
let idx = _collections.indexOf(this);
if (idx !== -1) {
_collections.splice(idx, 1);
}
}
};
return result;
}
forEach(callback: (collection: DiagnosticCollection) => any): void {
this._collections.forEach(callback);
}
}
| {
super(name, _proxy);
_collections.push(this);
} | identifier_body |
extHostDiagnostics.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (first: vscode.Uri | [vscode.Uri, vscode.Diagnostic[]][], diagnostics?: vscode.Diagnostic[]) {
if (!first) {
// this set-call is a clear-call
this.clear();
return;
}
// the actual implementation for #set
this._checkDisposed();
let toSync: vscode.Uri[];
if (first instanceof URI) {
if (!diagn... | set | identifier_name |
game_container.py | from pygame.locals import *
from pypogs import player_area
from pypogs import render
class GameContainer(object):
def __init__(self, world, dimensions):
self._player_areas = []
self._world = world
self._dimensions = dimensions
self._is_online = False
def render(self, screen)... |
if self._is_online:
self._send_input_to_server(event)
else:
for area in self._player_areas:
area.handle_event(event)
def _handle_key_event(self, key):
if key == K_ESCAPE:
self._world.switch_to_menu()
def _handle_joy_button_down_even... | self._handle_joy_button_down_event(event.button) | conditional_block |
game_container.py | from pygame.locals import *
from pypogs import player_area
from pypogs import render
class GameContainer(object):
def __init__(self, world, dimensions):
self._player_areas = []
self._world = world
self._dimensions = dimensions
self._is_online = False
def render(self, screen)... |
for area in self._player_areas:
area.render(screen)
def tick(self):
if not self._world.in_game():
return
if self._is_online:
self._check_for_server_update()
else:
for area in self._player_areas:
area.tick()
def h... | if not self._world.in_game():
return | random_line_split |
game_container.py | from pygame.locals import *
from pypogs import player_area
from pypogs import render
class GameContainer(object):
def __init__(self, world, dimensions):
self._player_areas = []
self._world = world
self._dimensions = dimensions
self._is_online = False
def render(self, screen)... | (self):
if not self._world.in_game():
return
if self._is_online:
self._check_for_server_update()
else:
for area in self._player_areas:
area.tick()
def handle_event(self, event):
if not self._world.in_game():
return
... | tick | identifier_name |
game_container.py | from pygame.locals import *
from pypogs import player_area
from pypogs import render
class GameContainer(object):
def __init__(self, world, dimensions):
self._player_areas = []
self._world = world
self._dimensions = dimensions
self._is_online = False
def render(self, screen)... |
def _check_for_server_update(self):
pass
def _send_input_to_server(self):
pass
| del self._player_areas[:]
posn = render.GamePositions(self._dimensions[0], self._dimensions[1],
player_count)
for player_id in range(player_count):
new_area = player_area.PlayerArea(posn, player_id)
self._player_areas.append(new_area) | identifier_body |
index-mkt.js | $(function() {
// iniciarlizar sidemenu
$(".button-collapse").sideNav();
$('.scrollspy').scrollSpy();
$('.modal-trigger').leanModal({
dismissible: true, // Modal can be dismissed by clicking outside of the modal
opacity: .5, // Opacity of modal background
in_duration: 300, // Transition in duratio... | itemsDesktopSmall : [901,3]
});
// $('select').material_select();
// $(".button-collapse").sideNav();
// // Focus any form on the first element
// $('form.fb').find('input:text').first().focus();
// $('form.fb').find('input:text').first().keypress(function () {
// $(this).siblings('l... | navigation: false,
stopOnHover: true,
autoplay : true,
responsive: true,
itemsDesktop : [1199,], | random_line_split |
websocket.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
use dom::bind... | // Step 4.
let protocols = match protocols {
Some(StringOrStringSequence::String(string)) => vec![String::from(string)],
Some(StringOrStringSequence::StringSequence(sequence)) => {
sequence.into_iter().map(String::from).collect()
},
_ => Ve... |
if BLOCKED_PORTS_LIST.iter().any(|&p| p == port) {
return Err(Error::Security);
}
| random_line_split |
websocket.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
use dom::bind... | {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
// list of bad ports according to
// https://fetch.spec.whatwg.org/#port-blocking
const BLOCKED_PORTS_LIST: &'static [u16] = &[
1, // tcpmux
7, // echo
9, // discard
11, // systat
13, // daytime
15, // netsta... | WebSocketRequestState | identifier_name |
websocket.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
use dom::bind... |
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send_(&self, blob: &Blob) -> ErrorResult {
/* As per https://html.spec.whatwg.org/multipage/#websocket
the buffered amount needs to be clamped to u32, even though Blob.Size() is u64
If the buffer limit is reached i... | {
let data_byte_len = data.0.as_bytes().len() as u64;
let send_data = try!(self.send_impl(data_byte_len));
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomActi... | identifier_body |
serverUtil.tsx | import * as ReactDOMServer from "react-dom/server"
import * as lodash from "lodash"
import urljoin from "url-join"
import { ADMIN_BASE_URL } from "../settings/serverSettings"
import { JsonError } from "../clientUtils/owidTypes"
// Fail-fast integer conversion, for e.g. ids in url params | export const expectInt = (value: any): number => {
const num = parseInt(value)
if (isNaN(num))
throw new JsonError(`Expected integer value, not '${value}'`, 400)
return num
}
export const tryInt = (value: any, defaultNum: number): number => {
const num = parseInt(value)
if (isNaN(num)) retu... | random_line_split | |
Pattern.ts | import { Loop, LoopOptions } from "./Loop";
import { PatternGenerator, PatternName } from "./PatternGenerator";
import { ToneEventCallback } from "./ToneEvent";
import { optionsFromArguments } from "../core/util/Defaults";
import { Seconds } from "../core/type/Units";
import { noOp } from "../core/util/Interface";
exp... | (time: Seconds): void {
const value = this._pattern.next() as IteratorResult<ValueType>;
this._value = value.value;
this.callback(time, this._value);
}
/**
* The array of events.
*/
get values(): ValueType[] {
return this._values;
}
set values(val) {
this._values = val;
// reset the pattern
this... | _tick | identifier_name |
Pattern.ts | import { Loop, LoopOptions } from "./Loop";
import { PatternGenerator, PatternName } from "./PatternGenerator";
import { ToneEventCallback } from "./ToneEvent";
import { optionsFromArguments } from "../core/util/Defaults";
import { Seconds } from "../core/type/Units";
import { noOp } from "../core/util/Interface";
exp... | this._pattern = PatternGenerator(this._values, this._type);
}
} | get pattern(): PatternName {
return this._type;
}
set pattern(pattern) {
this._type = pattern; | random_line_split |
Pattern.ts | import { Loop, LoopOptions } from "./Loop";
import { PatternGenerator, PatternName } from "./PatternGenerator";
import { ToneEventCallback } from "./ToneEvent";
import { optionsFromArguments } from "../core/util/Defaults";
import { Seconds } from "../core/type/Units";
import { noOp } from "../core/util/Interface";
exp... |
/**
* The array of events.
*/
get values(): ValueType[] {
return this._values;
}
set values(val) {
this._values = val;
// reset the pattern
this.pattern = this._type;
}
/**
* The current value of the pattern.
*/
get value(): ValueType | undefined {
return this._value;
}
/**
* The patter... | {
const value = this._pattern.next() as IteratorResult<ValueType>;
this._value = value.value;
this.callback(time, this._value);
} | identifier_body |
Deploy.ts | import normalizable from 'junction-normalizr-decorator';
import {Entity, Schema, SchemaTypes, Timestampable} from 'junction-orm/lib/Entity';
import Stack from '../stack/Stack';
import User from '../user/User';
@normalizable()
class | implements Entity, Timestampable {
static schema: Schema = {
type: SchemaTypes.ENTITY,
timestampable: true,
props: {
branch: {},
user: {
type: User
},
stack: {
type: Stack
},
logFile: {},
hosts: {
type: 'json'
}
}
};
id?: n... | Deploy | identifier_name |
Deploy.ts | import normalizable from 'junction-normalizr-decorator';
import {Entity, Schema, SchemaTypes, Timestampable} from 'junction-orm/lib/Entity';
import Stack from '../stack/Stack';
import User from '../user/User';
@normalizable()
class Deploy implements Entity, Timestampable {
static schema: Schema = {
type: Schema... | }
}
export default Deploy; | this.branch = branch;
this.user = user;
this.stack = stack; | random_line_split |
server.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var index_1 = require("./index");
var express = require("express");
var jwt = require("jsonwebtoken");
var cors = require("cors");
var app = express();
app.use(cors());
var mountpoint = '/';
var prefix = '';
var options = {};
if (!process.env.... |
else if (process.env.MODE === 'user') {
if (!process.env.SECRET) {
throw Error('no secret provided (by process env)');
}
console.log(jwt.sign({ prefix: '' }, process.env.SECRET));
}
app.use(mountpoint, index_1.default(videofolder, options));
app.listen(process.env.PORT);
| {
console.log(videofolder);
} | conditional_block |
server.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var index_1 = require("./index");
var express = require("express");
var jwt = require("jsonwebtoken");
var cors = require("cors");
var app = express();
app.use(cors());
var mountpoint = '/';
var prefix = '';
var options = {};
if (!process.env.... | if (process.env.MODE === 'user' && process.env.SECRET) {
options.mode = { type: 'users', secret: process.env.SECRET, ignoreExpiration: true };
}
options.serverUri = { path: videofolder, uri: process.env.SERVERURI + mountpoint + 'videolibrary/' };
if (!process.env.MODE) {
console.log(videofolder);
}
else if (pro... | process.env.PORT = parseInt(process.env.PORT);
if (process.env.CONVERSIONDEST) {
options.conversion = { dest: process.env.CONVERSIONDEST };
} | random_line_split |
account_setup.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Post-installation configuration helpers
# Copyright (C) 2015 OpusVL (<http://opusvl.com/>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General P... |
def unconfigured_company_ids(cr, registry, uid, context=None):
"""Return list of ids of companies without a chart of accounts.
"""
account_installer = registry['account.installer']
return account_installer.get_unconfigured_cmp(cr, uid, context=context)
def setup_chart_of_accounts(cr, registry, uid, c... | setup_chart_of_accounts(cr, registry, uid,
company_id=company.id,
chart_template_id=chart_template.id,
code_digits=code_digits,
context=context,
)
today = date.today()
fy_name = today.strftime('%Y')
fy_code = 'FY' + fy_name
account... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.