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 |
|---|---|---|---|---|
segmented-bar.d.ts | /**
* Contains the SegmentedBar class, which represents a SegmentedBar component.
*/
declare module "ui/segmented-bar" {
import view = require("ui/core/view");
import dependencyObservable = require("ui/core/dependency-observable");
import color = require("color");
import bindable = require("ui/core/bi... | extends bindable.Bindable {
/**
* Gets or sets the title of the SegmentedBarItem.
*/
public title: string;
}
/**
* Defines the data for the SegmentedBar.selectedIndexChanged event.
*/
export interface SelectedIndexChangedEventData extends observable.EventData {
... | SegmentedBarItem | identifier_name |
ripgrepTextSearch.ts |
// TODO@roblou move to SearchService
const MAX_TEXT_RESULTS = 10000;
export class RipgrepTextSearchEngine {
private isDone = false;
private rgProc: cp.ChildProcess;
private ripgrepParser: RipgrepParser;
constructor(private outputChannel: vscode.OutputChannel) { }
cancel() {
this.isDone = true;
if (this.r... | // If vscode-ripgrep is in an .asar file, then the binary is unpacked.
const rgDiskPath = rgPath.replace(/\bnode_modules\.asar\b/, 'node_modules.asar.unpacked'); | random_line_split | |
ripgrepTextSearch.ts | (`rg ${escapedArgs}\n - cwd: ${cwd}`);
this.rgProc = cp.spawn(rgDiskPath, rgArgs, { cwd });
this.rgProc.on('error', e => {
console.error(e);
this.outputChannel.append('Error: ' + (e && e.message));
reject(e);
});
let gotResult = false;
this.ripgrepParser = new RipgrepParser(MAX_TEXT_RESULTS... | getRgArgs | identifier_name | |
ripgrepTextSearch.ts | .match(/^-/) ? arg : `'${arg}'`)
.join(' ');
this.outputChannel.appendLine(`rg ${escapedArgs}\n - cwd: ${cwd}`);
this.rgProc = cp.spawn(rgDiskPath, rgArgs, { cwd });
this.rgProc.on('error', e => {
console.error(e);
this.outputChannel.append('Error: ' + (e && e.message));
reject(e);
});
... |
// Line is a result - add to collected results for the current file path
this.handleMatchLine(outputLine, lineNum, matchText);
} else if (r = outputLine.match(RipgrepParser.FILE_REGEX)) {
this.currentFile = r[1];
} else {
// Line is empty (or malformed)
}
}
}
private handleMatchLine(outp... | {
matchText += RipgrepParser.MATCH_END_MARKER;
} | conditional_block |
ripgrepTextSearch.ts | [0m';
private currentFile: string;
private remainder: string;
private isDone: boolean;
private stringDecoder: NodeStringDecoder;
private numResults = 0;
constructor(private maxResults: number, private rootFolder: string) {
super();
this.stringDecoder = new StringDecoder();
}
public cancel(): void {
th... | {
return value.replace(/[\-\\\{\}\*\+\?\|\^\$\.\[\]\(\)\#]/g, '\\$&');
} | identifier_body | |
write_test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use super::*;
use crate::test_helpers::{
arb_hash_batch, arb_list_of_hash_batches, test_append_empty_impl, test_append_many_impl,
MockHashStore, TestAccumulator,
};
use diem_crypto::hash::ACCUMULATOR_PLACEHOLDER_HASH;
use diem_t... | fn test_append_many(batches in arb_list_of_hash_batches(10, 10)) {
test_append_many_impl(batches);
}
#[test]
fn test_append_empty(leaves in arb_hash_batch(100)) {
test_append_empty_impl(leaves)
}
} |
#[test] | random_line_split |
write_test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use super::*;
use crate::test_helpers::{
arb_hash_batch, arb_list_of_hash_batches, test_append_empty_impl, test_append_many_impl,
MockHashStore, TestAccumulator,
};
use diem_crypto::hash::ACCUMULATOR_PLACEHOLDER_HASH;
use diem_t... |
#[test]
fn test_append_one() {
let mut store = MockHashStore::new();
store.verify(&[]).unwrap();
let mut leaves = Vec::new();
for v in 0..100 {
let hash = HashValue::random();
let (root_hash, writes) =
TestAccumulator::append(&store, leaves.len() as LeafCount, &[hash]).unw... | {
let store = MockHashStore::new();
assert_eq!(
TestAccumulator::append(&store, 0, &[]).unwrap(),
(*ACCUMULATOR_PLACEHOLDER_HASH, Vec::new())
);
} | identifier_body |
write_test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use super::*;
use crate::test_helpers::{
arb_hash_batch, arb_list_of_hash_batches, test_append_empty_impl, test_append_many_impl,
MockHashStore, TestAccumulator,
};
use diem_crypto::hash::ACCUMULATOR_PLACEHOLDER_HASH;
use diem_t... | () {
let mut store = MockHashStore::new();
store.verify(&[]).unwrap();
let mut leaves = Vec::new();
for v in 0..100 {
let hash = HashValue::random();
let (root_hash, writes) =
TestAccumulator::append(&store, leaves.len() as LeafCount, &[hash]).unwrap();
store.put_man... | test_append_one | identifier_name |
ResolutionRequest.js | ModuleName),
);
return cacheResult(result);
}
return cacheResult(this._resolveNodeDependency(fromModule, toModuleName));
}
resolveModuleDependencies(
module: TModule,
dependencyNames: $ReadOnlyArray<string>,
): [$ReadOnlyArray<string>, $ReadOnlyArray<TModule>] {
const dependencie... |
}
}
return result;
}
_resolveHasteDependency(fromModule: TModule, toModuleName: string): TModule {
toModuleName = normalizePath(toModuleName);
const pck = fromModule.getPackage();
let realModuleName;
if (pck) {
/* $FlowFixMe: redirectRequire can actually return `false` for
... | {
throw error;
} | identifier_body |
ResolutionRequest.js | ModuleName),
);
return cacheResult(result);
}
return cacheResult(this._resolveNodeDependency(fromModule, toModuleName));
}
resolveModuleDependencies(
module: TModule,
dependencyNames: $ReadOnlyArray<string>,
): [$ReadOnlyArray<string>, $ReadOnlyArray<TModule>] {
const dependencie... | onProgress(finishedModules, preprocessedModuleCount);
}
});
}
const resolveDependencies = (module: TModule) =>
Promise.resolve().then(() => {
const cached = module.readCached(transformOptions);
if (cached.result != null) {
return this.resolveModuleDepende... | if (count + 1 <= preprocessedModuleCount) {
return;
}
preprocessedModuleCount = count + 1;
if (onProgress != null) { | random_line_split |
ResolutionRequest.js | redirectRequire(
fromModule,
potentialModulePath,
);
if (realModuleName === false) {
return this._loadAsFile(
ResolutionRequest.EMPTY_MODULE,
fromModule,
toModuleName,
);
}
return tryResolveSync(
() => this._loadAsFile(realModuleName, fromModule, to... | constructor | identifier_name | |
ResolutionRequest.js | ModuleName),
);
return cacheResult(result);
}
return cacheResult(this._resolveNodeDependency(fromModule, toModuleName));
}
resolveModuleDependencies(
module: TModule,
dependencyNames: $ReadOnlyArray<string>,
): [$ReadOnlyArray<string>, $ReadOnlyArray<TModule>] {
const dependencie... |
preprocessedModuleCount = count + 1;
if (onProgress != null) {
onProgress(finishedModules, preprocessedModuleCount);
}
});
}
const resolveDependencies = (module: TModule) =>
Promise.resolve().then(() => {
const cached = module.readCached(transformOptions);... | {
return;
} | conditional_block |
it.py | : **%s**': 'Numero di entità: **%s**',
'About': 'About',
'Access Control': 'Controllo Accessi',
'Add': 'Aggiungi',
'Administrative Interface': 'Interfaccia Amministrativa',
'Administrative interface': 'Interfaccia amministrativa',
'Ajax Recipes': 'Ajax Recipes',
'An error occured, please %s the page': "E' stato rilevat... | 'contains': 'contiene',
'Controller': 'Controller',
'Copyright': 'Copyright',
'Created By': 'Creato Da',
'Created On': 'Creato Il',
'CSV': 'CSV',
'CSV (hidden cols)': 'CSV (hidden cols)',
'Current request': 'Richiesta (request) corrente',
'Current response': 'Risposta (response) corrente',
'Current session': 'Sessione ... | 'Cognome': 'Cognome',
'Community': 'Community',
'Components and Plugins': 'Componenti and Plugin', | random_line_split |
action_reposync.py | if env[k] is not None:
os.putenv(k,env[k])
if name is not None and repo.name != name:
# invoked to sync only a specific repo, this is not the one
continue
elif name is None and not repo.keep_updated:
# invoked t... | """
Syncs the current repo configuration file with the filesystem.
"""
self.logger.info("run, reposync, run!")
try:
self.tries = int(self.tries)
except:
utils.die(self.logger,"retry value must be an integer")
self.verbose = v... | identifier_body | |
action_reposync.py | /repomd.xml" % (dirname)):
if not HAS_YUM:
utils.die(self.logger,"yum is required to use this feature")
rmd = yum.repoMDObject.RepoMD('', "%s/.origin/repomd.xml" % (dirname))
if rmd.repoData.has_key("group"):
groupmdfile = rmd.getDa... | # now regardless of whether we're doing yumdownloader or reposync | random_line_split | |
action_reposync.py | if report_failure:
utils.die(self.logger,"overall reposync failed, at least one repo failed to synchronize")
return True
# ==================================================================================
def | (self, repo):
"""
Conditionally sync a repo, based on type.
"""
if repo.breed == "rhn":
return self.rhn_sync(repo)
elif repo.breed == "yum":
return self.yum_sync(repo)
#elif repo.breed == "apt":
# return self.apt_sync(repo)
... | sync | identifier_name |
action_reposync.py | if report_failure:
utils.die(self.logger,"overall reposync failed, at least one repo failed to synchronize")
return True
# ==================================================================================
def sync(self, repo):
"""
Conditionally sync a repo, based ... |
if repo.rpm_list != "" and repo.rpm_list != []:
self.logger.warning("--rpm-list is not supported for rsync'd repositories")
# FIXME: don't hardcode
dest_path = os.path.join("/var/www/cobbler/repo_mirror", repo.name)
spacer = ""
if not repo.mirror.startswith("rsync... | utils.die(self.logger,"rsync:// urls must be mirrored locally, yum cannot access them directly") | conditional_block |
env.rs | use std::ops::{Deref, DerefMut};
use std::collections::HashMap;
use std::iter::FromIterator;
use std::cell::RefCell;
use rand::IsaacRng;
use rand::distributions::{Range, Sample};
use common_util::IntType;
use syntax_tree::*;
use eval::types::*;
use eval::eval_functions::eval_expr;
use error::*;
/// The Roller runtim... | (&self, id: Ident) -> NameInfo {
if let Some(_) = self.var_ns.get(&id) {
NameInfo::Var
}
else if let Some(_) = self.fun_ns.get(&id) {
NameInfo::Fun
}
else {
NameInfo::Empty
}
}
/// Returns the value of the variable with the given identifier.
pub fn get_var<'a>(&'a self, id: &Ident) -> ParseResu... | get_name_info | identifier_name |
env.rs | use std::ops::{Deref, DerefMut};
use std::collections::HashMap;
use std::iter::FromIterator;
use std::cell::RefCell;
use rand::IsaacRng;
use rand::distributions::{Range, Sample};
use common_util::IntType;
use syntax_tree::*;
use eval::types::*;
use eval::eval_functions::eval_expr;
use error::*;
/// The Roller runtim... | ,
None => Err(RollerErr::EvalError(EvalErr::NoFunFound(id.to_owned() ))),
}
}
fn ns_from_args(names: &Vec<Ident>, args: Vec<Value>) -> ParseResult<HashMap<Ident, Value>>
{
// chech whether the lengths match
if names.len() != args.len() {
return Err(RollerErr::EvalError(
EvalErr::WrongNumParams{expec... | {
if self.call_stack.borrow().deref().len() > self.max_call_depth {
return Err(RollerErr::EvalError(EvalErr::ReachedMaxCallDepth));
}
// the fumction's local namespace
let local_ns = try!(Self::ns_from_args(&fun.params, args));
// add the function's local namespace
self.call_stack.borrow_m... | conditional_block |
env.rs | use std::ops::{Deref, DerefMut};
use std::collections::HashMap;
use std::iter::FromIterator;
use std::cell::RefCell;
use rand::IsaacRng;
use rand::distributions::{Range, Sample};
use common_util::IntType;
use syntax_tree::*;
use eval::types::*;
use eval::eval_functions::eval_expr;
use error::*;
/// The Roller runtim... | /// Returns the value of the variable with the given identifier.
pub fn get_var<'a>(&'a self, id: &Ident) -> ParseResult<Value> {
// check the last element of the call stack
if let Some(ref hm) = self.call_stack.borrow().deref().last() {
if let Some(ref val) = hm.get(id) {
// check if we found the variable... | random_line_split | |
test_nested.py | from pylastica.query import Query
from pylastica.aggregation.min import Min
from pylastica.aggregation.nested import Nested
from pylastica.doc_type.mapping import Mapping
from pylastica.document import Document
from tests.base import Base
__author__ = 'Joe Linn'
import unittest
| mapping.set_properties({
"resellers": {
"type": "nested",
"properties": {
"name": {"type": "string"},
"price": {"type": "double"}
}
}
})
doc_type = self._index.get_doc_type("test")
... | class NestedTest(unittest.TestCase, Base):
def setUp(self):
super(NestedTest, self).setUp()
self._index = self._create_index("test_aggregation_nested")
mapping = Mapping() | random_line_split |
test_nested.py | from pylastica.query import Query
from pylastica.aggregation.min import Min
from pylastica.aggregation.nested import Nested
from pylastica.doc_type.mapping import Mapping
from pylastica.document import Document
from tests.base import Base
__author__ = 'Joe Linn'
import unittest
class NestedTest(unittest.TestCase, B... | (self):
super(NestedTest, self).tearDown()
self._index.delete()
def test_nested_aggregation(self):
agg = Nested("resellers", "resellers")
agg.add_aggregation(Min("min_price").set_field("price"))
query = Query()
query.add_aggregation(agg)
results = self._inde... | tearDown | identifier_name |
test_nested.py | from pylastica.query import Query
from pylastica.aggregation.min import Min
from pylastica.aggregation.nested import Nested
from pylastica.doc_type.mapping import Mapping
from pylastica.document import Document
from tests.base import Base
__author__ = 'Joe Linn'
import unittest
class NestedTest(unittest.TestCase, B... | unittest.main() | conditional_block | |
test_nested.py | from pylastica.query import Query
from pylastica.aggregation.min import Min
from pylastica.aggregation.nested import Nested
from pylastica.doc_type.mapping import Mapping
from pylastica.document import Document
from tests.base import Base
__author__ = 'Joe Linn'
import unittest
class NestedTest(unittest.TestCase, B... | }
}),
Document(2, {
"resellers": {
"name": "cogswell cogs",
"price": 4.98
}
})
]
doc_type.add_documents(docs)
self._index.refresh()
def tearDown(self):
super(N... | def setUp(self):
super(NestedTest, self).setUp()
self._index = self._create_index("test_aggregation_nested")
mapping = Mapping()
mapping.set_properties({
"resellers": {
"type": "nested",
"properties": {
"name": {"type": "str... | identifier_body |
tables.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | (self, request, obj_id):
api.keystone.tenant_delete(request, obj_id)
def handle(self, table, request, obj_ids):
response = \
super(DeleteTenantsAction, self).handle(table, request, obj_ids)
auth_utils.remove_project_cache(request.user.token.id)
return response
class Te... | delete | identifier_name |
tables.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
return False
return filter(comp, tenants)
class UpdateRow(tables.Row):
ajax = True
def get_data(self, request, project_id):
project_info = api.keystone.tenant_get(request, project_id,
admin=True)
return project_info
class ... | return True | conditional_block |
tables.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
class UpdateGroupsLink(tables.LinkAction):
name = "groups"
verbose_name = _("Modify Groups")
url = "horizon:identity:projects:update"
classes = ("ajax-modal",)
icon = "pencil"
policy_rules = (("identity", "identity:list_groups"),)
def allowed(self, request, project):
return api.k... | step = 'update_members'
base_url = reverse(self.url, args=[project.id])
param = urlencode({"step": step})
return "?".join([base_url, param]) | identifier_body |
tables.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # FIXME(gabriel): This should be smarter. Written for demo purposes.
q = filter_string.lower()
def comp(tenant):
if q in tenant.name.lower():
return True
return False
return filter(comp, tenants)
class UpdateRow(tables.Row):
ajax = True
... |
class TenantFilterAction(tables.FilterAction):
def filter(self, table, tenants, filter_string):
"""Really naive case-insensitive search.""" | random_line_split |
link.service.ts | /*
* -- LinkService -- [Temporary]
* @MarkPieszak
*
* Similar to Meta service but made to handle <link> creation for SEO purposes
* Soon there will be an overall HeadService within Angular that handles Meta/Link everything
*/
import { Injectable, PLATFORM_ID, Optional, RendererFactory2, ViewEncapsulatio... | (
private rendererFactory: RendererFactory2,
@Inject(DOCUMENT) private document,
@Inject(PLATFORM_ID) private platform_id
) {
}
/**
* Inject the State into the bottom of the <head>
*/
addTag(tag: LinkDefinition, forceCreation?: boolean) {
try {
con... | constructor | identifier_name |
link.service.ts | /*
* -- LinkService -- [Temporary]
* @MarkPieszak
*
* Similar to Meta service but made to handle <link> creation for SEO purposes
* Soon there will be an overall HeadService within Angular that handles Meta/Link everything
*/
import { Injectable, PLATFORM_ID, Optional, RendererFactory2, ViewEncapsulatio... |
Object.keys(tag).forEach((prop: string) => {
return renderer.setAttribute(link, prop, tag[prop]);
});
// [TODO]: get them to update the existing one (if it exists) ?
renderer.appendChild(head, link);
} catch (e) {
console.error('Err... | {
throw new Error('<head> not found within DOCUMENT.');
} | conditional_block |
link.service.ts | /*
* -- LinkService -- [Temporary]
* @MarkPieszak
*
* Similar to Meta service but made to handle <link> creation for SEO purposes
* Soon there will be an overall HeadService within Angular that handles Meta/Link everything
*/
import { Injectable, PLATFORM_ID, Optional, RendererFactory2, ViewEncapsulatio... |
}
export declare type LinkDefinition = {
charset?: string;
crossorigin?: string;
href?: string;
hreflang?: string;
media?: string;
rel?: string;
rev?: string;
sizes?: string;
target?: string;
type?: string;
} & {
[prop: string]: string;
}; | {
// Possibly re-work this
const attr: string = tag.rel ? 'rel' : 'hreflang';
return `${attr}="${tag[attr]}"`;
} | identifier_body |
link.service.ts | /*
* -- LinkService -- [Temporary]
* @MarkPieszak
*
* Similar to Meta service but made to handle <link> creation for SEO purposes
* Soon there will be an overall HeadService within Angular that handles Meta/Link everything
*/
import { Injectable, PLATFORM_ID, Optional, RendererFactory2, ViewEncapsulatio... | // Possibly re-work this
const attr: string = tag.rel ? 'rel' : 'hreflang';
return `${attr}="${tag[attr]}"`;
}
}
export declare type LinkDefinition = {
charset?: string;
crossorigin?: string;
href?: string;
hreflang?: string;
media?: string;
rel?: string;
rev?:... | // if (!attrSelector) return null;
// return this._dom.querySelector(this._doc, `meta[${attrSelector}]`);
// }
private _parseSelector(tag: LinkDefinition): string { | random_line_split |
TelemetryConstants.ts | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
export const EVENT_NAME_PREFIX = "msal.";
export const EVENT_NAME_KEY = "event_name";
export const START_TIME_KEY = "start_time";
export const ELAPSED_TIME_KEY = "elapsed_time";
export const TELEMETRY_BLOB_EVENT_NA... | IsSuccessfulConstStrKey: "Microsoft_MSAL_is_successful",
ResponseTimeConstStrKey: "Microsoft_MSAL_response_time",
TenantIdConstStrKey: "Microsoft_MSAL_tenant_id",
UiEventCountTelemetryBatchKey: "Microsoft_MSAL_ui_event_count"
};
// This is used to replace the real tenant in telemetry info
export const ... | HttpEventCountTelemetryBatchKey: "Microsoft_MSAL_http_event_count",
IdpConstStrKey: "Microsoft_MSAL_idp",
IsSilentTelemetryBatchKey: "", | random_line_split |
__init__.py | class QubesTestCase(unittest.TestCase):
'''Base class for Qubes unit tests.
'''
def __init__(self, *args, **kwargs):
super(QubesTestCase, self).__init__(*args, **kwargs)
self.longMessage = True
self.log = logging.getLogger('{}.{}.{}'.format(
self.__class__.__module__,
... | super(SystemTestsMixin, self).tearDown()
# release the lock, because we have no way to check whether it was
# read or write lock
try:
self.qc.unlock_db()
except qubes.qubes.QubesException:
pass
self._kill_test_vms(self.qc)
self.qc.lock_d... | ef setUp(self):
"""Set up the test.
.. warning::
This method instantiates QubesVmCollection acquires write lock for
it. You can use is as :py:attr:`qc`. You can (and probably
should) release the lock at the end of setUp in subclass
"""
super(SystemTe... | identifier_body |
__init__.py | # You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""
.. warning::
The test suite hereby claims any domain whose name starts with
:py:data:`VMPREFIX`... | # GNU General Public License for more details.
# | random_line_split | |
__init__.py | class QubesTestCase(unittest.TestCase):
'''Base class for Qubes unit tests.
'''
def __init__(self, *args, **kwargs):
super(QubesTestCase, self).__init__(*args, **kwargs)
self.longMessage = True
self.log = logging.getLogger('{}.{}.{}'.format(
self.__class__.__module__,
... | self.save_and_reload_db()
@classmethod
def _remove_test_vms(cls, qc, conn, prefix=VMPREFIX):
"""Aggresively remove any domain that has name in testing namespace.
"""
# first, remove them Qubes-way
something_removed = False
for vm in qc.values():
if ... | elf._remove_vm_qubes(self.qc, self.conn, vm)
| conditional_block |
__init__.py | self, expected, test_case, expected_regexp=None):
self.expected = expected
self.failureException = test_case.failureException
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
if exc_type is None:
return True
try:
exc... | _init__( | identifier_name | |
arte.py | classmethod
def suitable(cls, url):
return any(re.match(regex, url) for regex in (cls._VIDEOS_URL, cls._LIVEWEB_URL))
# TODO implement Live Stream
# from ..utils import compat_urllib_parse
# def extractLiveStream(self, url):
# video_lang = url.split('/')[-4]
# info = self.grep_w... | # [
# (1, 'path', u'could not extract video path: %s' % url),
# (2, 'player', u'could not extract video player: %s' % url),
# (3, 'url', u'could not extract video url: %s' % url)
# ]
# )
# video_url = u'%s/%s' % (info.get('url'... | random_line_split | |
arte.py | classmethod
def | (cls, url):
return any(re.match(regex, url) for regex in (cls._VIDEOS_URL, cls._LIVEWEB_URL))
# TODO implement Live Stream
# from ..utils import compat_urllib_parse
# def extractLiveStream(self, url):
# video_lang = url.split('/')[-4]
# info = self.grep_webpage(
# url,
... | suitable | identifier_name |
arte.py | classmethod
def suitable(cls, url):
return any(re.match(regex, url) for regex in (cls._VIDEOS_URL, cls._LIVEWEB_URL))
# TODO implement Live Stream
# from ..utils import compat_urllib_parse
# def extractLiveStream(self, url):
# video_lang = url.split('/')[-4]
# info = self.grep_w... |
class ArteTVPlus7IE(InfoExtractor):
IE_NAME = u'arte.tv:+7'
_VALID_URL = r'https?://www\.arte.tv/guide/(?P<lang>fr|de)/(?:(?:sendungen|emissions)/)?(?P<id>.*?)/(?P<name>.*?)(\?.*)?'
@classmethod
def _extract_url_info(cls, url):
mobj = re.match(cls._VALID_URL, url)
lang = mobj.group('... | """Extract form http://liveweb.arte.tv/"""
webpage = self._download_webpage(url, name)
video_id = self._search_regex(r'eventId=(\d+?)("|&)', webpage, u'event id')
config_xml = self._download_webpage('http://download.liveweb.arte.tv/o21/liveweb/events/event-%s.xml' % video_id,
... | identifier_body |
arte.py | classmethod
def suitable(cls, url):
return any(re.match(regex, url) for regex in (cls._VIDEOS_URL, cls._LIVEWEB_URL))
# TODO implement Live Stream
# from ..utils import compat_urllib_parse
# def extractLiveStream(self, url):
# video_lang = url.split('/')[-4]
# info = self.grep_w... |
if re.match(r'[A-Z]Q', formats[0]['quality']) is not None:
def sort_key(f):
return ['HQ', 'MQ', 'EQ', 'SQ'].index(f['quality'])
else:
def sort_key(f):
return (
# Sort first by quality
int(f.get('height',-1)... | raise ExtractorError(u'The formats list is empty') | conditional_block |
__main__.py | from __future__ import division
import state
import time
import csv
import random
import sys
POPULATION_SIZE = 100
MAX_COLLISION = 28
VALID_ARGS = "emg"
class FitnessListener():
def __init__(self, qtd=0):
self._qtd = qtd
def log(self):
self._qtd += 1
def retrive_qtd(self):
ret... | else:
sys.exit(1)
#se o argumento não era válido, levantar um erro
#se não tivermos a flag de aceitar inválidos
#levantada
elif not next_is_literal_argument:
print "Unknown command-line argument", arg
err = True
#mas caso a f... | next_is_literal_argument = True
elif 'g' in argstr[:-1]:
sys.exit("-g option must be immediately followed by number of generations")
else:
sys.exit("-g used, but no number of generations specified") | random_line_split |
__main__.py | from __future__ import division
import state
import time
import csv
import random
import sys
POPULATION_SIZE = 100
MAX_COLLISION = 28
VALID_ARGS = "emg"
class FitnessListener():
def __init__(self, qtd=0):
self._qtd = qtd
def | (self):
self._qtd += 1
def retrive_qtd(self):
return self._qtd
def reset(self):
self._qtd = 0
def copy(self):
return FitnessListener(self._qtd)
def choose_method(string):
if "roulette".startswith(string):
method = "roulette"
elif "tourney".startswith(strin... | log | identifier_name |
__main__.py | from __future__ import division
import state
import time
import csv
import random
import sys
POPULATION_SIZE = 100
MAX_COLLISION = 28
VALID_ARGS = "emg"
class FitnessListener():
def __init__(self, qtd=0):
self._qtd = qtd
def log(self):
self._qtd += 1
def retrive_qtd(self):
ret... |
def make_config(arguments):
elitist = None
method = None
max_generations = None
mutation_rate = 0.8
#flag para permitir argumentos "inválidos" se vierem
#depois de opções que precisam de argumentos
next_is_literal_argument = False
err = False
for index, arg in enumerate(ar... | return generations | conditional_block |
__main__.py | from __future__ import division
import state
import time
import csv
import random
import sys
POPULATION_SIZE = 100
MAX_COLLISION = 28
VALID_ARGS = "emg"
class FitnessListener():
def __init__(self, qtd=0):
self._qtd = qtd
def log(self):
self._qtd += 1
def retrive_qtd(self):
|
def reset(self):
self._qtd = 0
def copy(self):
return FitnessListener(self._qtd)
def choose_method(string):
if "roulette".startswith(string):
method = "roulette"
elif "tourney".startswith(string):
method = "tourney"
else:
sys.exit(string + " is not a valid... | return self._qtd | identifier_body |
models.py | from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
from django.core.urlresolvers import reverse
from django.db import models
from github import UnknownObjectException
from social.apps.django_app.default.models imp... | return folders | folders.extend(docs)
| random_line_split |
models.py | from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
from django.core.urlresolvers import reverse
from django.db import models
from github import UnknownObjectException
from social.apps.django_app.default.models imp... | (self):
path_processor = PathProcessor(self.full_name, is_directory=True)
return path_processor.repo_disk_path
def enqueue(self, file_change=None):
file_change = file_change or {}
process_wiki.delay(self.id, file_change)
def get_folder_contents(self, path, documents):
f... | directory | identifier_name |
models.py | from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
from django.core.urlresolvers import reverse
from django.db import models
from github import UnknownObjectException
from social.apps.django_app.default.models imp... |
if self.user == user or user.is_staff:
return True
g = get_github(user)
grepo = g.get_repo(self.full_name)
guser = g.get_user(user.username)
return grepo.has_in_collaborators(guser)
def add_webhook(self, request):
if settings.DEBUG:
self.webh... | return False | conditional_block |
models.py | from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
from django.core.urlresolvers import reverse
from django.db import models
from github import UnknownObjectException
from social.apps.django_app.default.models imp... |
def enqueue(self, file_change=None):
file_change = file_change or {}
process_wiki.delay(self.id, file_change)
def get_folder_contents(self, path, documents):
folders = []
docs = []
for document in documents:
doc_path = document.path
if path != ... | path_processor = PathProcessor(self.full_name, is_directory=True)
return path_processor.repo_disk_path | identifier_body |
surface.rs | XyOpt {
/// Returns point coordinates.
fn xy(&self) -> (i16,i16);
}
/// A trait that can be translated to a rectangular area (`w` and `h` fields in `sdl::Rect`,
/// hence the name). Also contains `()`.
pub trait WhOpt { |
/// Same as `WhOpt` but does not contain `()`.
pub trait Wh {
/// Returns a rectangular area.
fn wh(&self) -> (u16,u16);
}
impl XyOpt for () {
#[inline(always)]
fn xy_opt(&self) -> Option<(i16,i16)> { None }
}
// Rust: we can't define these with `impl<T:Xy> XyOpt for T` due to the ambiguity.
impl XyO... | /// Returns a rectangular area if any.
fn wh_opt(&self) -> Option<(u16,u16)>;
} | random_line_split |
surface.rs | XyOpt {
/// Returns point coordinates.
fn xy(&self) -> (i16,i16);
}
/// A trait that can be translated to a rectangular area (`w` and `h` fields in `sdl::Rect`,
/// hence the name). Also contains `()`.
pub trait WhOpt {
/// Returns a rectangular area if any.
fn wh_opt(&self) -> Option<(u16,u16)>;
}
/... |
}
impl<'r,T:Wh> Wh for &'r T {
#[inline(always)]
fn wh(&self) -> (u16,u16) { (*self).wh() }
}
/// A helper trait for defining every implementations for types `(T1,T2)` where `T1` and `T2` is
/// convertible to an integer.
trait ToInt16 {
/// Converts to `i16`.
fn to_i16(&self) -> i16;
/// Convert... | { self.get_size() } | identifier_body |
surface.rs | () {
#[inline(always)]
fn xy_opt(&self) -> Option<(i16,i16)> { None }
}
// Rust: we can't define these with `impl<T:Xy> XyOpt for T` due to the ambiguity.
impl XyOpt for Rect {
#[inline(always)]
fn xy_opt(&self) -> Option<(i16,i16)> { Some((self.x, self.y)) }
}
impl<'r,T:XyOpt> XyOpt for &'r T {
... | get_pixel_checked | identifier_name | |
jquery.funnyText.js | $.extend({
'speed': 700,
'borderColor': 'black',
'activeColor': 'white',
'color': 'black',
'fontSize': '7em',
'direction': 'both'
}, options);
var that = $(this);
that.addClass('funnyText');
var original = $(this);
var characters = $.trim(original.text()).split('');
... | } else if(x == "left" && y == "bottom"){
result = "left top moveUp";
}
}
return result;
}
/**
* Sets the margin for the characters container depending on the position
* of the characters to show.
*/
function setMargin(obj){
if(obj.find('.normal').hasClass('bottom')... | {
var result;
if((getRandom(0, 100) % 2 && options.direction == 'both') || options.direction == 'horizontal') {
if(x == "right" && y == "top"){
result = "left top moveLeft";
} else if(x == "right" && y == "bottom"){
result = "left bottom moveLeft";
} else if(x == "left" && y == "... | identifier_body |
jquery.funnyText.js | $.extend({
'speed': 700,
'borderColor': 'black',
'activeColor': 'white',
'color': 'black',
'fontSize': '7em',
'direction': 'both'
}, options);
var that = $(this);
that.addClass('funnyText');
var original = $(this);
var characters = $.trim(original.text()).split('');
... | function getRandom(from, to){
return from + Math.floor(Math.random() * (to +1));
}
/**
* Gets a new position for the active character in a way it can be scrolled
* vertically or horizontally from the position of the original character.
* (from top left to botom right wouldn't work, for examp... |
/**
* Returnsn a random number between two values.
*/
| random_line_split |
jquery.funnyText.js | Text');
var original = $(this);
var characters = $.trim(original.text()).split('');
var positionsY = ['top', 'bottom'];
var positionsX = ['left', 'right'];
var activePositionX, activePositionY, normalPositionX, normalPositionY;
var previousPosition;
//removing the original text
o... | supportTransitions | identifier_name | |
test_shellcheck.py | from lintreview.review import Problems
from lintreview.review import Comment
from lintreview.tools.shellcheck import Shellcheck
from lintreview.utils import in_path
from unittest import TestCase
from unittest import skipIf
from nose.tools import eq_
shellcheck_missing = not(in_path('shellCheck'))
class Testshellchec... | (self):
self.tool.process_files([self.fixtures[1]])
problems = self.problems.all(self.fixtures[1])
eq_(2, len(problems))
fname = self.fixtures[1]
expected = Comment(
fname,
5,
3,
'a is referenced but not assigned.\nDouble quote to ... | test_process_files__one_file_fail | identifier_name |
test_shellcheck.py | from lintreview.review import Problems
from lintreview.review import Comment
from lintreview.tools.shellcheck import Shellcheck
from lintreview.utils import in_path
from unittest import TestCase
from unittest import skipIf
from nose.tools import eq_
shellcheck_missing = not(in_path('shellCheck'))
class Testshellchec... | self.assertTrue(self.tool.check_dependencies())
@needs_shellcheck
def test_process_files__one_file_pass(self):
self.tool.process_files([self.fixtures[0]])
eq_([], self.problems.all(self.fixtures[0]))
@needs_shellcheck
def test_process_files__one_file_fail(self):
self.to... | needs_shellcheck = skipIf(shellcheck_missing, 'Needs shellcheck')
fixtures = [
'tests/fixtures/shellcheck/no_errors.sh',
'tests/fixtures/shellcheck/has_errors.sh',
]
def setUp(self):
self.problems = Problems()
self.tool = Shellcheck(self.problems)
def test_match_file(s... | identifier_body |
test_shellcheck.py | from lintreview.review import Problems
from lintreview.review import Comment
from lintreview.tools.shellcheck import Shellcheck
from lintreview.utils import in_path
from unittest import TestCase
from unittest import skipIf
from nose.tools import eq_
shellcheck_missing = not(in_path('shellCheck'))
class Testshellchec... | @needs_shellcheck
def test_process_files_with_config(self):
config = {
'shell': 'bash',
'exclude': 'SC2154,SC2069'
}
tool = Shellcheck(self.problems, config)
tool.process_files([self.fixtures[1]])
problems = self.problems.all(self.fixtures[1])
... | random_line_split | |
mm.genre.js | function PrepareGenrePage() {
/*var json = [
{ "title": "Now Playing", "section": "nowplaying-movie-list-tube" },
{ "title": "Upcoming", "section": "upcoming-movie-list-tube" },
{ "title": "Previous", "section": "previous-movie-list-tube" },
... | $(".movies").append(GetTubeControl("Now Playing", "nowplaying-movie-list", "nowplaying-movies-pager"));
$(".movies").append(GetTubeControl("Upcoming Releases", "upcoming-movie-list", "upcoming-movies-pager"));
$(".movies").append(GetTubeControl("Previous Movies", "previous-movie-list", "previous-movies-page... | $(".movies").append("<div class=\"upcoming-movie-list\"></div>");
$(".movies").append("<div class=\"previous-movie-list\"></div>");
$(".movies").append("<div class=\"recent-container\"><div class=\"tube-tilte\">Recent</div></div>");
/*$(".movies").append(GetTubeControl(name + " Movies", "genre-name")); | random_line_split |
mm.genre.js | function PrepareGenrePage() {
| $(".movies").append(GetTubeControl("Upcoming Releases", "upcoming-movie-list", "upcoming-movies-pager"));
$(".movies").append(GetTubeControl("Previous Movies", "previous-movie-list", "previous-movies-pager"));
$(".movies").append(GetTubeControl("Recently Viewed", "recent-container", "recent-pager"));
$... | /*var json = [
{ "title": "Now Playing", "section": "nowplaying-movie-list-tube" },
{ "title": "Upcoming", "section": "upcoming-movie-list-tube" },
{ "title": "Previous", "section": "previous-movie-list-tube" },
{ "title": "Recently Vie... | identifier_body |
mm.genre.js | function Pr | {
/*var json = [
{ "title": "Now Playing", "section": "nowplaying-movie-list-tube" },
{ "title": "Upcoming", "section": "upcoming-movie-list-tube" },
{ "title": "Previous", "section": "previous-movie-list-tube" },
{ "title": "Recently ... | epareGenrePage() | identifier_name |
nsp.js | import async from 'async'
export default ({nspApiClient, db}) => {
let syncAdvisoriesIntervalId = null
const Nsp = {
// Given a list of dependency names, retrieve an object that lists advisories
// by dependency name
getAdvisories (depNames, cb) {
const tasks = depNames.reduce((tasks, depName) =... | } else {
console.log(`Adding another advisory ${advisory.id} for module ${advisory.module_name}`)
db.put(key, advisories.concat(advisory), cb)
}
})
}, cb)
})
}, cb)
})
},
syncAdvisoriesPeriodic... | // Already found - we're all synced
done = true
cb() | random_line_split |
nsp.js | import async from 'async'
export default ({nspApiClient, db}) => {
let syncAdvisoriesIntervalId = null
const Nsp = {
// Given a list of dependency names, retrieve an object that lists advisories
// by dependency name
getAdvisories (depNames, cb) {
const tasks = depNames.reduce((tasks, depName) =... | (cb) {
cb = cb || ((err) => { if (err) console.error('Failed to sync advisories', err) })
// Get the first page
const limit = 100
let done = false
nspApiClient.advisories({limit: 1, offset: 0}, (err, response) => {
if (err) return cb(err)
const pages = Math.ceil(respons... | syncAdvisories | identifier_name |
nsp.js | import async from 'async'
export default ({nspApiClient, db}) => {
let syncAdvisoriesIntervalId = null
const Nsp = {
// Given a list of dependency names, retrieve an object that lists advisories
// by dependency name
getAdvisories (depNames, cb) {
const tasks = depNames.reduce((tasks, depName) =... |
}
return Nsp
}
| {
clearInterval(syncAdvisoriesIntervalId)
interval = interval || 3600000
syncAdvisoriesIntervalId = setInterval(Nsp.syncAdvisories, interval)
} | identifier_body |
ensureUnique.js | /**
* Created by ane on 5/20/15.
*/
var app = angular.module('myApp', []);
app.directive('ensureUnique',['$http',function($http){
return {
require: 'ngModel',
link: function(scope,ele,attrs,c){
scope.$watch(attrs.ngModel,function(n){
if(!n) return;
$http({
... | // }else{
// $scope.signup_form.submitted = true;
// }
// };
//}); | // | random_line_split |
runner.py | #!/usr/bin/python
import os, sys
log_file = 'py_ns3_visualizer.log'
# Remove log file
if os.path.exists (log_file):
os.system ('rm %s' % log_file)
if len (sys.argv) == 2 and sys.argv[1] == 'help': #not in [1, 2, 3]:
print 'Usage: runner [<events.log>] [<interval>]'
sys.exit (0)
if len (sys.argv) >= 2: | # Pick any link state periodic
os.system ('find traces/ -name "events.log" | head -1 > tmp.txt')
events_log = open ('tmp.txt', 'r').readline ().strip ()
os.system ('rm tmp.txt')
if not os.path.exists (events_log):
print 'File does not exist:', events_log
sys.exit (0)
if len (sys.argv) >= 3:
interval = s... | events_log = sys.argv[1]
else: | random_line_split |
runner.py | #!/usr/bin/python
import os, sys
log_file = 'py_ns3_visualizer.log'
# Remove log file
if os.path.exists (log_file):
|
if len (sys.argv) == 2 and sys.argv[1] == 'help': #not in [1, 2, 3]:
print 'Usage: runner [<events.log>] [<interval>]'
sys.exit (0)
if len (sys.argv) >= 2:
events_log = sys.argv[1]
else:
# Pick any link state periodic
os.system ('find traces/ -name "events.log" | head -1 > tmp.txt')
events_log = open ('t... | os.system ('rm %s' % log_file) | conditional_block |
libs.py | 23689',
'lib/libopenmpt.a',
[
'--disable-shared', '--enable-static'
],
)
wildmidi = CmakeProject(
'https://codeload.github.com/Mindwerks/wildmidi/tar.gz/wildmidi-0.4.3',
'498e5a96455bb4b91b37188ad6dcb070824e92c44f5ed452b90adbaec8eef3c5',
'lib/libWildMidi.a',
[
'-DBUILD_SHARE... | '--disable-decoder=png',
'--disable-decoder=qdraw',
'--disable-decoder=qpeg',
'--disable-decoder=rawvideo',
'--disable-decoder=realtext', | random_line_split | |
tendermint.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | () {
let s = r#"{
"params": {
"gasLimitBoundDivisor": "0x0400",
"validators": {
"list": ["0xc6d9d2cd449a754c494264e1809c50e34d64562b"]
},
"blockReward": "0x50"
}
}"#;
let _deserialized: Tendermint = serde_json::from_str(s).unwrap();
}
}
| tendermint_deserialization | identifier_name |
tendermint.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | "gasLimitBoundDivisor": "0x0400",
"validators": {
"list": ["0xc6d9d2cd449a754c494264e1809c50e34d64562b"]
},
"blockReward": "0x50"
}
}"#;
let _deserialized: Tendermint = serde_json::from_str(s).unwrap();
}
} | random_line_split | |
main.py | import webapp2
from google.appengine.ext import db
import logging
import charbuilder
import traits
import traceback
import random
import string
instance_key = "".join(
(random.choice(string.ascii_uppercase + string.digits) for i in xrange(25)))
def getFile(_file):
with open(_file, "r") as f: return f.read().re... |
new_dict.extend(master_dict[dictionary].items())
return dict(new_dict)
class Parameters(db.Model):
parameters = db.StringProperty()
order = db.DateTimeProperty(auto_now=True)
instance_key = db.StringProperty()
class MainPage(webapp2.RequestHandler):
fields = {"cat_checkboxes": "",
"s... | continue | conditional_block |
main.py | import webapp2
from google.appengine.ext import db
import logging
import charbuilder
import traits
import traceback
import random
import string
instance_key = "".join(
(random.choice(string.ascii_uppercase + string.digits) for i in xrange(25)))
def getFile(_file):
with open(_file, "r") as f: return f.read().re... | fields = {"cat_checkboxes": "",
"spell_checkboxes": ""}
def get(self):
"""
"""
self.response.headers['Content-Type'] = 'text/html' # tells the page to load as html instead of plain text
try:
self.configureCatBoxes()
self.configureSpellCollegeCheckboxes()
self.response... |
class MainPage(webapp2.RequestHandler):
| random_line_split |
main.py | import webapp2
from google.appengine.ext import db
import logging
import charbuilder
import traits
import traceback
import random
import string
instance_key = "".join(
(random.choice(string.ascii_uppercase + string.digits) for i in xrange(25)))
def getFile(_file):
with open(_file, "r") as f: return f.read().re... | (master_dict):
new_dict = []
for dictionary in master_dict.keys():
if not dictionary:
continue
new_dict.extend(master_dict[dictionary].items())
return dict(new_dict)
class Parameters(db.Model):
parameters = db.StringProperty()
order = db.DateTimeProperty(auto_now=True)
instance_key = db.... | mergeDicts | identifier_name |
main.py | import webapp2
from google.appengine.ext import db
import logging
import charbuilder
import traits
import traceback
import random
import string
instance_key = "".join(
(random.choice(string.ascii_uppercase + string.digits) for i in xrange(25)))
def getFile(_file):
with open(_file, "r") as f: return f.read().re... | column = 0
for cat in power_cats:
if column > 5:
column = 0
if column == 0:
complete_html += "<tr>" # starts a new table row
y = checkbox_html % (cat, cat) # this puts whatever the current category is as the value and text to display
complete_html += "<td> %s </td>" % (... | psionic_powers = ["Antipsi", "Esp", "Psychic Healing",
"Psychokinesis", "Teleportation", "Telepathy"]
power_cats = []
checkbox_html = '<input type="checkbox" name="cat_type" value="%s"> %s'
column = 0
complete_html = "<table>"
for cat in sorted(traits.traits.SKILL_CATEGORIES):... | identifier_body |
read.component.ts | import { Component, OnInit } from "@angular/core";
import { ImageSource } from "@nativescript/core";
// >> fs-read-import-code
import { knownFolders, path, File, Folder } from "@nativescript/core";
// << fs-read-import-code
@Component({
moduleId: module.id,
templateUrl: "./read.component.html"
})
export class ... | public folder: Folder;
public file: File;
public imageFile: File;
public binarySource: string;
public folderEntities: Array<FolderEntity> = [];
ngOnInit() {
this.folderName = "NativeScript";
this.fileName = "README.txt";
this.fileTextContent = "Build amazing iOS and Andr... | public documents: Folder; | random_line_split |
read.component.ts | import { Component, OnInit } from "@angular/core";
import { ImageSource } from "@nativescript/core";
// >> fs-read-import-code
import { knownFolders, path, File, Folder } from "@nativescript/core";
// << fs-read-import-code
@Component({
moduleId: module.id,
templateUrl: "./read.component.html"
})
export class ... |
}
}
class FolderEntity {
private name: string;
private myPath: string;
private lastModified: string;
constructor(name: string, myPath: string, lastModified: string) {
this.name = name;
this.myPath = myPath;
this.lastModified = lastModified;
}
}
| {
this.imageFile = File.fromPath(myPath);
this.binarySource = this.imageFile.readSync(err => { console.log("Error:" + err); });
console.log(this.binarySource);
// << fs-read-sync-code
// >> fs-write-sync-code
this.imageFile.writeSync(this.binarySo... | conditional_block |
read.component.ts | import { Component, OnInit } from "@angular/core";
import { ImageSource } from "@nativescript/core";
// >> fs-read-import-code
import { knownFolders, path, File, Folder } from "@nativescript/core";
// << fs-read-import-code
@Component({
moduleId: module.id,
templateUrl: "./read.component.html"
})
export class ... | () {
// >> fs-read-sync-code
let image = ImageSource.fromResourceSync("icon");
let folder = knownFolders.documents();
let myPath = path.join(folder.path, "Test.png");
let saved = image.saveToFile(myPath, "png");
if (saved) {
this.imageFile = File.fromPath(myP... | onReadSync | identifier_name |
worker_test.js | "use strict";
/**
* @license
* Copyright 2019 Google 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... | //@ts-ignore
importScripts('http://bs-local.com:12345/base/dist/tf-core.min.js');
var a = tf.tensor1d([1, 2, 3]);
var b = tf.tensor1d([3, 2, 1]);
a = a.add(b);
//@ts-ignore
self.postMessage({ data: a.dataSync() });
};
jasmine_util_1.describeWithFlags('computation in worker', jasmine_util_1.H... | // The source code of a web worker.
var workerTest = function () { | random_line_split |
bad-turn.service.spec.ts | import {beforeEachProviders, it, describe, expect, inject} from '@angular/core/testing';
import {BadTurnService} from './bad-turn.service';
describe('Bad Turn Service', () => {
beforeEachProviders(() => [BadTurnService]);
it('should return a quote when getBadTurn is called',
inject([BadTurnService], (service... | }); |
for (let quoteTest in test) {
expect(test[quoteTest]).toBe(true);
}
})); | random_line_split |
bad-turn.service.spec.ts | import {beforeEachProviders, it, describe, expect, inject} from '@angular/core/testing';
import {BadTurnService} from './bad-turn.service';
describe('Bad Turn Service', () => {
beforeEachProviders(() => [BadTurnService]);
it('should return a quote when getBadTurn is called',
inject([BadTurnService], (service... |
for (let quoteTest in test) {
expect(test[quoteTest]).toBe(true);
}
}));
});
| {
test[service.getBadTurn()] = true;
done = true;
for (let quoteTest in test) {
done = done && test[quoteTest];
}
i -= 1;
} | conditional_block |
slice.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use anyhow::{anyhow, Error, Result};
use blobrepo::BlobRepo;
use c... | }
let mut head_generation_groups: BTreeMap<u64, Vec<ChangesetId>> = BTreeMap::new();
stream::iter(heads.into_iter().map(|csid| async move {
match repo.get_generation_number(ctx.clone(), csid).await? {
Some(gen) => Ok(Some((csid, gen))),
None => Err(anyhow!(
"... | {
let heads = underived_heads(ctx, repo, derivers, heads.as_slice()).await?;
if skiplist_index.indexed_node_count() == 0 {
// This skiplist index is not populated. Generate a single
// slice with all heads.
info!(
ctx.logger(),
"Repository not sliced as skiplist... | identifier_body |
slice.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use anyhow::{anyhow, Error, Result};
use blobrepo::BlobRepo;
use c... |
} else {
// This commit is in a new generation group.
let gen_group = (gen.value() / slice_size) * slice_size;
new_heads_groups.insert(parent, gen_group);
}
}
}
// Add all commits we've seen to the ... | {
heads.push(parent);
} | conditional_block |
slice.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use anyhow::{anyhow, Error, Result};
use blobrepo::BlobRepo;
use c... | }
/// Slice a respository into a sequence of slices for derivation.
///
/// For large repositories with a long history, computing the full set of
/// commits before beginning backfilling is slow, and cannot be resumed
/// if interrupted.
///
/// This function makes large repositories more tractible by using the
/// sk... | .try_collect::<Vec<_>>()
.await?;
Ok(parents_with_generations) | random_line_split |
slice.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use anyhow::{anyhow, Error, Result};
use blobrepo::BlobRepo;
use c... | (
ctx: &CoreContext,
repo: &BlobRepo,
derivers: &[Arc<dyn DerivedUtils>],
heads: &[ChangesetId],
) -> Result<HashSet<ChangesetId>> {
derivers
.iter()
.map(|deriver| async move {
Ok::<_, Error>(stream::iter(
deriver
.pending(ctx.clone(),... | underived_heads | identifier_name |
mod.rs | //! Unified interface for communicating with different trackers.
use std::old_io::{IoResult};
use std::old_io::net::ip::{SocketAddr, IpAddr};
use types::{Timepoint};
pub mod udp;
/// Information pertaining to the swarm we are in.
pub struct AnnounceInfo {
/// Number of leechers in the swarm.
pub leechers: i... | {
/// Number of leechers in the swarm.
pub leechers: i32,
/// Number of seeders in the swarm.
pub seeders: i32,
/// Number of downloads for this torrent.
pub downloads: i32
}
/// Statistics for our download session.
#[derive(Copy)]
pub struct TransferStatus {
/// Number of bytes downloa... | ScrapeInfo | identifier_name |
mod.rs | //! Unified interface for communicating with different trackers.
use std::old_io::{IoResult};
use std::old_io::net::ip::{SocketAddr, IpAddr};
use types::{Timepoint};
pub mod udp;
/// Information pertaining to the swarm we are in.
pub struct AnnounceInfo {
/// Number of leechers in the swarm.
pub leechers: i... | }
/// Interface for communicating with an generic tracker.
pub trait Tracker {
/// Returns the local ip address that is being used to communicate with the tracker.
fn local_ip(&mut self) -> IpAddr;
/// Returns information about the swarm for a particular torrent file without
/// joining the swarm.
... | pub remaining: i64,
/// Number of bytes uploaded so far.
pub uploaded: i64 | random_line_split |
nditer_test.py | import weldnumpy as wn
import numpy as np
def assert_correct(np_a, z):
'''
common part of the check.
'''
shape = []
for s in z.shape:
shape.append(s)
shape = tuple(shape)
np_a = np.reshape(np_a, shape)
for i in range((z.shape[0])):
for j in range(z.shape[1]):
... |
def test_start():
'''
Has a different start from the base array.
'''
orig = np.random.rand(20,20)
a = orig[0:20:1,0:20:1]
start = (wn.addr(a) - wn.addr(orig)) / a.itemsize
orig = wn.array(orig)
z = np.copy(a)
z = np.exp(z)
shapes = orig.weldobj.update(np.array(list(a.shape)))
... | assert_correct(np_a, z)
| random_line_split |
nditer_test.py | import weldnumpy as wn
import numpy as np
def assert_correct(np_a, z):
'''
common part of the check.
'''
shape = []
for s in z.shape:
shape.append(s)
shape = tuple(shape)
np_a = np.reshape(np_a, shape)
for i in range((z.shape[0])):
for j in range(z.shape[1]):
... | ():
'''
Has a different start from the base array.
'''
orig = np.random.rand(20,20)
orig2 = np.random.rand(20,20)
a = orig[5:20:1,3:20:2]
b = orig2[5:20:1,3:20:2]
start = (wn.addr(a) - wn.addr(orig)) / a.itemsize
orig = wn.array(orig)
# copying so we can test them later.
z =... | test_zip | identifier_name |
nditer_test.py | import weldnumpy as wn
import numpy as np
def assert_correct(np_a, z):
'''
common part of the check.
'''
shape = []
for s in z.shape:
|
shape = tuple(shape)
np_a = np.reshape(np_a, shape)
for i in range((z.shape[0])):
for j in range(z.shape[1]):
assert np_a[i][j] == z[i][j]
def test_view():
'''
Adding the iter code to a view.
In general, do we deal correctly with wn.array(view)??
'''
orig = np.ran... | shape.append(s) | conditional_block |
nditer_test.py | import weldnumpy as wn
import numpy as np
def assert_correct(np_a, z):
'''
common part of the check.
'''
shape = []
for s in z.shape:
shape.append(s)
shape = tuple(shape)
np_a = np.reshape(np_a, shape)
for i in range((z.shape[0])):
for j in range(z.shape[1]):
... | for s in a.shape:
end = end*s
end = end + start
iter_code = 'result(for(nditer({arr}, {start}L, {end}L, 1L, {shapes}, {strides}), appender, \
|b, i, e| merge(b,exp(e))))'.format(shapes=shapes, strides=strides, end=str(end),
start=str(start), arr=orig.name)
orig.weldobj.weld_code... | '''
Has a different start from the base array.
'''
orig = np.random.rand(20,20)
a = orig[0:20:1,0:20:1]
start = (wn.addr(a) - wn.addr(orig)) / a.itemsize
orig = wn.array(orig)
z = np.copy(a)
z = np.exp(z)
shapes = orig.weldobj.update(np.array(list(a.shape)))
strides = []
f... | identifier_body |
ifmt-bad-arg.rs | // Copyright 2013 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 ... | () {
// bad arguments to the format! call
format!("{}"); //~ ERROR: invalid reference to argument
format!("{1}", 1); //~ ERROR: invalid reference to argument `1`
//~^ ERROR: argument never used
format!("{foo}"); //~ ERROR: no argument named `foo`
... | main | identifier_name |
ifmt-bad-arg.rs | // Copyright 2013 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 ... | format!("{0}");
//~^ ERROR invalid reference to argument `0` (no arguments given)
format!("{0} {1}", 1);
//~^ ERROR invalid reference to argument `1` (there is 1 argument)
format!("{0} {1} {2}", 1, 2);
//~^ ERROR invalid reference to argument `2` (there are 2 arguments)
format!("{0} {1}")... | random_line_split | |
ifmt-bad-arg.rs | // Copyright 2013 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 ... |
// bad number of arguments, see #15780
format!("{0}");
//~^ ERROR invalid reference to argument `0` (no arguments given)
format!("{0} {1}", 1);
//~^ ERROR invalid reference to argument `1` (there is 1 argument)
format!("{0} {1} {2}", 1, 2);
//~^ ERROR invalid reference to argument `2` (t... | {
// bad arguments to the format! call
format!("{}"); //~ ERROR: invalid reference to argument
format!("{1}", 1); //~ ERROR: invalid reference to argument `1`
//~^ ERROR: argument never used
format!("{foo}"); //~ ERROR: no argument named `foo`
... | identifier_body |
core.py | #
# core.py
#
# Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com>
#
# Deluge is free software.
#
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.... |
@export
def get_commands(self):
return self.config["commands"]
@export
def remove_command(self, command_id):
for command in self.config["commands"]:
if command[EXECUTE_ID] == command_id:
self.config["commands"].remove(command)
component.get(... | command_id = hashlib.sha1(str(time.time())).hexdigest()
self.config["commands"].append((command_id, event, command))
self.config.save()
component.get("EventManager").emit(ExecuteCommandAddedEvent(command_id, event, command)) | identifier_body |
core.py | #
# core.py
#
# Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com>
#
# Deluge is free software.
#
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.... | (self, command_id):
self._args = [command_id]
class Core(CorePluginBase):
def enable(self):
self.config = ConfigManager("execute.conf", DEFAULT_CONFIG)
event_manager = component.get("EventManager")
self.registered_events = {}
# Go through the commands list and register even... | __init__ | identifier_name |
core.py | #
# core.py
#
# Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com>
#
# Deluge is free software.
#
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.... |
self.config.save()
@export
def save_command(self, command_id, event, cmd):
for i, command in enumerate(self.config["commands"]):
if command[EXECUTE_ID] == command_id:
self.config["commands"][i] = (command_id, event, cmd)
break
self.config.sav... | self.config["commands"].remove(command)
component.get("EventManager").emit(ExecuteCommandRemovedEvent(command_id))
break | conditional_block |
core.py | #
# core.py
#
# Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com>
#
# Deluge is free software.
#
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.... | EXECUTE_ID = 0
EXECUTE_EVENT = 1
EXECUTE_COMMAND = 2
EVENT_MAP = {
"complete": "TorrentFinishedEvent",
"added": "TorrentAddedEvent"
}
class ExecuteCommandAddedEvent(DelugeEvent):
"""
Emitted when a new command is added.
"""
def __init__(self, command_id, event, command):
self._args = [... | random_line_split | |
svg.filter.js | // svg.filter.js 0.4 - Copyright (c) 2013-2014 Wout Fierens - Licensed under the MIT license
;(function() {
// Main filter class
SVG.Filter = function() {
this.constructor.call(this, SVG.create('filter'))
}
// Inherit from SVG.Container
SVG.Filter.prototype = new SVG.Parent
//
SVG.extend(SVG.Filter... |
}).call(this); | {
if (!Array.isArray(list))
return list
for (var i = 0, l = list.length, s = []; i < l; i++)
s.push(list[i])
return s.join(' ')
} | identifier_body |
svg.filter.js | // svg.filter.js 0.4 - Copyright (c) 2013-2014 Wout Fierens - Licensed under the MIT license
;(function() {
// Main filter class
SVG.Filter = function() {
this.constructor.call(this, SVG.create('filter'))
}
// Inherit from SVG.Container
SVG.Filter.prototype = new SVG.Parent
//
SVG.extend(SVG.Filter... | return filter
}
})
//
SVG.extend(SVG.Container, {
// Define filter on defs
filter: function(block) {
return this.defs().filter(block)
}
})
//
SVG.extend(SVG.Element, SVG.G, SVG.Nested, {
// Create filter element in defs and store reference
filter: function(blo... | random_line_split | |
svg.filter.js | // svg.filter.js 0.4 - Copyright (c) 2013-2014 Wout Fierens - Licensed under the MIT license
;(function() {
// Main filter class
SVG.Filter = function() {
this.constructor.call(this, SVG.create('filter'))
}
// Inherit from SVG.Container
SVG.Filter.prototype = new SVG.Parent
//
SVG.extend(SVG.Filter... | (matrix) {
/* convert possible array value to string */
if (Array.isArray(matrix))
matrix = new SVG.Array(matrix)
/* ensure there are no leading, tailing or double spaces */
return matrix.toString().replace(/^\s+/, '').replace(/\s+$/, '').replace(/\s+/g, ' ')
}
function listString(list) {
... | normaliseMatrix | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.