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 |
|---|---|---|---|---|
emit-appender.ts | import { LoggingEvent } from "log4js";
import { EventEmitter } from "events";
import { EMIT_APPENDER_EVENT_NAME } from "../../../constants";
function emitAppender(layout: Function, emitter: EventEmitter) |
export function configure(
config: Log4JSEmitAppenderConfiguration,
layouts: any
) {
if (!config.emitter) {
throw new Error("Emitter must be passed to emit-appender");
}
if (!config.emitter.emit || typeof config.emitter.emit !== "function") {
throw new Error("The passed emitter must be instance of EventEmit... | {
const appender = (loggingEvent: LoggingEvent) => {
emitter.emit(EMIT_APPENDER_EVENT_NAME, {
loggingEvent,
formattedMessage: layout(loggingEvent),
});
};
appender.shutdown = () => {
emitter.removeAllListeners(EMIT_APPENDER_EVENT_NAME);
};
return appender;
} | identifier_body |
irng.ts | /* This is a conversion from libRmath.so to Typescript/Javascript
Copyright (C) 2018 Jacob K.F. Bogers info@mail.jacob-bogers.com
This program 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... | (event: MessageType, handler: (...args: any[]) => void): void {
const handlers = this.notify.get(event) || [];
this.notify.set(event, handlers);
handlers.push(handler);
}
public unregister(event: MessageType, handler?: (...args: any[]) => void): void {
if (!handler) {
... | register | identifier_name |
irng.ts | /* This is a conversion from libRmath.so to Typescript/Javascript
Copyright (C) 2018 Jacob K.F. Bogers info@mail.jacob-bogers.com
This program 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... | }
public register(event: MessageType, handler: (...args: any[]) => void): void {
const handlers = this.notify.get(event) || [];
this.notify.set(event, handlers);
handlers.push(handler);
}
public unregister(event: MessageType, handler?: (...args: any[]) => void): void {
... | const handlers = this.notify.get(event);
if (handlers !== undefined) {
handlers.forEach((h) => h(...args));
} | random_line_split |
irng.ts | /* This is a conversion from libRmath.so to Typescript/Javascript
Copyright (C) 2018 Jacob K.F. Bogers info@mail.jacob-bogers.com
This program 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... |
public get name(): string {
return this._name;
}
public randoms(n: number): Float32Array {
n = !n || n < 0 ? 1 : n;
const rc = new Float32Array(n);
for (let i = 0; i < n; i++) {
rc[i] = this.random();
}
return rc;
}
random(): number {
... | {
this._name = name;
this.notify = new Map();
this.emit = this.emit.bind(this);
} | identifier_body |
irng.ts | /* This is a conversion from libRmath.so to Typescript/Javascript
Copyright (C) 2018 Jacob K.F. Bogers info@mail.jacob-bogers.com
This program 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... |
return rc;
}
random(): number {
throw new Error(`override this function in ${this.constructor.name}`)
}
public emit(event: MessageType, ...args: unknown[]): void {
const handlers = this.notify.get(event);
if (handlers !== undefined) {
handlers.forEach((h) =... | {
rc[i] = this.random();
} | conditional_block |
setup.py | import os, sys
from setuptools import setup
setup(
name='reddit_comment_scraper',
version='2.0.5',
description='A simple Reddit-scraping script',
url='https://github.com/jfarmer/reddit_comment_scraper',
author='Jesse Farmer',
author_email='jesse@20bits.com',
license='MIT',
packages=['r... | 'unicodecsv==0.9.4',
'praw==2.1.19'
],
entry_points={
'console_scripts': [
'scrape_comments=reddit_comment_scraper:main'
]
},
classifiers=[
'Development Status :: 4 - Beta',
'Natural Language :: English',
'Intended Audience :: Science... |
install_requires=[ | random_line_split |
counters.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Generic types for counters-related CSS values.
#[cfg(feature = "servo")]
use crate::computed_values::list_st... | )]
pub enum Content<ImageUrl> {
/// `normal` reserved keyword.
Normal,
/// `none` reserved keyword.
None,
/// `-moz-alt-content`.
#[cfg(feature = "gecko")]
MozAltContent,
/// Content items.
Items(#[css(iterable)] Box<[ContentItem<ImageUrl>]>),
}
impl<ImageUrl> Content<ImageUrl> {
... | ToCss,
ToResolvedValue,
ToShmem, | random_line_split |
counters.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Generic types for counters-related CSS values.
#[cfg(feature = "servo")]
use crate::computed_values::list_st... | (&self) -> &Self::Target {
&(self.0).0
}
}
/// A generic value for the `counter-set` and `counter-reset` properties.
#[derive(
Clone,
Debug,
Default,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
pub struct CounterS... | deref | identifier_name |
test_property_tree_wrappers.py | # Copyright (c) 2016, the Cap authors.
#
# This file is subject to the Modified BSD License and may not be distributed
# without copyright and license information. Please refer to the file LICENSE
# for the text and further information on this license.
from pycap import PropertyTree
from os import remove
import unitte... | today = 'april 8th, 2016'
with open(info_file, 'w') as fout:
fout.write('date "' + today + '"')
ptree.parse_info(info_file)
self.assertEqual(ptree.get_string('date'), today)
remove(info_file)
# XML parser
xml_file = 'input.xml'
pi = 3.14
... | # INFO parser
info_file = 'input.info' | random_line_split |
test_property_tree_wrappers.py | # Copyright (c) 2016, the Cap authors.
#
# This file is subject to the Modified BSD License and may not be distributed
# without copyright and license information. Please refer to the file LICENSE
# for the text and further information on this license.
from pycap import PropertyTree
from os import remove
import unitte... |
def test_raise_exceptions(self):
ptree = PropertyTree()
# property tree will throw if the specified path does not exist
self.assertRaises(KeyError, ptree.get_int, 'path.does.not.exist')
# or if the translation fails
ptree.put_string('some.path.to.a.string', 'not a double')
... | ptree = PropertyTree()
# put child
child = PropertyTree()
child.put_double('prune', 6.10)
ptree.put_child('a.g', child)
self.assertEqual(ptree.get_double('a.g.prune'), 6.10)
# get child
ptree.put_string('child.name', 'clement')
ptree.put_int('child.age', -... | identifier_body |
test_property_tree_wrappers.py | # Copyright (c) 2016, the Cap authors.
#
# This file is subject to the Modified BSD License and may not be distributed
# without copyright and license information. Please refer to the file LICENSE
# for the text and further information on this license.
from pycap import PropertyTree
from os import remove
import unitte... | unittest.main() | conditional_block | |
test_property_tree_wrappers.py | # Copyright (c) 2016, the Cap authors.
#
# This file is subject to the Modified BSD License and may not be distributed
# without copyright and license information. Please refer to the file LICENSE
# for the text and further information on this license.
from pycap import PropertyTree
from os import remove
import unitte... | (self):
ptree = PropertyTree()
# put child
child = PropertyTree()
child.put_double('prune', 6.10)
ptree.put_child('a.g', child)
self.assertEqual(ptree.get_double('a.g.prune'), 6.10)
# get child
ptree.put_string('child.name', 'clement')
ptree.put_in... | test_get_children | identifier_name |
extension.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | private _waiting : boolean;
constructor(context: ExtensionContext) {
this._context = context;
this._waiting = false;
}
private getMediaPath(mediaFile) {
return this._context.asAbsolutePath(path.join('media', mediaFile));
}
private fixHref(resource: Uri, href: string) {
if (href) {
// Return early if... | class MDDocumentContentProvider implements TextDocumentContentProvider {
private _context: ExtensionContext;
private _onDidChange = new EventEmitter<Uri>(); | random_line_split |
extension.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | ].join('\n');
return head + body + tail;
});
}
get onDidChange(): Event<Uri> {
return this._onDidChange.event;
}
public update(uri: Uri) {
if (!this._waiting) {
this._waiting = true;
setTimeout(() => {
this._waiting = false;
this._onDidChange.fire(uri);
}, 300);
}
}
} | {
return vscode.workspace.openTextDocument(Uri.parse(uri.query)).then(document => {
const head = [].concat(
'<!DOCTYPE html>',
'<html>',
'<head>',
'<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',
`<link rel="stylesheet" type="text/css" href="${this.getMediaPath('markdown.c... | identifier_body |
extension.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (resource: Uri, href: string) {
if (href) {
// Return early if href is already a URL
if (Uri.parse(href).scheme) {
return href;
}
// Otherwise convert to a file URI by joining the href with the resource location
return Uri.file(path.join(path.dirname(resource.fsPath), href)).toString();
}
retur... | fixHref | identifier_name |
extension.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
// Otherwise convert to a file URI by joining the href with the resource location
return Uri.file(path.join(path.dirname(resource.fsPath), href)).toString();
}
return href;
}
private computeCustomStyleSheetIncludes(uri: Uri): string[] {
const styles = vscode.workspace.getConfiguration('markdown')['style... | {
return href;
} | conditional_block |
dvs_securitygroup_rpc.py | # Copyright 2015 Mirantis, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
def _refresh_ports(self):
device_ids = self._devices_to_update
self._devices_to_update = self._devices_to_update - device_ids
if not device_ids:
return
if self.use_enhanced_rpc:
devices_info = self.plugin_rpc.security_group_info_for_devices(
... | if not device_ids:
return
LOG.info(_LI("Remove device filter for %r"), device_ids)
self.firewall.remove_port_filter(device_ids) | identifier_body |
dvs_securitygroup_rpc.py | # Copyright 2015 Mirantis, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
else:
devices = self.plugin_rpc.security_group_rules_for_devices(
self.context, list(device_ids))
self.firewall.prepare_port_filter(devices.values())
def remove_devices_filter(self, device_ids):
if not device_ids:
return
LOG.info(_LI("Remove ... | devices_info = self.plugin_rpc.security_group_info_for_devices(
self.context, list(device_ids))
devices = update_rules(devices_info) | conditional_block |
dvs_securitygroup_rpc.py | # Copyright 2015 Mirantis, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | (self):
device_ids = self._devices_to_update
self._devices_to_update = self._devices_to_update - device_ids
if not device_ids:
return
if self.use_enhanced_rpc:
devices_info = self.plugin_rpc.security_group_info_for_devices(
self.context, device_ids... | _refresh_ports | identifier_name |
dvs_securitygroup_rpc.py | # Copyright 2015 Mirantis, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | from networking_vsphere._i18n import _LI
from networking_vsphere.utils.rpc_translator import update_rules
from neutron.agent import securitygroups_rpc
LOG = logging.getLogger(__name__)
class DVSSecurityGroupRpc(securitygroups_rpc.SecurityGroupAgentRpc):
def __init__(self, context, plugin_rpc,
... | # License for the specific language governing permissions and limitations
# under the License.
from threading import Timer
from oslo_log import log as logging
| random_line_split |
hover.ts | import * as LServer from "vscode-languageserver-types";
import {IRegistry} from "../_iregistry";
import {ABAPObject} from "../objects/_abap_object";
import {LSPUtils} from "./_lsp_utils";
import * as Tokens from "../abap/1_lexer/tokens";
import {ITextDocumentPositionParams} from "./_interfaces";
import {LSPLookup} from... | else if (found.token instanceof Tokens.StringTemplate
|| found.token instanceof Tokens.StringTemplateBegin
|| found.token instanceof Tokens.StringTemplateEnd
|| found.token instanceof Tokens.StringTemplateMiddle) {
return {kind: LServer.MarkupKind.Markdown, value: "String Template"};
} else... | {
return undefined;
} | conditional_block |
hover.ts | import * as LServer from "vscode-languageserver-types";
import {IRegistry} from "../_iregistry";
import {ABAPObject} from "../objects/_abap_object";
import {LSPUtils} from "./_lsp_utils";
import * as Tokens from "../abap/1_lexer/tokens";
import {ITextDocumentPositionParams} from "./_interfaces";
import {LSPLookup} from... | private readonly reg: IRegistry;
public constructor(reg: IRegistry) {
this.reg = reg;
}
public find(pos: ITextDocumentPositionParams): LServer.MarkupContent | undefined {
const file = LSPUtils.getABAPFile(this.reg, pos.textDocument.uri);
if (file === undefined) {
return undefined;
}
... | random_line_split | |
hover.ts | import * as LServer from "vscode-languageserver-types";
import {IRegistry} from "../_iregistry";
import {ABAPObject} from "../objects/_abap_object";
import {LSPUtils} from "./_lsp_utils";
import * as Tokens from "../abap/1_lexer/tokens";
import {ITextDocumentPositionParams} from "./_interfaces";
import {LSPLookup} from... | }
const lookup = LSPLookup.lookup(found, this.reg, obj);
if (lookup?.hover) {
return {kind: LServer.MarkupKind.Markdown, value: lookup.hover};
}
if (found.token instanceof Tokens.String) {
return {kind: LServer.MarkupKind.Markdown, value: "String"};
}
return undefined;
}
} | {
const file = LSPUtils.getABAPFile(this.reg, pos.textDocument.uri);
if (file === undefined) {
return undefined;
}
const obj = this.reg.getObject(file.getObjectType(), file.getObjectName());
if (!(obj instanceof ABAPObject)) {
return undefined;
}
const found = LSPUtils.findCurso... | identifier_body |
hover.ts | import * as LServer from "vscode-languageserver-types";
import {IRegistry} from "../_iregistry";
import {ABAPObject} from "../objects/_abap_object";
import {LSPUtils} from "./_lsp_utils";
import * as Tokens from "../abap/1_lexer/tokens";
import {ITextDocumentPositionParams} from "./_interfaces";
import {LSPLookup} from... | {
private readonly reg: IRegistry;
public constructor(reg: IRegistry) {
this.reg = reg;
}
public find(pos: ITextDocumentPositionParams): LServer.MarkupContent | undefined {
const file = LSPUtils.getABAPFile(this.reg, pos.textDocument.uri);
if (file === undefined) {
return undefined;
}
... | Hover | identifier_name |
photos-container.component.ts | import { CanActivate, ChangeDetectionStrategy, Component } from "../core";
import * as actions from "./photo.actions";
import { pluck } from "../core/pluck";
import { Photo } from "./photo.model";
@Component({
routes: ["/admin/photos","/admin/photo/edit/:photoId"],
template: require("./photos-container.compone... | if (state.lastTriggeredByAction instanceof actions.RemovePhotoAction && this.entity && this.entity.id) {
this.entity = pluck({ value: Number(this.$routeParams["photoId"]), items: this.entities }) as Photo;
if (Object.keys(this.entity).length === 0) { this.$location.path("/admin/photos");... | if (state.lastTriggeredByAction instanceof actions.SetCurrentPhotoAction && state.lastTriggeredByAction.entity)
this.$location.path("/admin/photo/edit/" + state.lastTriggeredByAction.entity.id);
| random_line_split |
photos-container.component.ts | import { CanActivate, ChangeDetectionStrategy, Component } from "../core";
import * as actions from "./photo.actions";
import { pluck } from "../core/pluck";
import { Photo } from "./photo.model";
@Component({
routes: ["/admin/photos","/admin/photo/edit/:photoId"],
template: require("./photos-container.compone... |
storeOnChange = state => {
this.entities = state.photos;
if (state.lastTriggeredByAction instanceof actions.SetCurrentPhotoAction && !state.lastTriggeredByAction.entity)
this.$location.path("/admin/photos");
if (state.lastTriggeredByAction instanceof actions.SetCurrentPhoto... | { } | identifier_body |
photos-container.component.ts | import { CanActivate, ChangeDetectionStrategy, Component } from "../core";
import * as actions from "./photo.actions";
import { pluck } from "../core/pluck";
import { Photo } from "./photo.model";
@Component({
routes: ["/admin/photos","/admin/photo/edit/:photoId"],
template: require("./photos-container.compone... |
}
upload = () => this.photoActionCreator.openPhotoUploadModal();
edit = entity => this.photoActionCreator.edit(entity);
remove = entity => this.photoActionCreator.remove(entity);
create = entity => this.photoActionCreator.create();
addOrUpdate = options => this.photoActionCreator.addOrUpdate(... | {
this.entity = new Photo();
} | conditional_block |
photos-container.component.ts | import { CanActivate, ChangeDetectionStrategy, Component } from "../core";
import * as actions from "./photo.actions";
import { pluck } from "../core/pluck";
import { Photo } from "./photo.model";
@Component({
routes: ["/admin/photos","/admin/photo/edit/:photoId"],
template: require("./photos-container.compone... | (private $location: angular.ILocationService, private $routeParams: angular.route.IRouteParamsService, private photoActionCreator: actions.PhotoActionCreator) { }
storeOnChange = state => {
this.entities = state.photos;
if (state.lastTriggeredByAction instanceof actions.SetCurrentPhotoAction && !... | constructor | identifier_name |
main.js | // @flow
/* eslint-env node */
/* global Restivus */
// Import Meteor :3 and Mongo :3
import { Meteor } from 'meteor/meteor'
// Import fs and path to access the filesystem. And mime to get MIMETypes.
import { readdirSync, lstatSync, readFileSync } from 'fs'
import { join, sep, basename } from 'path'
import { ... |
return 'file'
}
// Start the loop to push folderContents.
for (i = 0; i < folderContents.length; i += 1) {
// Push objects to folderContentsWithTypes.
folderContentsWithTypes.push({ name: folderContents[i], type: getType() })
}
// Return folderContentsWithTypes.
retur... | {
return 'folder'
} | conditional_block |
main.js | // @flow
/* eslint-env node */
/* global Restivus */
// Import Meteor :3 and Mongo :3
import { Meteor } from 'meteor/meteor'
// Import fs and path to access the filesystem. And mime to get MIMETypes.
import { readdirSync, lstatSync, readFileSync } from 'fs'
import { join, sep, basename } from 'path'
import { ... | folderContentsWithTypes.push({ name: folderContents[i], type: getType() })
}
// Return folderContentsWithTypes.
return folderContentsWithTypes
},
// Pass it some paths and get a combination of those paths.
joinPaths (...paths): string {
return join(...paths)
},
goUpOneDirect... | for (i = 0; i < folderContents.length; i += 1) {
// Push objects to folderContentsWithTypes.
| random_line_split |
main.js | // @flow
/* eslint-env node */
/* global Restivus */
// Import Meteor :3 and Mongo :3
import { Meteor } from 'meteor/meteor'
// Import fs and path to access the filesystem. And mime to get MIMETypes.
import { readdirSync, lstatSync, readFileSync } from 'fs'
import { join, sep, basename } from 'path'
import { ... |
})
| {
// Get basename.
const filename = basename(this.urlParams._filePath)
const mimetype = lookup(this.urlParams._filePath)
// Set em' headers.
this.response.writeHead({
// Filename.
'Content-disposition': `attachment; filename=${filename}`,
// Type of file.
'Content-... | identifier_body |
main.js | // @flow
/* eslint-env node */
/* global Restivus */
// Import Meteor :3 and Mongo :3
import { Meteor } from 'meteor/meteor'
// Import fs and path to access the filesystem. And mime to get MIMETypes.
import { readdirSync, lstatSync, readFileSync } from 'fs'
import { join, sep, basename } from 'path'
import { ... | () {
// Get basename.
const filename = basename(this.urlParams._filePath)
const mimetype = lookup(this.urlParams._filePath)
// Set em' headers.
this.response.writeHead({
// Filename.
'Content-disposition': `attachment; filename=${filename}`,
// Type of file.
'Cont... | get | identifier_name |
derive-clone_1_0.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
/// Since builtin `Clone` impls were introduced in Rust 1.21 this struct
/// should impl `Clone` "manually".
#[repr(C)]
#[derive(Copy)]
pub struct ShouldImplClone {
pub large: [::std::os::raw::c_int; 33usize],
}
#[... |
}
impl Default for ShouldImplClone {
fn default() -> Self {
unsafe {
let mut s: Self = ::std::mem::uninitialized();
::std::ptr::write_bytes(&mut s, 0, 1);
s
}
}
}
| {
*self
} | identifier_body |
derive-clone_1_0.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
/// Since builtin `Clone` impls were introduced in Rust 1.21 this struct
/// should impl `Clone` "manually".
#[repr(C)]
#[derive(Copy)]
pub struct ShouldImplClone {
pub large: [::std::os::raw::c_int; 33usize],
}
#[... | );
assert_eq!(
unsafe {
&(*(::std::ptr::null::<ShouldImplClone>())).large as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(ShouldImplClone),
"::",
stringify!(large)
)
)... | assert_eq!(
::std::mem::align_of::<ShouldImplClone>(),
4usize,
concat!("Alignment of ", stringify!(ShouldImplClone)) | random_line_split |
derive-clone_1_0.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
/// Since builtin `Clone` impls were introduced in Rust 1.21 this struct
/// should impl `Clone` "manually".
#[repr(C)]
#[derive(Copy)]
pub struct ShouldImplClone {
pub large: [::std::os::raw::c_int; 33usize],
}
#[... | () -> Self {
unsafe {
let mut s: Self = ::std::mem::uninitialized();
::std::ptr::write_bytes(&mut s, 0, 1);
s
}
}
}
| default | identifier_name |
database.py | #!/usr/bin/env python
"""
A convinience wrapper around mysql connector.
|
open-ihm is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
open-ihm is distributed in the hope that it will be useful, but
WITHOUT ANY... |
This file is part of open-ihm.
| random_line_split |
setupEnvironment.js | /* eslint-disable */
const NODE_ENV = process.env.NODE_ENV;
if (NODE_ENV !== 'development' && NODE_ENV !== 'production') {
throw new Error('NODE_ENV must either be set to development or production.');
}
global.__DEV__ = NODE_ENV === 'development';
global.requestAnimationFrame = function(callback) {
setTimeout(cal... | () {
return Infinity;
},
});
});
};
global.cancelIdleCallback = function(callbackID) {
clearTimeout(callbackID);
};
// By default React console.error()'s any errors, caught or uncaught.
// However it is annoying to assert that a warning fired each time
// we assert that there is an exception in ... | timeRemaining | identifier_name |
setupEnvironment.js | /* eslint-disable */
const NODE_ENV = process.env.NODE_ENV;
if (NODE_ENV !== 'development' && NODE_ENV !== 'production') {
throw new Error('NODE_ENV must either be set to development or production.');
}
global.__DEV__ = NODE_ENV === 'development';
global.requestAnimationFrame = function(callback) {
setTimeout(cal... | ,
});
});
};
global.cancelIdleCallback = function(callbackID) {
clearTimeout(callbackID);
};
// By default React console.error()'s any errors, caught or uncaught.
// However it is annoying to assert that a warning fired each time
// we assert that there is an exception in our tests. This lets us
// opt out of... | {
return Infinity;
} | identifier_body |
setupEnvironment.js | /* eslint-disable */
const NODE_ENV = process.env.NODE_ENV;
if (NODE_ENV !== 'development' && NODE_ENV !== 'production') {
throw new Error('NODE_ENV must either be set to development or production.');
}
global.__DEV__ = NODE_ENV === 'development';
|
global.requestIdleCallback = function(callback) {
return setTimeout(() => {
callback({
timeRemaining() {
return Infinity;
},
});
});
};
global.cancelIdleCallback = function(callbackID) {
clearTimeout(callbackID);
};
// By default React console.error()'s any errors, caught or uncaugh... | global.requestAnimationFrame = function(callback) {
setTimeout(callback);
}; | random_line_split |
setupEnvironment.js | /* eslint-disable */
const NODE_ENV = process.env.NODE_ENV;
if (NODE_ENV !== 'development' && NODE_ENV !== 'production') {
throw new Error('NODE_ENV must either be set to development or production.');
}
global.__DEV__ = NODE_ENV === 'development';
global.requestAnimationFrame = function(callback) {
setTimeout(cal... |
// Preserve the empty object identity across module resets.
// This is needed for some tests that rely on string refs
// but reset modules between loading different renderers.
const obj = require.requireActual('fbjs/lib/emptyObject');
jest.mock('fbjs/lib/emptyObject', () => obj);
| {
// Same as above.
DOMException.prototype.suppressReactErrorLogging = true;
// Also prevent JSDOM from logging intentionally thrown errors.
// TODO: it might make sense to do it the other way around.
// https://github.com/facebook/react/issues/11098#issuecomment-355032539
window.addEventListener('error', ... | conditional_block |
bootstrap.py | from distutils.dir_util import copy_tree, remove_tree
import os
import shutil
def _copy_function(source, destination):
print('Bootstrapping project at %s' % destination)
copy_tree(source, destination)
def create_app():
cwd = os.getcwd()
game_logic_path = os.path.join(cwd, 'game_logic')
game_app_... |
else:
_copy_function(app_template, cwd)
if not os.path.exists('settings.yaml'):
shutil.copy2('settings.yaml.template', 'settings.yaml')
if not os.path.exists('logging.yaml'):
shutil.copy2('logging.yaml.template', 'logging.yaml')
if __name__ == '__main__':
create_app()
| if _game_app_interface_exists:
os.remove(game_app_interface)
if _game_logic_path_exists:
remove_tree(game_logic_path)
_copy_function(app_template, cwd) | conditional_block |
bootstrap.py | from distutils.dir_util import copy_tree, remove_tree
import os
import shutil
def _copy_function(source, destination):
print('Bootstrapping project at %s' % destination)
copy_tree(source, destination)
def create_app():
| if not os.path.exists('settings.yaml'):
shutil.copy2('settings.yaml.template', 'settings.yaml')
if not os.path.exists('logging.yaml'):
shutil.copy2('logging.yaml.template', 'logging.yaml')
if __name__ == '__main__':
create_app()
| cwd = os.getcwd()
game_logic_path = os.path.join(cwd, 'game_logic')
game_app_interface = os.path.join(cwd, 'game_app.py')
app_template = os.path.join(cwd, 'engine', 'app_template')
_game_logic_path_exists = os.path.exists(game_logic_path)
_game_app_interface_exists = os.path.exists(game_app_interfac... | identifier_body |
bootstrap.py | from distutils.dir_util import copy_tree, remove_tree
import os
import shutil
def _copy_function(source, destination):
print('Bootstrapping project at %s' % destination)
copy_tree(source, destination)
def create_app():
cwd = os.getcwd()
game_logic_path = os.path.join(cwd, 'game_logic')
game_app_... | if not os.path.exists('logging.yaml'):
shutil.copy2('logging.yaml.template', 'logging.yaml')
if __name__ == '__main__':
create_app() | shutil.copy2('settings.yaml.template', 'settings.yaml')
| random_line_split |
bootstrap.py | from distutils.dir_util import copy_tree, remove_tree
import os
import shutil
def | (source, destination):
print('Bootstrapping project at %s' % destination)
copy_tree(source, destination)
def create_app():
cwd = os.getcwd()
game_logic_path = os.path.join(cwd, 'game_logic')
game_app_interface = os.path.join(cwd, 'game_app.py')
app_template = os.path.join(cwd, 'engine', 'app_t... | _copy_function | identifier_name |
blueprint.py | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from flask import request
from indico.modules.auth.controllers import (RHAccounts, RHAdminImpersonate, RH... |
# Legacy URLs
auth_compat_blueprint = _compat_bp = IndicoBlueprint('compat_auth', __name__)
_compat_bp.add_url_rule('/user/login', 'login', make_compat_redirect_func(_bp, 'login'))
_compat_bp.add_url_rule('/user/register', 'register', make_compat_redirect_func(_bp, 'register'))
| if endpoint in {'auth.accounts', 'auth.remove_account'} and 'user_id' not in values:
values['user_id'] = request.view_args.get('user_id') | identifier_body |
blueprint.py | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from flask import request
from indico.modules.auth.controllers import (RHAccounts, RHAdminImpersonate, RH... | (endpoint, values):
if endpoint in {'auth.accounts', 'auth.remove_account'} and 'user_id' not in values:
values['user_id'] = request.view_args.get('user_id')
# Legacy URLs
auth_compat_blueprint = _compat_bp = IndicoBlueprint('compat_auth', __name__)
_compat_bp.add_url_rule('/user/login', 'login', make_com... | _add_user_id | identifier_name |
blueprint.py | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from flask import request
from indico.modules.auth.controllers import (RHAccounts, RHAdminImpersonate, RH... | _bp.add_url_rule('/login/<provider>/link-account', 'link_account', RHLinkAccount, methods=('GET', 'POST'))
_bp.add_url_rule('/logout/', 'logout', RHLogout)
_bp.add_url_rule('/register/', 'register', RHRegister, methods=('GET', 'POST'), defaults={'provider': None})
_bp.add_url_rule('/register/<provider>', 'register', R... | random_line_split | |
blueprint.py | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from flask import request
from indico.modules.auth.controllers import (RHAccounts, RHAdminImpersonate, RH... |
# Legacy URLs
auth_compat_blueprint = _compat_bp = IndicoBlueprint('compat_auth', __name__)
_compat_bp.add_url_rule('/user/login', 'login', make_compat_redirect_func(_bp, 'login'))
_compat_bp.add_url_rule('/user/register', 'register', make_compat_redirect_func(_bp, 'register'))
| values['user_id'] = request.view_args.get('user_id') | conditional_block |
SimpleFactoryConfiguration.py | '''
Created on Mar 29, 2015
@author: rnc4
'''
import json
class SimpleFactoryConfiguration:
def __init__(self, path="factory_config.json"):
|
def parse(self):
self.RANDOM_SEED= self.data["RANDOM_SEED"]
self.RUN_RT = self.data["RUN_RT"]
self.SIM_RT_FACTOR= self.data["SIM_RT_FACTOR"]
self.NUM_PARTS= self.data["NUM_PARTS"]
self.NUM_MACHINES= self.data["NUM_MACHINES"]
self.NUM_STATIONS= self.data["N... | self.client_addrs = []
with open(path) as data_file:
self.data = json.load(data_file)
self.parse() | identifier_body |
SimpleFactoryConfiguration.py | '''
Created on Mar 29, 2015
@author: rnc4
'''
import json
class | :
def __init__(self, path="factory_config.json"):
self.client_addrs = []
with open(path) as data_file:
self.data = json.load(data_file)
self.parse()
def parse(self):
self.RANDOM_SEED= self.data["RANDOM_SEED"]
self.RUN_RT = self.data["RUN_RT"]... | SimpleFactoryConfiguration | identifier_name |
SimpleFactoryConfiguration.py | '''
Created on Mar 29, 2015 |
class SimpleFactoryConfiguration:
def __init__(self, path="factory_config.json"):
self.client_addrs = []
with open(path) as data_file:
self.data = json.load(data_file)
self.parse()
def parse(self):
self.RANDOM_SEED= self.data["RANDOM_SEED"]
... |
@author: rnc4
'''
import json | random_line_split |
failing.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 th... | (command.Command):
"""Show the current failures known by the repository.
Without --subunit, the process exit code will be non-zero if the
previous test run was not successful and test failures are shown. But,
with --subunit, the process exit code is non-zero only if the subunit
stream could not be ... | Failing | identifier_name |
failing.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 th... | for failures.
:rtype: int
"""
if repo_type not in ['file', 'sql']:
stdout.write('Repository type %s is not a type' % repo_type)
return 1
repo = util.get_repo_open(repo_type, repo_url)
run = repo.get_failing()
if subunit:
return _show_subunit(run)
case = run.g... | """Print the failing tests from the most recent run in the repository
This function will print to STDOUT whether there are any tests that failed
in the last run. It optionally will print the test_ids for the failing
tests if ``list_tests`` is true. If ``subunit`` is true a subunit stream
with just the ... | identifier_body |
failing.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 th... |
def take_action(self, parsed_args):
user_conf = user_config.get_user_config(self.app_args.user_config)
args = parsed_args
if getattr(user_conf, 'failing', False):
list_opt = args.list or user_conf.failing.get('list', False)
else:
list_opt = args.list
... | random_line_split | |
failing.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 th... |
case = run.get_test()
failed = False
result, summary = _make_result(repo, list_tests=list_tests)
result.startTestRun()
try:
case.run(result)
finally:
result.stopTestRun()
failed = not results.wasSuccessful(summary)
if failed:
result = 1
else:
result =... | return _show_subunit(run) | conditional_block |
regions-fn-subtyping-2.rs | // Copyright 2012 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 ... |
fn wants_same_region(_f: Box<for<'b> FnMut(&'b isize, Box<FnMut(&'b isize)>)>) {
}
pub fn main() {
} | fn has_same_region(f: Box<for<'a> FnMut(&'a isize, Box<FnMut(&'a isize)>)>) {
// `f` should be the type that `wants_same_region` wants, but
// right now the compiler complains that it isn't.
wants_same_region(f);
} | random_line_split |
regions-fn-subtyping-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (f: Box<for<'a> FnMut(&'a isize, Box<FnMut(&'a isize)>)>) {
// `f` should be the type that `wants_same_region` wants, but
// right now the compiler complains that it isn't.
wants_same_region(f);
}
fn wants_same_region(_f: Box<for<'b> FnMut(&'b isize, Box<FnMut(&'b isize)>)>) {
}
pub fn main() {
}
| has_same_region | identifier_name |
regions-fn-subtyping-2.rs | // Copyright 2012 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 ... |
fn wants_same_region(_f: Box<for<'b> FnMut(&'b isize, Box<FnMut(&'b isize)>)>) {
}
pub fn main() {
}
| {
// `f` should be the type that `wants_same_region` wants, but
// right now the compiler complains that it isn't.
wants_same_region(f);
} | identifier_body |
index.d.ts | import {Options as FastGlobOptions} from 'fast-glob';
declare namespace globby {
type ExpandDirectoriesOption =
| boolean
| readonly string[]
| {files?: readonly string[]; extensions?: readonly string[]};
interface GlobbyOptions extends FastGlobOptions {
/**
If set to `true`, `globby` will automatically g... | interface GlobTask {
readonly pattern: string;
readonly options: globby.GlobbyOptions;
}
interface GitignoreOptions {
readonly cwd?: string;
readonly ignore?: readonly string[];
}
type FilterFunction = (path: string) => boolean;
}
interface Gitignore {
/**
`.gitignore` files matched by the ignore conf... | */
readonly gitignore?: boolean;
}
| random_line_split |
binary.ts |
'use strict';
declare function require(n:string):any
/*eslint-disable no-bitwise*/
// A trick for browserified version.
// Since we make browserifier to ignore `buffer` module, NodeBuffer will be undefined
var NodeBuffer = require('buffer').Buffer;
import {Type} from '../type';
// [ 64, 65, 66 ] -> [ padding, CR,... | // Dump tail
tailbits = (max % 4) * 6;
if (tailbits === 0) {
result.push((bits >> 16) & 0xFF);
result.push((bits >> 8) & 0xFF);
result.push(bits & 0xFF);
} else if (tailbits === 18) {
result.push((bits >> 10) & 0xFF);
result.push((bits >> 2) & 0xFF);
} else if (tailbits === 12) {
res... | {
var code, idx, tailbits,
input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
max = input.length,
map = BASE64_MAP,
bits = 0,
result = [];
// Collect by 6*4 bits (3 bytes)
for (idx = 0; idx < max; idx++) {
if ((idx % 4 === 0) && idx) {
result... | identifier_body |
binary.ts |
'use strict';
declare function require(n:string):any
/*eslint-disable no-bitwise*/
// A trick for browserified version.
// Since we make browserifier to ignore `buffer` module, NodeBuffer will be undefined
var NodeBuffer = require('buffer').Buffer;
import {Type} from '../type';
// [ 64, 65, 66 ] -> [ padding, CR,... | (data) {
if (null === data) {
return false;
}
var code, idx, bitlen = 0, len = 0, max = data.length, map = BASE64_MAP;
// Convert one by one.
for (idx = 0; idx < max; idx++) {
code = map.indexOf(data.charAt(idx));
// Skip CR/LF
if (code > 64) { continue; }
// Fail on illegal characters... | resolveYamlBinary | identifier_name |
binary.ts |
'use strict';
declare function require(n:string):any
/*eslint-disable no-bitwise*/
// A trick for browserified version.
// Since we make browserifier to ignore `buffer` module, NodeBuffer will be undefined
var NodeBuffer = require('buffer').Buffer;
import {Type} from '../type';
// [ 64, 65, 66 ] -> [ padding, CR,... |
// Fail on illegal characters
if (code < 0) { return false; }
bitlen += 6;
}
// If there are any bits left, source was corrupted
return (bitlen % 8) === 0;
}
function constructYamlBinary(data) {
var code, idx, tailbits,
input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to si... | { continue; } | conditional_block |
binary.ts | 'use strict';
declare function require(n:string):any
/*eslint-disable no-bitwise*/
// A trick for browserified version.
// Since we make browserifier to ignore `buffer` module, NodeBuffer will be undefined
var NodeBuffer = require('buffer').Buffer;
import {Type} from '../type';
// [ 64, 65, 66 ] -> [ padding, CR, L... | result += map[64];
} else if (tail === 1) {
result += map[(bits >> 2) & 0x3F];
result += map[(bits << 4) & 0x3F];
result += map[64];
result += map[64];
}
return result;
}
function isBinary(object) {
return NodeBuffer && NodeBuffer.isBuffer(object);
}
export = new Type('tag:yaml.org,2002:b... | result += map[bits & 0x3F];
} else if (tail === 2) {
result += map[(bits >> 10) & 0x3F];
result += map[(bits >> 4) & 0x3F];
result += map[(bits << 2) & 0x3F]; | random_line_split |
Primer.py | # -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
import random
k=9
xx=[[1,0,1,0,1,0,1,0,1]]
d=[1]
def rndB():
return random.uniform(0.5, 0.9)
def rndL():
|
for i in range(50):
xx.append([rndB(), rndL(),rndB(),
rndL(),rndB(),rndL(),
rndB(), rndL(),rndB()])
d.append([1,0,0,0])
xx.append([rndL(), rndB(),rndL(),
rndB(),rndL(),rndB(),
rndL(), rndB(),rndL()])
d.append([0,1,0,0])
xx.appe... | return random.uniform(0.1, 0.5) | identifier_body |
Primer.py | # -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
import random
k=9
xx=[[1,0,1,0,1,0,1,0,1]]
d=[1]
def rndB():
return random.uniform(0.5, 0.9)
def rndL():
return random.uniform(0.1, 0.5)
for i in range(50):
xx.append([rndB(), rndL(),rndB(),
rndL(),rndB(),rndL(),... | range(k):
xtest.append(float(input('Введите {}-й элемент: '.format(j+1))))
plt.imshow([xtest[:3], xtest[3:6], xtest[6:]], interpolation='nearest')
y1=0; y2=0
for j in range(len(xtest)):
y1+=w1[j]*xtest[j]
y2+=w2[j]*xtest[j]
... | conditional_block | |
Primer.py | # -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
import random
k=9
xx=[[1,0,1,0,1,0,1,0,1]]
d=[1]
def rndB():
return random.uniform(0.5, 0.9)
def rndL():
return random.uniform(0.1, 0.5)
for i in range(50):
xx.append([rndB(), rndL(),rndB(),
rndL(),rndB(),rndL(),... | d.append([0,0,0,1])
def pict(a):
if a==1: return [rndB(), rndL(),rndB(),
rndL(),rndB(), rndL(),
rndB(), rndL(),rndB()]
elif a==0:return [rndL(), rndB(),rndL(),
rndB(),rndL(), rndB(),
rndL(), rndB(),rndL()]
... | d.append([0,0,1,0])
xx.append([rndB(), rndL(),rndB(),
rndB(),rndB(), rndB(),
rndB(), rndL(), rndB()])
| random_line_split |
Primer.py | # -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
import random
k=9
xx=[[1,0,1,0,1,0,1,0,1]]
d=[1]
def rndB():
return random.uniform(0.5, 0.9)
def rndL():
return random.uniform(0.1, 0.5)
for i in range(50):
xx.append([rndB(), rndL(),rndB(),
rndL(),rndB(),rndL(),... | (a):
if a==1: return [rndB(), rndL(),rndB(),
rndL(),rndB(), rndL(),
rndB(), rndL(),rndB()]
elif a==0:return [rndL(), rndB(),rndL(),
rndB(),rndL(), rndB(),
rndL(), rndB(),rndL()]
elif a==2:return [rndB(), rndB(),rndB()... | pict | identifier_name |
ability.rs | use entity::Entity;
use spatial::Place;
use self::Ability::*;
/// Ability describes some way of affecting the game world. It is generally
/// attached to a mob or an item.
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub enum Ability {
Multi(Vec<Ability>),
/// Damage a target for a given amount.
... | (&self, agent: Option<Entity>, target: Place) {
if let &Multi(ref abls) = self {
for abl in abls.iter() {
abl.apply(agent, target);
}
return;
}
// Target entity.
let te = match target {
Place::In(e, _) => Some(e),
... | apply | identifier_name |
ability.rs | use entity::Entity;
use spatial::Place;
use self::Ability::*;
/// Ability describes some way of affecting the game world. It is generally
/// attached to a mob or an item.
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub enum Ability {
Multi(Vec<Ability>),
/// Damage a target for a given amount.
... | }
} | } | random_line_split |
ability.rs | use entity::Entity;
use spatial::Place;
use self::Ability::*;
/// Ability describes some way of affecting the game world. It is generally
/// attached to a mob or an item.
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub enum Ability {
Multi(Vec<Ability>),
/// Damage a target for a given amount.
... |
}
_ => ()
}
}
}
| {
e.heal(n);
if let Some(a) = agent { a.delete() }
} | conditional_block |
kegg_taxonomy.py | #!/usr/bin/env python
__author__ = "Jesse Zaneveld"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Jesse Zaneveld", "Rob Knight"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Jesse Zaneveld"
__email__ = "zaneveld@gmail.com"
__status__ = "Development"
from sys import argv
from... | (lines):
"""Returns successive taxonomy entries from lines.
Format of return value is four levels of taxonomy (sometimes empty),
unique id, three-letter kegg code, abbreviated name, full name,
genus, species, and common name if present.
Taxonomic level information is implicit in the number of... | parse_kegg_taxonomy | identifier_name |
kegg_taxonomy.py | #!/usr/bin/env python
__author__ = "Jesse Zaneveld"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Jesse Zaneveld", "Rob Knight"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Jesse Zaneveld"
__email__ = "zaneveld@gmail.com"
__status__ = "Development"
from sys import argv
from... | filename = argv[1]
for result_line in parse_kegg_taxonomy(open(filename,"U")):
print result_line.strip() | yield "\t".join(output_taxon) + "\n"
if __name__ == '__main__':
from sys import argv | random_line_split |
kegg_taxonomy.py | #!/usr/bin/env python
__author__ = "Jesse Zaneveld"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Jesse Zaneveld", "Rob Knight"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Jesse Zaneveld"
__email__ = "zaneveld@gmail.com"
__status__ = "Development"
from sys import argv
from... | genus and species names which may have a common name in parentheses
afterwards.
"""
max_taxonomy_length = 4
taxonomy_stack = []
for line in lines:
#bail out if it's a blank line
line = line.rstrip()
if not line:
continue
if line.startswith('#'): #line... | """Returns successive taxonomy entries from lines.
Format of return value is four levels of taxonomy (sometimes empty),
unique id, three-letter kegg code, abbreviated name, full name,
genus, species, and common name if present.
Taxonomic level information is implicit in the number of hashes read
... | identifier_body |
kegg_taxonomy.py | #!/usr/bin/env python
__author__ = "Jesse Zaneveld"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Jesse Zaneveld", "Rob Knight"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Jesse Zaneveld"
__email__ = "zaneveld@gmail.com"
__status__ = "Development"
from sys import argv
from... |
elif level > len(taxonomy_stack): #add level: assume sequential
taxonomy_stack.append(name)
else: #level must be less than stack length: truncate
del taxonomy_stack[level:]
taxonomy_stack[level-1] = name
else: #line defining an indiv... | taxonomy_stack[-1] = name | conditional_block |
video_utils.py | # Copyright 2022 The Scenic Authors.
#
# 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 w... | (x: jnp.ndarray,
n_sampled_frames: int) -> jnp.ndarray:
"""Sample frames from the input video."""
if x.ndim != 5:
raise ValueError('Input shape should be [bs, t, h, w, c].')
num_frames = x.shape[1]
if n_sampled_frames < num_frames:
t_start_idx = num_frames / (n_sampled_frames... | sample_frames_uniformly | identifier_name |
video_utils.py | # Copyright 2022 The Scenic Authors.
#
# 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 w... | """Sample frames from the input video."""
if x.ndim != 5:
raise ValueError('Input shape should be [bs, t, h, w, c].')
num_frames = x.shape[1]
if n_sampled_frames < num_frames:
t_start_idx = num_frames / (n_sampled_frames + 1)
t_step = t_start_idx
else:
t_start_idx = 0
t_step = 1
t_end_idx ... | identifier_body | |
video_utils.py | # Copyright 2022 The Scenic Authors.
#
# 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 w... |
t_end_idx = num_frames
temporal_indices = jnp.arange(t_start_idx, t_end_idx, t_step)
temporal_indices = jnp.round(temporal_indices).astype(jnp.int32)
temporal_indices = jnp.minimum(temporal_indices, num_frames - 1)
return x[:, temporal_indices] # [n, t_s, in_h, in_w, c]
| t_start_idx = 0
t_step = 1 | conditional_block |
video_utils.py | # Copyright 2022 The Scenic Authors.
#
# 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 w... | t_start_idx = num_frames / (n_sampled_frames + 1)
t_step = t_start_idx
else:
t_start_idx = 0
t_step = 1
t_end_idx = num_frames
temporal_indices = jnp.arange(t_start_idx, t_end_idx, t_step)
temporal_indices = jnp.round(temporal_indices).astype(jnp.int32)
temporal_indices = jnp.minimum(temporal_... | if x.ndim != 5:
raise ValueError('Input shape should be [bs, t, h, w, c].')
num_frames = x.shape[1]
if n_sampled_frames < num_frames: | random_line_split |
mod.rs | use std::hash::{Hash, Hasher};
use std::hash::sip::SipHasher;
static LOG_MAX_SIZE: uint = 21;
pub static MAX_SIZE: uint = 1 << LOG_MAX_SIZE;
pub fn hash<T: Hash>(s: &T, k1: u64, k2: u64) -> (uint, uint, uint) |
pub fn displace(f1: uint, f2: uint, d1: uint, d2: uint) -> uint {
d2 + f1 * d1 + f2
}
| {
let hash = SipHasher::new_with_keys(k1, k2).hash(s);
let mask = (MAX_SIZE - 1) as u64;
((hash & mask) as uint,
((hash >> LOG_MAX_SIZE) & mask) as uint,
((hash >> (2 * LOG_MAX_SIZE)) & mask) as uint)
} | identifier_body |
mod.rs | use std::hash::{Hash, Hasher};
use std::hash::sip::SipHasher;
static LOG_MAX_SIZE: uint = 21;
pub static MAX_SIZE: uint = 1 << LOG_MAX_SIZE;
pub fn | <T: Hash>(s: &T, k1: u64, k2: u64) -> (uint, uint, uint) {
let hash = SipHasher::new_with_keys(k1, k2).hash(s);
let mask = (MAX_SIZE - 1) as u64;
((hash & mask) as uint,
((hash >> LOG_MAX_SIZE) & mask) as uint,
((hash >> (2 * LOG_MAX_SIZE)) & mask) as uint)
}
pub fn displace(f1: uint, f2: uint, ... | hash | identifier_name |
mod.rs | use std::hash::{Hash, Hasher};
use std::hash::sip::SipHasher;
static LOG_MAX_SIZE: uint = 21;
pub static MAX_SIZE: uint = 1 << LOG_MAX_SIZE; | ((hash & mask) as uint,
((hash >> LOG_MAX_SIZE) & mask) as uint,
((hash >> (2 * LOG_MAX_SIZE)) & mask) as uint)
}
pub fn displace(f1: uint, f2: uint, d1: uint, d2: uint) -> uint {
d2 + f1 * d1 + f2
} |
pub fn hash<T: Hash>(s: &T, k1: u64, k2: u64) -> (uint, uint, uint) {
let hash = SipHasher::new_with_keys(k1, k2).hash(s);
let mask = (MAX_SIZE - 1) as u64;
| random_line_split |
SourcesList.js | /*
Copyright 2010-2012 Infracom & Eurotechnia (support@webcampak.com)
This file is part of the Webcampak project.
Webcampak 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 (a... | alias : 'widget.statssourceslistpicturesizes',
store: 'permissions.sources.Sources',
name: 'source',
valueField: 'id',
displayField: 'name',
typeAhead: true,
emptyText: i18n.gettext('Select another source...'),
style: 'text-align: center;',
width: 315
}); | */
console.log('Log: Load: Webcampak.view.dashboard.sourcepicturesizes.SourcesList');
//var rowEditing = Ext.create('Ext.grid.plugin.RowEditing');
Ext.define('Webcampak.view.dashboard.sourcepicturesizes.SourcesList' ,{
extend: 'Ext.form.ComboBox', | random_line_split |
AddNewRolesController.js | Panel.getRootNode();
/*for(i=0;i<rawData.length;i++){
data=rawData[i];
var fChild=data.children;*/
var fChild=rawData;
for(var x1=0;x1<fChild.length;x1++)
{
this.addChild(rootNode,fChild[x1]);
}
//} /**Use this for loop if menu list order is changed **/
... | read :true,
}
child["expanded"]=true;
child["isRead"]=true;
child["isWrite"]=true;
child["isExecute"]=false;
/** here we are not getting does the menu is head or not from db so i am adding headMenu property here to identify it**/
child["isHeadMenu"] = true;
var... | text:node.text,
menuId:node.menuId,
icon : 'images/folder-database-icon.png', | random_line_split |
AddNewRolesController.js | )
child.set(property,checked);
}
}
},
// Propagate change upwards (if all siblings are the same, update parent).
updateParentCheckedStatus : function (current, property, checked) {
debugger;
if (current.parentNode.data.isHeadMenu) {
debugger;
var parent = current.parentNode;... | {
Ext.Msg.alert('Success',"Data Saved Successfully");
rolesTree=currentObject.me.getView().up().up().down('#rolesTree');
rolesTree.store.load();
currentObject.me.onResetRolesClick();
} | conditional_block | |
demo_gevent_only.py | #! /usr/local/bin/stackless2.6
# by pts@fazekas.hu at Fri Jun 17 14:08:07 CEST 2011
"""Demo for hosting a gevent application with Stackless, without Syncless."""
__author__ = 'pts@fazekas.hu (Peter Szabo)'
import sys
# Import best_greenlet before gevent to add greenlet emulation for Stackless
# if necessary.
import... | # This is to demonstrate the error reporting and recovery behavior of gevent:
# We get an error message like this, and the process execution continues:
#
# Traceback (most recent call last):
# File "/usr/local/lib/python2.6/site-packages/gevent/greenlet.py", line 388, in run
# result = self._run... | print >>sys.stderr, 'info: connection from %r, handled by %r' % (
addr, gevent.hub.greenlet.getcurrent())
f = client_socket.makefile()
# Read HTTP request.
line1 = None
while True:
line = f.readline().rstrip('\r\n')
if not line: # Empty line, end of HTTP request.
break
if line1 is None... | identifier_body |
demo_gevent_only.py | #! /usr/local/bin/stackless2.6
# by pts@fazekas.hu at Fri Jun 17 14:08:07 CEST 2011
"""Demo for hosting a gevent application with Stackless, without Syncless."""
__author__ = 'pts@fazekas.hu (Peter Szabo)'
import sys
# Import best_greenlet before gevent to add greenlet emulation for Stackless
# if necessary.
import... | (object):
__slots__ = ['seed']
def __init__(self, seed=0):
self.seed = int(seed) & 0xffffffff
def next(self):
"""Generate a 32-bit unsigned random number."""
# http://en.wikipedia.org/wiki/Linear_congruential_generator
self.seed = (
((1664525 * self.seed) & 0xffffffff) + 1013904223) & 0xff... | Lprng | identifier_name |
demo_gevent_only.py | #! /usr/local/bin/stackless2.6
# by pts@fazekas.hu at Fri Jun 17 14:08:07 CEST 2011
"""Demo for hosting a gevent application with Stackless, without Syncless."""
__author__ = 'pts@fazekas.hu (Peter Szabo)'
import sys
# Import best_greenlet before gevent to add greenlet emulation for Stackless
# if necessary.
import... | assert 0, 'unreached' | gevent.hub.spawn_raw(GeventListener, server_socket)
# Run the gevent main loop indefinitely. This is not a requirement, we
# could to non-blocking Syncless operations instead right here for a long
# time.
syncless.best_greenlet.gevent_hub_main() | random_line_split |
demo_gevent_only.py | #! /usr/local/bin/stackless2.6
# by pts@fazekas.hu at Fri Jun 17 14:08:07 CEST 2011
"""Demo for hosting a gevent application with Stackless, without Syncless."""
__author__ = 'pts@fazekas.hu (Peter Szabo)'
import sys
# Import best_greenlet before gevent to add greenlet emulation for Stackless
# if necessary.
import... |
if line1 is None:
line1 = line
# Parse HTTP request.
# Please note that an assertion here doesn't abort the server.
items = line1.split(' ')
assert 3 == len(items)
assert items[2] in ('HTTP/1.0', 'HTTP/1.1')
assert items[0] == 'GET'
assert items[1].startswith('/')
# This is to demonstrate th... | break | conditional_block |
searching.rs | use criterion::Criterion;
use criterion::{criterion_group, criterion_main};
use futures::stream::StreamExt;
use mimir::domain::model::configuration;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::fs::File;
use mimir::adapters::primary::bragi::api::DEFAULT_LIMIT_RESULT_ES;
use mimir::adapters::... | .await
.unwrap();
download::ntfs("fr-idf").await.unwrap();
// false: don't force regenerate admins for 'ile-de-france'
cosmogony::generate("ile-de-france", false).await.unwrap();
// true: force reindex admins on bench dataset for 'ile-de-france'
cosmogony:... | {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(6)
.enable_time()
.enable_io()
.build()
.unwrap();
rt.block_on(async {
docker::initialize()
.await
.expect("elasticsearch docker initialization");
let config = ... | identifier_body |
searching.rs | use criterion::Criterion;
use criterion::{criterion_group, criterion_main};
use futures::stream::StreamExt;
use mimir::domain::model::configuration;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::fs::File;
use mimir::adapters::primary::bragi::api::DEFAULT_LIMIT_RESULT_ES;
use mimir::adapters::... | )
.await
.unwrap();
}
})
.await;
})
});
});
group.finish();
}
#[derive(Debug, Serialize, Deserialize)]
struct Record {
pub quer... | DEFAULT_LIMIT_RESULT_ES,
None, | random_line_split |
searching.rs | use criterion::Criterion;
use criterion::{criterion_group, criterion_main};
use futures::stream::StreamExt;
use mimir::domain::model::configuration;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::fs::File;
use mimir::adapters::primary::bragi::api::DEFAULT_LIMIT_RESULT_ES;
use mimir::adapters::... | {
pub query: String,
pub lon: Option<String>,
pub lat: Option<String>,
pub limit: Option<String>,
pub expected_housenumber: Option<String>,
pub expected_street: Option<String>,
pub expected_city: Option<String>,
pub expected_postcode: Option<String>,
}
criterion_group! {
name = ben... | Record | identifier_name |
QuestionService.js | function QuestionService($interval, Restangular) {
this.question = Restangular.all('Note');
var _this = this, errorCount = 0, running = true;
this.questions = [];
this.selectedQuestion;
function questionsReceived(questions) {
errorCount = 0;
if (_this.questions.length != questions.length) {
// Updating the ... |
}, 100);
}
app.service('questionService', QuestionService); | {
_this.getQuestions();
} | conditional_block |
QuestionService.js | function QuestionService($interval, Restangular) {
this.question = Restangular.all('Note');
var _this = this, errorCount = 0, running = true;
this.questions = [];
this.selectedQuestion;
function questionsReceived(questions) {
errorCount = 0;
if (_this.questions.length != questions.length) { | _this.questions.push(value)
});
} else {
angular.forEach(questions, function(value, key) {
_this.questions[key].voteCount = value.voteCount
})
}
}
function questionsFailed(question) {
running = !(++errorCount > 5);
}
this.add = function(item){
return _this.question.post(item);
}
this.... | // Updating the lists seemed to help with performance.
while(_this.questions.length > 0) {
_this.questions.pop();
}
angular.forEach(questions, function(value) { | random_line_split |
QuestionService.js | function QuestionService($interval, Restangular) {
this.question = Restangular.all('Note');
var _this = this, errorCount = 0, running = true;
this.questions = [];
this.selectedQuestion;
function questionsReceived(questions) {
errorCount = 0;
if (_this.questions.length != questions.length) {
// Updating the ... |
this.add = function(item){
return _this.question.post(item);
}
this.getQuestions = function() {
this.question.getList().then(questionsReceived, questionsFailed);
}
this.getQuestion = function(id) {
return this.questions[id];
}
//TODO: Very inefficient some of these issues will be addressed in 2.0
var clo... | {
running = !(++errorCount > 5);
} | identifier_body |
QuestionService.js | function QuestionService($interval, Restangular) {
this.question = Restangular.all('Note');
var _this = this, errorCount = 0, running = true;
this.questions = [];
this.selectedQuestion;
function | (questions) {
errorCount = 0;
if (_this.questions.length != questions.length) {
// Updating the lists seemed to help with performance.
while(_this.questions.length > 0) {
_this.questions.pop();
}
angular.forEach(questions, function(value) {
_this.questions.push(value)
});
} else {
an... | questionsReceived | identifier_name |
param.ts | /*
Copyright (c) Université catholique Louvain. All rights reserved
Authors : Daubry Benjamin & Marchesini Bruno
Date : July 2018
This file is part of UCLCampus
Licensed under the GPL 3.0 license. See LICENSE file in the project root for full license information.
UCLCampus is free software: ... | }
|
const type: any = "radio";
return [
this.getCampusChoiceInput('Louvain-la-Neuve', 'LLN', check),
this.getCampusChoiceInput('Woluwé', 'Woluwe', check),
this.getCampusChoiceInput('Mons', 'Mons', check),
{
type: type,
label: 'Tournai',
value: 'Tournai',
disa... | identifier_body |
param.ts | /*
Copyright (c) Université catholique Louvain. All rights reserved
Authors : Daubry Benjamin & Marchesini Bruno
Date : July 2018
This file is part of UCLCampus
Licensed under the GPL 3.0 license. See LICENSE file in the project root for full license information.
UCLCampus is free software: ... | import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { UserService } from '../../services/utils-services/user-service';
import { UtilsService } from '../../services/utils-services/utils-service';
import { SettingsProvider } from "../../services/utils-services/settin... | along with UCLCampus. If not, see <http://www.gnu.org/licenses/>.
*/
import { AlertController, ModalController, NavController, NavParams } from '@ionic/angular';
import { animate, state, style, transition, trigger } from '@angular/animations'; | random_line_split |
param.ts | /*
Copyright (c) Université catholique Louvain. All rights reserved
Authors : Daubry Benjamin & Marchesini Bruno
Date : July 2018
This file is part of UCLCampus
Licensed under the GPL 3.0 license. See LICENSE file in the project root for full license information.
UCLCampus is free software: ... | ) {
const languageAlert = await this.alertCtrl.create({
header: this.utilsService.getText('HOME', 'SETTING2'),
message: this.utilsService.getText('HOME', 'MESSAGE2'),
cssClass: this.selectedTheme,
inputs: this.utilsService.getLanguageAlertInputs(this.translateService.currentLang),
butt... | anguage_choice( | identifier_name |
param.ts | /*
Copyright (c) Université catholique Louvain. All rights reserved
Authors : Daubry Benjamin & Marchesini Bruno
Date : July 2018
This file is part of UCLCampus
Licensed under the GPL 3.0 license. See LICENSE file in the project root for full license information.
UCLCampus is free software: ... | }
async campus_choice() {
const settingsAlert = await this.alertCtrl.create({
header: this.utilsService.getText('HOME', 'SETTING1'),
message: this.utilsService.getText('HOME', 'MESSAGE'),
inputs: this.getSettingsInputs(this.userS.campus),
cssClass: this.selectedTheme,
buttons: [
... |
this.settings.setActiveTheme('dark-theme');
}
| conditional_block |
literals.rs | fn | () {
// 整数相加
println!("1 + 2 = {}", 1u32 + 2);
// 整数相减
println!("1 - 2 = {}", 1i32 - 2);
// 试一试 ^ 尝试将 `1i32` 改为 `1u32`,体会为什么类型声明这么重要
// 短路的布尔类型的逻辑运算
println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false);
println!("NOT true is {}", !true);
... | main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.