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
detect_outlier.py
import numpy as np import sys sys.path.append("../Pipeline/Audio/Pipeline/") from AudioPipe.features import mfcc # Feature Extraction Module, part of the shared preprocessing import AudioPipe.speaker.recognition as SR # Speaker Recognition Module import scipy.io.wavfile as wav import commands, os import json import ar...
with open(list_fn, "w") as fh: fh.write(to_json(new_ls, indent=2)) stat_dict[spk_name]["clip_num"]=len(clip_ls) stat_dict[spk_name]["zpos_num"]=sum(z_score>0) stat_dict[spk_name]["total_duration"]=sum([get_sec(clp["duration"]) for clp in new_ls]) stat_dict[spk_name]["clean_duration"]=sum([g...
new_ls[i]["zscore"] = z_score[i]
conditional_block
activity.js
(function () { 'use strict'; var module = angular.module('fim.base'); module.config(function($routeProvider) { $routeProvider .when('/activity/:engine/:section/:period', { templateUrl: 'partials/activity.html', controller: 'ActivityController' }); }); module.controller('ActivityController', fun...
}); if ($scope.showTransactionFilter) { $scope.filter.all = true; $scope.filter.payments = true; $scope.filter.messages = true; $scope.filter.aliases = true; $scope.filter.namespacedAliases = true; $scope.filter.polls = true; $scope.filter.accountInfo = true; $scope.filter.announce...
{ stopWatching = true; var formatted = dateFilter(newValue, $scope.format); $location.path('/activity/'+$scope.paramEngine+'/'+$scope.paramSection+'/'+formatted); }
conditional_block
activity.js
(function () { 'use strict'; var module = angular.module('fim.base'); module.config(function($routeProvider) { $routeProvider .when('/activity/:engine/:section/:period', { templateUrl: 'partials/activity.html', controller: 'ActivityController' }); }); module.controller('ActivityController', fun...
$scope.filterChanged = function () { $scope.provider.applyFilter($scope.filter); } } $scope.loadStatistics = function (engine, collapse_var) { $scope[collapse_var] = !$scope[collapse_var]; if (!$scope[collapse_var]) { if (!$scope.statistics[engine]) { var api = nxt.get(engine);...
}); }
random_line_split
set_watch_mode.rs
use std::io; use super::super::{WriteTo, WatchMode, WatchModeReader, WriteResult, Reader, ReaderStatus, MessageInner, Message}; #[derive(Debug, Eq, PartialEq, Clone)] pub struct SetWatchMode { mode: WatchMode, } #[derive(Debug)] pub struct SetWatchModeReader { inner: WatchModeReader, } impl SetWatchMode { ...
} impl MessageInner for SetWatchMode { #[inline] fn wrap(self) -> Message { Message::SetWatchMode(self) } } impl Reader<SetWatchMode> for SetWatchModeReader { fn resume<R>(&mut self, input: &mut R) -> io::Result<ReaderStatus<SetWatchMode>> where R: io::Read { let status = self.inner.r...
{ SetWatchModeReader { inner: WatchMode::reader() } }
identifier_body
set_watch_mode.rs
use std::io; use super::super::{WriteTo, WatchMode, WatchModeReader, WriteResult, Reader, ReaderStatus, MessageInner, Message}; #[derive(Debug, Eq, PartialEq, Clone)] pub struct SetWatchMode { mode: WatchMode, } #[derive(Debug)] pub struct SetWatchModeReader { inner: WatchModeReader, } impl SetWatchMode { ...
(mode: WatchMode) -> Self { SetWatchMode { mode } } pub fn mode(&self) -> WatchMode { self.mode } pub fn reader() -> SetWatchModeReader { SetWatchModeReader { inner: WatchMode::reader() } } } impl MessageInner for SetWatchMode { #[inline] fn wrap(self) -> Message {...
new
identifier_name
set_watch_mode.rs
use std::io; use super::super::{WriteTo, WatchMode, WatchModeReader, WriteResult, Reader, ReaderStatus, MessageInner, Message}; #[derive(Debug, Eq, PartialEq, Clone)] pub struct SetWatchMode { mode: WatchMode, } #[derive(Debug)] pub struct SetWatchModeReader { inner: WatchModeReader, } impl SetWatchMode { ...
ReaderStatus::Pending, ReaderStatus::Complete(Message::SetWatchMode(SetWatchMode::new(WatchMode::All))) }; } }
ReaderStatus::Pending,
random_line_split
SchedulerProfiling.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {PriorityLevel} from './SchedulerPriorities'; import {enableProfiling} from './SchedulerFeatureFlags'; im...
let eventLog = null; let eventLogIndex = 0; const TaskStartEvent = 1; const TaskCompleteEvent = 2; const TaskErrorEvent = 3; const TaskCancelEvent = 4; const TaskRunEvent = 5; const TaskYieldEvent = 6; const SchedulerSuspendEvent = 7; const SchedulerResumeEvent = 8; function logEvent(entries) { if (eventLog !== nul...
let eventLogSize = 0; let eventLogBuffer = null;
random_line_split
SchedulerProfiling.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {PriorityLevel} from './SchedulerPriorities'; import {enableProfiling} from './SchedulerFeatureFlags'; im...
--; if (eventLog !== null) { logEvent([TaskCompleteEvent, ms * 1000, task.id]); } } } export function markTaskCanceled( task: { id: number, priorityLevel: PriorityLevel, ... }, ms: number, ) { if (enableProfiling) { profilingState[QUEUE_SIZE]--; if (eventLog !== null) { ...
[QUEUE_SIZE]
identifier_name
SchedulerProfiling.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {PriorityLevel} from './SchedulerPriorities'; import {enableProfiling} from './SchedulerFeatureFlags'; im...
export function stopLoggingProfilingEvents(): ArrayBuffer | null { const buffer = eventLogBuffer; eventLogSize = 0; eventLogBuffer = null; eventLog = null; eventLogIndex = 0; return buffer; } export function markTaskStart( task: { id: number, priorityLevel: PriorityLevel, ... }, ms: num...
{ eventLogSize = INITIAL_EVENT_LOG_SIZE; eventLogBuffer = new ArrayBuffer(eventLogSize * 4); eventLog = new Int32Array(eventLogBuffer); eventLogIndex = 0; }
identifier_body
SchedulerProfiling.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {PriorityLevel} from './SchedulerPriorities'; import {enableProfiling} from './SchedulerFeatureFlags'; im...
} } export function markSchedulerUnsuspended(ms: number) { if (enableProfiling) { if (eventLog !== null) { logEvent([SchedulerResumeEvent, ms * 1000, mainThreadIdCounter]); } } }
{ logEvent([SchedulerSuspendEvent, ms * 1000, mainThreadIdCounter]); }
conditional_block
opportunity_kraken.py
from exchanges import helpers from exchanges import kraken from decimal import Decimal ### Kraken opportunities #### ARBITRAGE OPPORTUNITY 1 def
(): sellLTCbuyEUR = kraken.get_current_bid_LTCEUR() sellEURbuyXBT = kraken.get_current_ask_XBTEUR() sellXBTbuyLTC = kraken.get_current_ask_XBTLTC() opport = 1-((sellLTCbuyEUR/sellEURbuyBTX)*sellXBTbuyLTC) return Decimal(opport) def opportunity_2(): sellEURbuyLTC = kraken.get_current_ask_LTCEUR() sellLT...
opportunity_1
identifier_name
opportunity_kraken.py
from exchanges import helpers from exchanges import kraken from decimal import Decimal ### Kraken opportunities #### ARBITRAGE OPPORTUNITY 1
opport = 1-((sellLTCbuyEUR/sellEURbuyBTX)*sellXBTbuyLTC) return Decimal(opport) def opportunity_2(): sellEURbuyLTC = kraken.get_current_ask_LTCEUR() sellLTCbuyXBT = kraken.get_current_ask_XBTLTC() sellXBTbuyEUR = kraken.get_current_bid_XBTEUR() opport = 1-(((1/sellEURbuyLTC)/sellLTCbuyXBT)*sellXBTbuyEUR)...
def opportunity_1(): sellLTCbuyEUR = kraken.get_current_bid_LTCEUR() sellEURbuyXBT = kraken.get_current_ask_XBTEUR() sellXBTbuyLTC = kraken.get_current_ask_XBTLTC()
random_line_split
opportunity_kraken.py
from exchanges import helpers from exchanges import kraken from decimal import Decimal ### Kraken opportunities #### ARBITRAGE OPPORTUNITY 1 def opportunity_1(): sellLTCbuyEUR = kraken.get_current_bid_LTCEUR() sellEURbuyXBT = kraken.get_current_ask_XBTEUR() sellXBTbuyLTC = kraken.get_current_ask_XBTLTC() oppor...
sellEURbuyLTC = kraken.get_current_ask_LTCEUR() sellLTCbuyXBT = kraken.get_current_ask_XBTLTC() sellXBTbuyEUR = kraken.get_current_bid_XBTEUR() opport = 1-(((1/sellEURbuyLTC)/sellLTCbuyXBT)*sellXBTbuyEUR) return Decimal(opport)
identifier_body
lib.fluidContent.ts
# Default configuration for content elements which are using FLUIDTEMPLATE directly lib.fluidContent > lib.fluidContent = FLUIDTEMPLATE lib.fluidContent { templateName = Default templateRootPaths { 0 = EXT:fluid_styled_content/Resources/Private/Templates/ 10 = {$styles.templates.templateRootPath} } partialRootP...
media { popup { bodyTag = <body style="margin:0; background:#fff;"> wrap = <a href="javascript:close();"> | </a> width = {$styles.content.textmedia.linkWrap.width} height = {$styles.content.textmedia.linkWrap.height} JSwindow = 1 JSwindow { newWindow = {$styles.content.textmedia.linkW...
} settings { defaultHeaderType = {$styles.content.defaultHeaderType}
random_line_split
dev-server.ts
import express, { Router } from 'express'; import { Builder, logConfig, Options } from '@storybook/core-common'; import { getMiddleware } from './utils/middleware'; import { getServerAddresses } from './utils/server-address'; import { getServer } from './utils/server-init'; import { useStatics } from './utils/server-...
const { port, host } = options; const proto = options.https ? 'https' : 'http'; const { address, networkAddress } = getServerAddresses(port, host, proto); await new Promise<void>((resolve, reject) => { // FIXME: Following line doesn't match TypeScript signature at all 🤔 // @ts-ignore server.liste...
{ const startTime = process.hrtime(); const app = express(); const server = await getServer(app, options); if (typeof options.extendServer === 'function') { options.extendServer(server); } app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-...
identifier_body
dev-server.ts
import express, { Router } from 'express'; import { Builder, logConfig, Options } from '@storybook/core-common'; import { getMiddleware } from './utils/middleware'; import { getServerAddresses } from './utils/server-address'; import { getServer } from './utils/server-init'; import { useStatics } from './utils/server-...
}
return { previewResult, managerResult, address, networkAddress };
random_line_split
dev-server.ts
import express, { Router } from 'express'; import { Builder, logConfig, Options } from '@storybook/core-common'; import { getMiddleware } from './utils/middleware'; import { getServerAddresses } from './utils/server-address'; import { getServer } from './utils/server-init'; import { useStatics } from './utils/server-...
(options: Options) { const startTime = process.hrtime(); const app = express(); const server = await getServer(app, options); if (typeof options.extendServer === 'function') { options.extendServer(server); } app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.head...
storybookDevServer
identifier_name
dev-server.ts
import express, { Router } from 'express'; import { Builder, logConfig, Options } from '@storybook/core-common'; import { getMiddleware } from './utils/middleware'; import { getServerAddresses } from './utils/server-address'; import { getServer } from './utils/server-init'; import { useStatics } from './utils/server-...
const preview = options.ignorePreview ? Promise.resolve() : previewBuilder.start({ startTime, options, router, }); const manager = managerBuilder.start({ startTime, options, router, }); const [previewResult, managerResult] = await Promise.all([ preview, ...
logConfig('Preview webpack config', await previewBuilder.getConfig(options)); logConfig('Manager webpack config', await managerBuilder.getConfig(options)); }
conditional_block
005_tle_error.py
class Solution(object): def longestPalindrome(self, s): max_len = 0 max_str = '' if len(s) <= 2: return s for i, ch in enumerate(s): delta = 1 count = 0 # center is ch while (i - delta) >= 0 and (i + delta) < len(s): ...
# center is ch right delta = 0.5 count = 0 j = i + 0.5 while (j - delta) >= 0 and (j + delta) < len(s): if s[int(j - delta)] != s[int(j + delta)]: break count += 1 delta += 1 if c...
max_str = s[i-count:i+1+count]
random_line_split
005_tle_error.py
class Solution(object): def longestPalindrome(self, s): max_len = 0 max_str = '' if len(s) <= 2: return s for i, ch in enumerate(s): delta = 1 count = 0 # center is ch while (i - delta) >= 0 and (i + delta) < len(s): ...
s = Solution() s.test()
conditional_block
005_tle_error.py
class Solution(object): def longestPalindrome(self, s): max_len = 0 max_str = '' if len(s) <= 2: return s for i, ch in enumerate(s): delta = 1 count = 0 # center is ch while (i - delta) >= 0 and (i + delta) < len(s): ...
(self): assert self.longestPalindrome('a') == 'a' assert self.longestPalindrome('abcba') == 'abcba' assert self.longestPalindrome('eabcbae') == 'eabcbae' assert self.longestPalindrome('abba') == 'abba' assert self.longestPalindrome('abbc') == 'bb' assert self.longestPalin...
test
identifier_name
005_tle_error.py
class Solution(object): def longestPalindrome(self, s): max_len = 0 max_str = '' if len(s) <= 2: return s for i, ch in enumerate(s): delta = 1 count = 0 # center is ch while (i - delta) >= 0 and (i + delta) < len(s): ...
if __name__ == '__main__': s = Solution() s.test()
assert self.longestPalindrome('a') == 'a' assert self.longestPalindrome('abcba') == 'abcba' assert self.longestPalindrome('eabcbae') == 'eabcbae' assert self.longestPalindrome('abba') == 'abba' assert self.longestPalindrome('abbc') == 'bb' assert self.longestPalindrome('dbabba') ...
identifier_body
settings.py
""" Django settings for paulpruitt_net project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...
# Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.6/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = '/srv/www/site/...
}
random_line_split
violations.py
ends=True) offset = self.definition.start # type: ignore lines_stripped = list( reversed(list(dropwhile(is_blank, reversed(lines)))) ) numbers_width = len(str(offset + len(lines_stripped))) line_format = f'{{:{numbers_width}}}:{{}}' for n, line in enumerate(l...
@classmethod def to_rst(cls) -> str: """Output the registry as reStructuredText, for documentation.""" max_len = max( len(error.short_desc) for group in cls.groups for error in group.errors ) sep_line = '+' + 6 * '-' + '+' + '-' * (max_len + ...
"""Yield all registered codes.""" for group in cls.groups: for error in group.errors: yield error.code
identifier_body
violations.py
ends=True) offset = self.definition.start # type: ignore lines_stripped = list( reversed(list(dropwhile(is_blank, reversed(lines)))) ) numbers_width = len(str(offset + len(lines_stripped))) line_format = f'{{:{numbers_width}}}:{{}}' for n, line in enumerate(l...
'D215', 'Section underline is over-indented', 'in section {0!r}', ) D3xx = ErrorRegistry.create_group('D3', 'Quotes Issues') D300 = D3xx.create_error( 'D300', 'Use """triple double quotes"""', 'found {0}-quotes', ) D301 = D3xx.create_error( 'D301', 'Use r""" if any backslashes in a docs...
D215 = D2xx.create_error(
random_line_split
violations.py
ends=True) offset = self.definition.start # type: ignore lines_stripped = list( reversed(list(dropwhile(is_blank, reversed(lines)))) ) numbers_width = len(str(offset + len(lines_stripped))) line_format = f'{{:{numbers_width}}}:{{}}' for n, line in enumerate(l...
@classmethod def to_rst(cls) -> str: """Output the registry as reStructuredText, for documentation.""" max_len = max( len(error.short_desc) for group in cls.groups for error in group.errors ) sep_line = '+' + 6 * '-' + '+' + '-' * (max_len + ...
for error in group.errors: yield error.code
conditional_block
violations.py
(cls, prefix: str, name: str) -> ErrorGroup: """Create a new error group and return it.""" group = cls.ErrorGroup(prefix, name) cls.groups.append(group) return group @classmethod def get_error_codes(cls) -> Iterable[str]: """Yield all registered codes.""" for gro...
__getattr__
identifier_name
VoiceNetwork.tsx
import React, { useMemo, useState } from 'react'; import { TMemo } from '@shared/components/TMemo'; import { useRTCRoomClientContext } from '@rtc/RoomContext'; import { useAsyncTimeout } from '@shared/hooks/useAsyncTimeout'; import _get from 'lodash/get'; import filesize from 'filesize'; import { useTranslation } from ...
() => { return { // 即生产者的传输通道在远程接收到的信息 upstream: getStreamRate( _get(remoteStats, ['sendRemoteStats', 0, 'recvBitrate'], 0) ), // 即消费者的传输通道在远程发送的信息 downstream: getStreamRate( _get(remoteStats, ['recvRemoteStats', 0, 'sendBitrate'], 0) ), }; }, [remoteStats])...
ient .getSendTransportRemoteStats() .catch(() => {}); const recvRemoteStats = await client .getRecvTransportRemoteStats() .catch(() => {}); setRemoteStats({ sendRemoteStats, recvRemoteStats, }); } }, 2000); const bitrate = useMemo(
conditional_block
VoiceNetwork.tsx
import React, { useMemo, useState } from 'react'; import { TMemo } from '@shared/components/TMemo'; import { useRTCRoomClientContext } from '@rtc/RoomContext'; import { useAsyncTimeout } from '@shared/hooks/useAsyncTimeout'; import _get from 'lodash/get'; import filesize from 'filesize'; import { useTranslation } from ...
port const VoiceNetwork: React.FC = TMemo(() => { const { client } = useRTCRoomClientContext(); const [remoteStats, setRemoteStats] = useState<any>({}); const { t } = useTranslation(); useAsyncTimeout(async () => { if (client) { const sendRemoteStats = await client .getSendTransportRemoteStat...
er(bitrate) / 8, { bits: true }) + '/s'; } /** * 语音网络状态显示 */ ex
identifier_body
VoiceNetwork.tsx
import React, { useMemo, useState } from 'react'; import { TMemo } from '@shared/components/TMemo'; import { useRTCRoomClientContext } from '@rtc/RoomContext'; import { useAsyncTimeout } from '@shared/hooks/useAsyncTimeout'; import _get from 'lodash/get'; import filesize from 'filesize'; import { useTranslation } from ...
return ( <pre> {t('上传')}: {bitrate.upstream} {t('下载')}: {bitrate.downstream} </pre> ); }); VoiceNetwork.displayName = 'VoiceNetwork';
_get(remoteStats, ['recvRemoteStats', 0, 'sendBitrate'], 0) ), }; }, [remoteStats]);
random_line_split
VoiceNetwork.tsx
import React, { useMemo, useState } from 'react'; import { TMemo } from '@shared/components/TMemo'; import { useRTCRoomClientContext } from '@rtc/RoomContext'; import { useAsyncTimeout } from '@shared/hooks/useAsyncTimeout'; import _get from 'lodash/get'; import filesize from 'filesize'; import { useTranslation } from ...
g { return filesize(Number(bitrate) / 8, { bits: true }) + '/s'; } /** * 语音网络状态显示 */ export const VoiceNetwork: React.FC = TMemo(() => { const { client } = useRTCRoomClientContext(); const [remoteStats, setRemoteStats] = useState<any>({}); const { t } = useTranslation(); useAsyncTimeout(async () => { ...
umber): strin
identifier_name
rayon.rs
use crate::{ProgressBar, ProgressBarIter}; use rayon::iter::{ plumbing::{Consumer, Folder, Producer, ProducerCallback, UnindexedConsumer}, IndexedParallelIterator, ParallelIterator, }; use std::convert::TryFrom; /// Wraps a Rayon parallel iterator. /// /// See [`ProgressIterator`](trait.ProgressIterator.html) ...
fn drive<C: Consumer<Self::Item>>(self, consumer: C) -> <C as Consumer<Self::Item>>::Result { let consumer = ProgressConsumer::new(consumer, self.progress); self.it.drive(consumer) } fn with_producer<CB: ProducerCallback<Self::Item>>( self, callback: CB, ) -> <CB as Pr...
{ self.it.len() }
identifier_body
rayon.rs
use crate::{ProgressBar, ProgressBarIter}; use rayon::iter::{ plumbing::{Consumer, Folder, Producer, ProducerCallback, UnindexedConsumer}, IndexedParallelIterator, ParallelIterator, }; use std::convert::TryFrom; /// Wraps a Rayon parallel iterator. /// /// See [`ProgressIterator`](trait.ProgressIterator.html) ...
(self, item: T) -> Self { self.progress.inc(1); ProgressFolder { base: self.base.consume(item), progress: self.progress, } } fn complete(self) -> C::Result { self.base.complete() } fn full(&self) -> bool { self.base.full() } } impl<S...
consume
identifier_name
rayon.rs
use crate::{ProgressBar, ProgressBarIter}; use rayon::iter::{ plumbing::{Consumer, Folder, Producer, ProducerCallback, UnindexedConsumer}, IndexedParallelIterator, ParallelIterator, }; use std::convert::TryFrom; /// Wraps a Rayon parallel iterator. /// /// See [`ProgressIterator`](trait.ProgressIterator.html) ...
} impl<T, C: Consumer<T>> Consumer<T> for ProgressConsumer<C> { type Folder = ProgressFolder<C::Folder>; type Reducer = C::Reducer; type Result = C::Result; fn split_at(self, index: usize) -> (Self, Self, Self::Reducer) { let (left, right, reducer) = self.base.split_at(index); ( ...
fn new(base: C, progress: ProgressBar) -> Self { ProgressConsumer { base, progress } }
random_line_split
class_physics_component.js
var class_physics_component = [ [ "createXmlNode", "class_physics_component.html#a5a2e3761a13d45a4dd38fe3b69253332", null ], [ "destroyDispatcher", "class_physics_component.html#a3c17f238e0ea725fc91a151591bf9510", null ], [ "getPosition", "class_physics_component.html#aeee07d4204bae0ff7747f5c0009907a1", nul...
[ "myPhysicsSystem", "class_physics_component.html#a975c62b57bcba88f3738edfe308da17b", null ] ];
random_line_split
view.tree.js
class TreeView { constructor($dom, store, adapter) { this.store = store; this.adapter = adapter; this.$view = $dom.find('.octotree_treeview'); this.$tree = this.$view .find('.octotree_view_body') .on('click.jstree', '.jstree-open>a', ({target}) => { setTimeout(() => { thi...
if ($jstree.get_node(nodeId)) { $jstree.deselect_all(); $jstree.select_node(nodeId); $jstree.open_node(nodeId, () => { if (++index < paths.length) { selectPath(paths, index); } }); } } } }
} function selectPath(paths, index = 0) { const nodeId = NODE_PREFIX + paths[index];
random_line_split
view.tree.js
class TreeView { constructor($dom, store, adapter) { this.store = store; this.adapter = adapter; this.$view = $dom.find('.octotree_treeview'); this.$tree = this.$view .find('.octotree_view_body') .on('click.jstree', '.jstree-open>a', ({target}) => { setTimeout(() => { thi...
(folder) { folder.sort((a, b) => { if (a.type === b.type) return a.text === b.text ? 0 : a.text < b.text ? -1 : 1; return a.type === 'blob' ? 1 : -1; }); folder.forEach((item) => { if (item.type === 'tree' && item.children !== true && item.children.length > 0) { this._sort(item.ch...
_sort
identifier_name
view.tree.js
class TreeView { constructor($dom, store, adapter) { this.store = store; this.adapter = adapter; this.$view = $dom.find('.octotree_treeview'); this.$tree = this.$view .find('.octotree_view_body') .on('click.jstree', '.jstree-open>a', ({target}) => { setTimeout(() => { thi...
} } }
{ $jstree.deselect_all(); $jstree.select_node(nodeId); $jstree.open_node(nodeId, () => { if (++index < paths.length) { selectPath(paths, index); } }); }
conditional_block
view.tree.js
class TreeView { constructor($dom, store, adapter) { this.store = store; this.adapter = adapter; this.$view = $dom.find('.octotree_treeview'); this.$tree = this.$view .find('.octotree_view_body') .on('click.jstree', '.jstree-open>a', ({target}) => { setTimeout(() => { thi...
_collapse(folder) { return folder.map((item) => { if (item.type === 'tree') { item.children = this._collapse(item.children); if (item.children.length === 1 && item.children[0].type === 'tree') { const onlyChild = item.children[0]; onlyChild.text = item.text + '/' + only...
{ folder.sort((a, b) => { if (a.type === b.type) return a.text === b.text ? 0 : a.text < b.text ? -1 : 1; return a.type === 'blob' ? 1 : -1; }); folder.forEach((item) => { if (item.type === 'tree' && item.children !== true && item.children.length > 0) { this._sort(item.children); ...
identifier_body
statistic_spec.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular...
() { describe('statistic', () => { it('should calculate the mean', () => { expect(Statistic.calculateMean([])).toBeNaN(); expect(Statistic.calculateMean([1, 2, 3])).toBe(2.0); }); it('should calculate the standard deviation', () => { expect(Statistic.calculateStandardDeviation([], NaN)...
main
identifier_name
statistic_spec.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular...
expect(Statistic.calculateStandardDeviation([2, 4, 4, 4, 5, 5, 7, 9], 5)).toBe(2.0); }); it('should calculate the coefficient of variation', () => { expect(Statistic.calculateCoefficientOfVariation([], NaN)).toBeNaN(); expect(Statistic.calculateCoefficientOfVariation([1], 1)).toBe(0.0); ...
expect(Statistic.calculateStandardDeviation([1], 1)).toBe(0.0);
random_line_split
statistic_spec.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular...
it('should calculate the regression slope', () => { expect(Statistic.calculateRegressionSlope([], NaN, [], NaN)).toBeNaN(); expect(Statistic.calculateRegressionSlope([1], 1, [2], 2)).toBeNaN(); expect(Statistic.calculateRegressionSlope([1, 2], 1.5, [2, 4], 3)).toBe(2.0); }); }); }
{ describe('statistic', () => { it('should calculate the mean', () => { expect(Statistic.calculateMean([])).toBeNaN(); expect(Statistic.calculateMean([1, 2, 3])).toBe(2.0); }); it('should calculate the standard deviation', () => { expect(Statistic.calculateStandardDeviation([], NaN)).t...
identifier_body
edit.state.d.ts
import { Command } from '../command/command'; /** * Property that controls grid edit unit. * * * `'cell'` data is editable through the grid cells. * * `'row'` data is editable through the grid rows. * * `'null'` data is not editable. */ export declare type EditStateMode = null | 'cell' | 'row'; /** * Indicates...
/** * Object that contains `{columnKey: keyboardKeys}` map, that is used by q-grid to manage * when cancel command should be execute on key down event. */ cancelShortcuts: { [key: string]: string }; /** * Object that contains `{columnKey: keyboardKeys}` map, that is used by q-grid to manage * when enter c...
clear: Command;
random_line_split
edit.state.d.ts
import { Command } from '../command/command'; /** * Property that controls grid edit unit. * * * `'cell'` data is editable through the grid cells. * * `'row'` data is editable through the grid rows. * * `'null'` data is not editable. */ export declare type EditStateMode = null | 'cell' | 'row'; /** * Indicates...
{ /** * Property that controls grid edit unit. */ mode: EditStateMode; /** * Indicates if q-grid is in `'edit'` or in a `'view'` mode. */ status: EditStateStatus; /** * Property that controls grid edit behavior. */ method: EditStateMethod; /** * Allows to the grid user to control if cell or row...
EditState
identifier_name
loaders.py
""" Test cases for the template loaders Note: This test requires setuptools! """ from django.conf import settings if __name__ == '__main__': settings.configure() import unittest import sys import pkg_resources import imp import StringIO import os.path from django.template import TemplateDoesNotExist from djang...
unittest.main()
"Loading an existent template from an egg not included in INSTALLED_APPS should fail" settings.INSTALLED_APPS = [] self.assertRaises(TemplateDoesNotExist, lts_egg, "y.html") if __name__ == "__main__":
random_line_split
loaders.py
""" Test cases for the template loaders Note: This test requires setuptools! """ from django.conf import settings if __name__ == '__main__': settings.configure() import unittest import sys import pkg_resources import imp import StringIO import os.path from django.template import TemplateDoesNotExist from djang...
(self): settings.INSTALLED_APPS = self._old_installed_apps def test_empty(self): "Loading any template on an empty egg should fail" settings.INSTALLED_APPS = ['egg_empty'] self.assertRaises(TemplateDoesNotExist, lts_egg, "not-existing.html") def test_non_existing(self): ...
tearDown
identifier_name
loaders.py
""" Test cases for the template loaders Note: This test requires setuptools! """ from django.conf import settings if __name__ == '__main__': settings.configure() import unittest import sys import pkg_resources import imp import StringIO import os.path from django.template import TemplateDoesNotExist from djang...
def test_empty(self): "Loading any template on an empty egg should fail" settings.INSTALLED_APPS = ['egg_empty'] self.assertRaises(TemplateDoesNotExist, lts_egg, "not-existing.html") def test_non_existing(self): "Template loading fails if the template is not in the egg" ...
settings.INSTALLED_APPS = self._old_installed_apps
identifier_body
loaders.py
""" Test cases for the template loaders Note: This test requires setuptools! """ from django.conf import settings if __name__ == '__main__': settings.configure() import unittest import sys import pkg_resources import imp import StringIO import os.path from django.template import TemplateDoesNotExist from djang...
unittest.main()
conditional_block
gui.js
var gui={}; (function() { try { var open = require("open"); var fs = require("fs"); } catch(e) { var open = function(path) { window.open("file://"+path); } } var state = document.getElementById("state"), statemsg = document.getElementById("statemsg"), progress = document.getElementById("progress"),...
function insert_collision (idx, files, dist) { var row = table.insertRow(idx); row.dataset["dist"] = dist; for (var i=0; i<2; i++) { var cell = row.insertCell(i); var pathElem = document.createTextNode(files[i].dirname+"/"); var fileNameElem = document.createElement("b"); var sizeElem = document.cre...
{ if (size > 1e9) return ((size/1e8|0)/10) + " Gb"; else if (size > 1e6) return ((size/1e5|0)/10) + " Mb"; else if (size > 1e3) return ((size/1e2|0)/10) + " Kb"; else return size+" bytes"; }
identifier_body
gui.js
var gui={}; (function() { try { var open = require("open"); var fs = require("fs"); } catch(e) { var open = function(path) { window.open("file://"+path); } } var state = document.getElementById("state"), statemsg = document.getElementById("statemsg"), progress = document.getElementById("progress"),...
fileNameElem.textContent = files[i].stats.name; deleteBtn.textContent = "delete"; deleteBtn.addEventListener("click",function(e) { var path = e.target.parentElement.dataset["filepath"]; if (confirm("Delete "+path+"?")) { fs.unlink(path, function (err) { if (err) { alert("Unable to del...
cell.dataset["filepath"] = files[i].filepath; fileNameElem.addEventListener("click",function(e) { var path = e.target.parentElement.dataset["filepath"]; open(path); }, true);
random_line_split
gui.js
var gui={}; (function() { try { var open = require("open"); var fs = require("fs"); } catch(e) { var open = function(path) { window.open("file://"+path); } } var state = document.getElementById("state"), statemsg = document.getElementById("statemsg"), progress = document.getElementById("progress"),...
(size) { if (size > 1e9) return ((size/1e8|0)/10) + " Gb"; else if (size > 1e6) return ((size/1e5|0)/10) + " Mb"; else if (size > 1e3) return ((size/1e2|0)/10) + " Kb"; else return size+" bytes"; } function insert_collision (idx, files, dist) { var row = table.insertRow(idx); row.dataset["dist"] = dist; ...
readableSize
identifier_name
HumidTemp.js
const sensor = require('node-dht-sensor'); const logger = require('../logging/Logger'); /** * Reads pin 4 of the raspberry PI to obtain temperature and humidity information. * @return {Promise} A promise that will resolve with the results. In the * case where there was an error reading, will return a zero filled ob...
resolve({ temperature: temperature * 1.8 + 32, humidity: humidity}); }); }); }
{ logger.error("Could not read from the DHT sensor. " + err); return resolve({ temperature: 0, humidity: 0, error: err}); }
conditional_block
HumidTemp.js
const sensor = require('node-dht-sensor'); const logger = require('../logging/Logger'); /** * Reads pin 4 of the raspberry PI to obtain temperature and humidity information. * @return {Promise} A promise that will resolve with the results. In the * case where there was an error reading, will return a zero filled ob...
resolve({ temperature: temperature * 1.8 + 32, humidity: humidity}); }); }); }
random_line_split
issue-17441.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let _foo = &[1_usize, 2] as [usize]; //~^ ERROR cast to unsized type: `&[usize; 2]` as `[usize]` //~^^ HELP consider using an implicit coercion to `&[usize]` instead // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. let _bar = Box::new(1_usize) as std::fmt::Debug; //~...
main
identifier_name
issue-17441.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let _foo = &[1_usize, 2] as [usize]; //~^ ERROR cast to unsized type: `&[usize; 2]` as `[usize]` //~^^ HELP consider using an implicit coercion to `&[usize]` instead // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. let _bar = Box::new(1_usize) as std::fmt::Debug; //~^ E...
identifier_body
issue-17441.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
fn main() { let _foo = &[1_usize, 2] as [usize]; //~^ ERROR cast to unsized type: `&[usize; 2]` as `[usize]` //~^^ HELP consider using an implicit coercion to `&[usize]` instead // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. let _bar = Box::new(1_usize) as std::fmt::Debug;...
// 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
main.ts
class
extends Rf.ETS.FrameWork.GameMain { private group: Rf.ETS.FrameWork.Group = null; private sprite: Rf.ETS.FrameWork.Sprite = null; private touchCharactor: Rf.ETS.FrameWork.Character = null; private touchCharactorTouchPosX:number = 0; private touchCharactorTouchPosY:number ...
GameMain
identifier_name
main.ts
class GameMain extends Rf.ETS.FrameWork.GameMain { private group: Rf.ETS.FrameWork.Group = null; private sprite: Rf.ETS.FrameWork.Sprite = null; private touchCharactor: Rf.ETS.FrameWork.Character = null; private touchCharactorTouchPosX:number = 0; private touchCharactorTou...
this.touchCharactor.y = 32; this.touchCharactor.originX = 16*2; this.touchCharactor.originY = 16*2; this.touchCharactor.scale(2.0,2.0); this.touchCharactor.maxWaitCount = 6; this.touchCharactor.addEventListener(enchant.Event.TOUCH_START,(e:enc...
this.touchCharactor = new Rf.ETS.FrameWork.Character(32,32,parent); this.touchCharactor.FileName = this.resourceManager.GetResourceName("charaImage"); this.touchCharactor.charaIndex = 3; this.touchCharactor.Dir = Rf.ETS.FrameWork.Direction.Up; this.touchCh...
random_line_split
main.ts
class GameMain extends Rf.ETS.FrameWork.GameMain { private group: Rf.ETS.FrameWork.Group = null; private sprite: Rf.ETS.FrameWork.Sprite = null; private touchCharactor: Rf.ETS.FrameWork.Character = null; private touchCharactorTouchPosX:number = 0; private touchCharactorTou...
conditional_block
test_markup.py
# Check translations of pango markup # # This will look for translatable strings that appear to contain markup and # check that the markup in the translation matches. # # Copyright (C) 2015 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subjec...
for plural_id, msgstr in xlations.items(): # Check if the markup is valid at all try: # pylint: disable=unescaped-markup ET.fromstring('<markup>%s</markup>' % msgstr) except ET.ParseError: if entry.ms...
random_line_split
test_markup.py
# Check translations of pango markup # # This will look for translatable strings that appear to contain markup and # check that the markup in the translation matches. # # Copyright (C) 2015 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subjec...
(mofile): mo = polib.mofile(mofile) for entry in mo.translated_entries(): if is_markup(entry.msgid): # If this is a plural, check each of the plural translations if entry.msgid_plural: xlations = entry.msgstr_plural else: xlations = {N...
test_markup
identifier_name
test_markup.py
# Check translations of pango markup # # This will look for translatable strings that appear to contain markup and # check that the markup in the translation matches. # # Copyright (C) 2015 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subjec...
raise AssertionError("Markup does not match for msgid %s" % entry.msgid)
conditional_block
test_markup.py
# Check translations of pango markup # # This will look for translatable strings that appear to contain markup and # check that the markup in the translation matches. # # Copyright (C) 2015 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subjec...
raise AssertionError("Invalid markup translation for msgid %s" % entry.msgid) # Check if the markup has the same number and kind of tags if not markup_match(entry.msgid, msgstr): if entry.msgid_plural: raise AssertionEr...
mo = polib.mofile(mofile) for entry in mo.translated_entries(): if is_markup(entry.msgid): # If this is a plural, check each of the plural translations if entry.msgid_plural: xlations = entry.msgstr_plural else: xlations = {None: entry.msg...
identifier_body
index.d.ts
// Type definitions for animejs 2.0 // Project: http://animejs.com // Definitions by: Andrew Babin <https://github.com/A-Babin> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 type FunctionBasedParamter = (element: HTMLElement, index: number, length: number) => number; typ...
function random(min: number, max: number): number; } declare function anime(params: anime.AnimeParams): anime.AnimeInstance; export = anime; export as namespace anime;
function timeline(params?: AnimeInstanceParams | ReadonlyArray<AnimeInstance>): AnimeTimelineInstance;
random_line_split
run_CNN_SAT.py
# Copyright 2015 Tianchuan Du University of Delaware # 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 # # THIS CODE IS PROVIDED *AS IS* BAS...
# save the model and network configuration if cfg.param_output_file != '': _nnet2file(dnn.dnn_adapt.layers, filename = cfg.param_output_file + '.adapt', input_factor = cfg_adapt.input_dropout_factor, factor = cfg_adapt.dropout_factor) _nnet2file(dnn.cnn_si.layers, filename =...
valid_error = validate_by_minibatch_verbose(valid_fn, cfg_si.valid_sets, cfg_si.valid_xy, cfg.batch_size) log('> epoch %d, lrate %f, validation error %f ' % (cfg.lrate.epoch, cfg.lrate.get_rate(), 100*numpy.mean(valid_error)) + '(%)') cfg.lrate.get_next_rate(current_error = 100 * numpy.mean(valid_error)...
conditional_block
run_CNN_SAT.py
# Copyright 2015 Tianchuan Du University of Delaware # 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 # # THIS CODE IS PROVIDED *AS IS* BAS...
# Implements the Speaker Adaptive Training of DNNs proposed in the following papers: # [1] Yajie Miao, Hao Zhang, Florian Metze. "Towards Speaker Adaptive Training of Deep # Neural Network Acoustic Models". Interspeech 2014. # [2] Yajie Miao, Lu Jiang, Hao Zhang, Florian Metze. "Improvements to Speaker Adaptive # Tra...
from utils.utils import parse_arguments
random_line_split
colorbeams.py
""" Color beams pattern """ from .pattern import Pattern import colorsys import time class ColorBeams(Pattern): @staticmethod def getHue(hue): hsv = colorsys.hsv_to_rgb(hue, 1, 1) return int(hsv[0] * 255), int(hsv[1] * 255), int(hsv[2] * 255) @staticmethod def highlight(strip, i, h...
def __init__(self): pass @classmethod def get_id(self): return 11 @classmethod def update(self, strip, state): # use the time to determine the offset t = ColorBeams.__get_time() offset = int(((t % state.delay) / state.delay) * len(strip)) for y ...
@staticmethod def __get_time(): return time.time() * 1000
random_line_split
colorbeams.py
""" Color beams pattern """ from .pattern import Pattern import colorsys import time class ColorBeams(Pattern): @staticmethod def
(hue): hsv = colorsys.hsv_to_rgb(hue, 1, 1) return int(hsv[0] * 255), int(hsv[1] * 255), int(hsv[2] * 255) @staticmethod def highlight(strip, i, hue = 0.5): i = i % len(strip) # set the color of this pixel strip[i] = ColorBeams.getHue(hue) for x in range(15): ...
getHue
identifier_name
colorbeams.py
""" Color beams pattern """ from .pattern import Pattern import colorsys import time class ColorBeams(Pattern): @staticmethod def getHue(hue): hsv = colorsys.hsv_to_rgb(hue, 1, 1) return int(hsv[0] * 255), int(hsv[1] * 255), int(hsv[2] * 255) @staticmethod def highlight(strip, i, h...
@classmethod def update(self, strip, state): # use the time to determine the offset t = ColorBeams.__get_time() offset = int(((t % state.delay) / state.delay) * len(strip)) for y in range(0, len(strip), 50): ColorBeams.highlight(strip, offset + y, (5 * y / len(strip...
return 11
identifier_body
colorbeams.py
""" Color beams pattern """ from .pattern import Pattern import colorsys import time class ColorBeams(Pattern): @staticmethod def getHue(hue): hsv = colorsys.hsv_to_rgb(hue, 1, 1) return int(hsv[0] * 255), int(hsv[1] * 255), int(hsv[2] * 255) @staticmethod def highlight(strip, i, h...
@staticmethod def __get_time(): return time.time() * 1000 def __init__(self): pass @classmethod def get_id(self): return 11 @classmethod def update(self, strip, state): # use the time to determine the offset t = ColorBeams.__get_time() ...
index = (i - x) % len(strip) decay = pow(0.7, x) # strip[index] = (int(strip[index][0] * decay), int(strip[index][1] * decay), int(strip[index][2] * decay)) strip[index] = (int(strip[i][0] * decay), int(strip[i][1] * decay), int(strip[i][2] * decay))
conditional_block
facebookConnect.js
/* * Module : FacebookConnect.js * * Setups up the basic code to connect to the facebook JS api. * * Requires Config: * - app.config.facebook.appId */ (function(app) { var module = app.module("facebookConnect", { requires : [ "jquery-1.9.1.min" ], init : function() ...
//fix scroll bars if (self !== top) { $("body").css("overflow", "hidden"); } }; }(app));
$(document).trigger('facebookConnected');
random_line_split
facebookConnect.js
/* * Module : FacebookConnect.js * * Setups up the basic code to connect to the facebook JS api. * * Requires Config: * - app.config.facebook.appId */ (function(app) { var module = app.module("facebookConnect", { requires : [ "jquery-1.9.1.min" ], init : function() ...
}; }(app));
{ $("body").css("overflow", "hidden"); }
conditional_block
mod.rs
use lexer::dfa::*; use lexer::re::Test; use rust::RustWrite; use std::io::{self, Write}; #[cfg(test)] mod test; /// Generates a fn `__tokenize` based on the given DFA with the following signature: /// /// ```ignore /// fn tokenize(text: &str) -> Option<(usize, usize)> /// ``` /// /// This function returns `None` if t...
(&mut self, target_state: DFAStateIndex, index: &str) -> io::Result<()> { match self.dfa.state(target_state).kind { Kind::Accepts(nfa) => { rust!(self.out, "{}current_match = Some(({}, {}));", self.prefix, nf...
transition
identifier_name
mod.rs
use lexer::dfa::*; use lexer::re::Test; use rust::RustWrite; use std::io::{self, Write}; #[cfg(test)] mod test; /// Generates a fn `__tokenize` based on the given DFA with the following signature: /// /// ```ignore /// fn tokenize(text: &str) -> Option<(usize, usize)> /// ``` /// /// This function returns `None` if t...
struct Matcher<'m, W: Write+'m> { prefix: &'m str, dfa: &'m DFA, out: &'m mut RustWrite<W>, } impl<'m,W> Matcher<'m,W> where W: Write { fn tokenize(&mut self) -> io::Result<()> { rust!(self.out, "fn {}tokenize(text: &str) -> Option<(usize, usize)> {{", self.prefix); ...
{ let mut matcher = Matcher { prefix: prefix, dfa: dfa, out: out }; try!(matcher.tokenize()); Ok(()) }
identifier_body
mod.rs
use lexer::dfa::*; use lexer::re::Test; use rust::RustWrite; use std::io::{self, Write}; #[cfg(test)] mod test; /// Generates a fn `__tokenize` based on the given DFA with the following signature: /// /// ```ignore /// fn tokenize(text: &str) -> Option<(usize, usize)> /// ``` /// /// This function returns `None` if t...
Kind::Reject => { rust!(self.out, "return {}current_match;", self.prefix); return Ok(()); } } rust!(self.out, "{}current_state = {};", self.prefix, target_state.index()); rust!(self.out, "continue;"); Ok(()) } }
{ }
conditional_block
mod.rs
use lexer::dfa::*; use lexer::re::Test; use rust::RustWrite; use std::io::{self, Write}; #[cfg(test)] mod test; /// Generates a fn `__tokenize` based on the given DFA with the following signature: /// /// ```ignore /// fn tokenize(text: &str) -> Option<(usize, usize)> /// ``` /// /// This function returns `None` if t...
for (index, state) in self.dfa.states.iter().enumerate() { rust!(self.out, "{} => {{", index); try!(self.state(state)); rust!(self.out, "}}"); } rust!(self.out, "_ => {{ panic!(\"invalid state {{}}\", {}current_state); }}", self.prefix); ...
random_line_split
test.py
# -*- coding: utf-8 -*- import base64 import inspect import json import logging import requests import types from django.conf import settings from django.core.management import call_command from django_nose import FastFixtureTestCase from functools import wraps from mock import patch from tastypie.test import Resource...
""" Don't be smart in test cases! CAVEAT: Proxy classes have to be imported within each test method to mock the requests """ pass
identifier_body
test.py
# -*- coding: utf-8 -*- import base64 import inspect import json import logging import requests import types from django.conf import settings from django.core.management import call_command from django_nose import FastFixtureTestCase from functools import wraps from mock import patch from tastypie.test import Resource...
(self): call_command('loaddata', *TEST_DATA) super(TestCase, self).setUp() class Proxy(TestCase): """ Don't be smart in test cases! CAVEAT: Proxy classes have to be imported within each test method to mock the requests """ pass
setUp
identifier_name
test.py
# -*- coding: utf-8 -*- import base64 import inspect import json import logging import requests import types from django.conf import settings from django.core.management import call_command from django_nose import FastFixtureTestCase from functools import wraps from mock import patch from tastypie.test import Resource...
elif method == 'PUT': data = json.loads(kwargs.get('data', '{}')) djresponse = client.put(url, data=data, authentication=authentication) elif method == 'PATCH': data = json.loads(kwargs.get('data', '{}')) djresponse = client.patch(url, data=data, authentication=authentication) ...
data = json.loads(kwargs.get('data', '{}')) djresponse = client.post(url, data=data, authentication=authentication)
conditional_block
test.py
# -*- coding: utf-8 -*- import base64 import inspect import json import logging import requests import types from django.conf import settings from django.core.management import call_command from django_nose import FastFixtureTestCase from functools import wraps from mock import patch from tastypie.test import Resource...
return response def mock_cache_set(key, value, timeout=None): # do nothing pass def mock_api(func, **decorator_kwargs): @patch('requests.sessions.Session.request', mock_request) @patch('tastypie.cache.SimpleCache.set', mock_cache_set) @wraps(func) def wrapper(*args, **kwargs): retu...
except: pass response.encoding = requests.utils.get_encoding_from_headers(response.headers) response._content = djresponse.content
random_line_split
immunicity.py
import re import fnmatch import urllib2 from kodipopcorntime import plugin from kodipopcorntime.caching import shelf PAC_URL = "http://clientconfig.immunicity.org/pacs/all.pac" CACHE = 1 * 3600 # 1 hour caching _config = {} def config(): global _config if not _config: with shelf("kodipopcorntime.imm...
conf = config() for domain in conf["domains"]: if re.search(domain, url): return conf["server"]
identifier_body
immunicity.py
import re import fnmatch import urllib2 from kodipopcorntime import plugin from kodipopcorntime.caching import shelf PAC_URL = "http://clientconfig.immunicity.org/pacs/all.pac" CACHE = 1 * 3600 # 1 hour caching _config = {} def config(): global _config if not _config:
return _config def get_proxy_for(url): conf = config() for domain in conf["domains"]: if re.search(domain, url): return conf["server"]
with shelf("kodipopcorntime.immunicity.pac_config", ttl=CACHE) as pac_config: plugin.log.info("Fetching Immunicity PAC file") pac_data = urllib2.urlopen(PAC_URL).read() pac_config["server"] = re.search(r"var proxyserver = '(.*)'", pac_data).group(1) pac_config["domains"] ...
conditional_block
immunicity.py
import re import fnmatch import urllib2 from kodipopcorntime import plugin from kodipopcorntime.caching import shelf PAC_URL = "http://clientconfig.immunicity.org/pacs/all.pac" CACHE = 1 * 3600 # 1 hour caching _config = {} def config(): global _config if not _config: with shelf("kodipopcorntime.imm...
(url): conf = config() for domain in conf["domains"]: if re.search(domain, url): return conf["server"]
get_proxy_for
identifier_name
immunicity.py
import re import fnmatch import urllib2 from kodipopcorntime import plugin from kodipopcorntime.caching import shelf PAC_URL = "http://clientconfig.immunicity.org/pacs/all.pac" CACHE = 1 * 3600 # 1 hour caching _config = {} def config(): global _config if not _config: with shelf("kodipopcorntime.imm...
for domain in conf["domains"]: if re.search(domain, url): return conf["server"]
conf = config()
random_line_split
recipe-440498.py
# Relative-refs.pyw """A short python script for repathing xrefs in Autocad.""" import win32com.client,os, os.path, tkFileDialog from Tkinter import * from tkMessageBox import askokcancel from time import sleep # Get a COM object for Autocad acad = win32com.client.Dispatch("AutoCAD.Application") def repath(filename)...
root.update() acad.Visible = True
drawing = os.path.join(dirpath, name) try: repath(drawing) except: print 'Unable to repath drawing %s!' %drawing
conditional_block
recipe-440498.py
# Relative-refs.pyw """A short python script for repathing xrefs in Autocad.""" import win32com.client,os, os.path, tkFileDialog from Tkinter import * from tkMessageBox import askokcancel from time import sleep # Get a COM object for Autocad acad = win32com.client.Dispatch("AutoCAD.Application") def repath(filename)...
def close(self): """Fake close method.""" pass if __name__ == '__main__': if acad.Visible: acad.Visible = False root = Tk() text = Tktextfile(root) logger = Logger(text) dir = tkFileDialog.askdirectory() answer = askokcancel('RePath','Re path all dwg files in ...
"""Write method for file like widget.""" self.text.insert(INSERT, line) self.text.see(END)
identifier_body
recipe-440498.py
# Relative-refs.pyw """A short python script for repathing xrefs in Autocad.""" import win32com.client,os, os.path, tkFileDialog from Tkinter import * from tkMessageBox import askokcancel from time import sleep # Get a COM object for Autocad acad = win32com.client.Dispatch("AutoCAD.Application") def repath(filename)...
: """A filelike object that prints its input on the screen.""" def __init__(self, logfile=None): """Takes one argument, a file like object for logging.""" print 'Starting logger...' if not logfile: self.logfile = open('relative-refs.log','w') else: se...
Logger
identifier_name
recipe-440498.py
# Relative-refs.pyw """A short python script for repathing xrefs in Autocad.""" import win32com.client,os, os.path, tkFileDialog from Tkinter import * from tkMessageBox import askokcancel from time import sleep # Get a COM object for Autocad acad = win32com.client.Dispatch("AutoCAD.Application") def repath(filename)...
drawing = os.path.join(dirpath, name) try: repath(drawing) except: print 'Unable to repath drawing %s!' %drawing root.update() acad.Visible = True
random_line_split
services.py
import logging import requests import xml.etree.ElementTree as ET from django.utils.translation import gettext_lazy as _ from churchill.apps.currencies.models import CurrencyValue, Currency, CurrencyValueType logger = logging.getLogger() def get_default_currency_id() -> int: currency, _ = Currency.objects.get_...
code_to = node.find("codeTo").text if ( byn_currency and (code == "USD" and code_to == "BYN") or (code == "BYN" and code_to == "USD") ): create_currency_pair(byn_c...
if child.attrib.get("id") == "168,768,968,868": for node in child.findall("currency"): code = node.find("code").text
random_line_split
services.py
import logging import requests import xml.etree.ElementTree as ET from django.utils.translation import gettext_lazy as _ from churchill.apps.currencies.models import CurrencyValue, Currency, CurrencyValueType logger = logging.getLogger() def
() -> int: currency, _ = Currency.objects.get_or_create( name="United States Dollar", iso3="USD" ) return currency.id def get_currency_options() -> dict: return {c.iso3: c.name for c in Currency.objects.all()} def create_currency_pair(currency, node): CurrencyValue.objects.create( ...
get_default_currency_id
identifier_name
services.py
import logging import requests import xml.etree.ElementTree as ET from django.utils.translation import gettext_lazy as _ from churchill.apps.currencies.models import CurrencyValue, Currency, CurrencyValueType logger = logging.getLogger() def get_default_currency_id() -> int: currency, _ = Currency.objects.get_...
if ( eur_currency and (code == "USD" and code_to == "EUR") or (code == "EUR" and code_to == "USD") ): create_currency_pair(eur_currency, node) if ( ...
byn_currency = Currency.objects.first(iso3="BYN") eur_currency = Currency.objects.first(iso3="EUR") rub_currency = Currency.objects.first(iso3="RUB") if not any((byn_currency, eur_currency, rub_currency)): logger.info(_("No currencies are setup")) response = requests.get("https://www.mtbank.by/...
identifier_body
services.py
import logging import requests import xml.etree.ElementTree as ET from django.utils.translation import gettext_lazy as _ from churchill.apps.currencies.models import CurrencyValue, Currency, CurrencyValueType logger = logging.getLogger() def get_default_currency_id() -> int: currency, _ = Currency.objects.get_...
rub_currency and (code == "USD" and code_to == "RUB") or (code == "RUB" and code_to == "USD") ): create_currency_pair(rub_currency, node)
if child.attrib.get("id") == "168,768,968,868": for node in child.findall("currency"): code = node.find("code").text code_to = node.find("codeTo").text if ( byn_currency and (code == "USD" and co...
conditional_block
fix_csxml_character_encoding.py
import sys import logging codec_options = ['utf-8', 'latin_1'] logger = logging.getLogger(__name__) def try_decode(byte_string, codec): try: s = byte_string.decode(codec) return s except: return None def shortest_string(strings): best_string = None best_length = None ...
else: # If more than one, choose the codec that gives the best # length chosen_string = shortest_string(decoded) # Write result as ascii, with non-ascii characters escaped f_out.write(chosen_string.enco...
logger.info('Could not decode: %s' % line) sys.exit(1)
conditional_block
fix_csxml_character_encoding.py
import sys import logging codec_options = ['utf-8', 'latin_1'] logger = logging.getLogger(__name__) def try_decode(byte_string, codec): try: s = byte_string.decode(codec) return s except: return None def shortest_string(strings):
def fix_character_encoding(input_file, output_file): with open(input_file, 'rb') as f_in: with open(output_file, 'wb') as f_out: for line in f_in: # Try to decode with both latin_1 and utf-8 decoded = [try_decode(line, c) for c in codec_options] ...
best_string = None best_length = None for s in strings: if best_string is None or len(s) < best_length: best_string = s best_length = len(s) return best_string
identifier_body
fix_csxml_character_encoding.py
import sys import logging codec_options = ['utf-8', 'latin_1'] logger = logging.getLogger(__name__) def try_decode(byte_string, codec): try: s = byte_string.decode(codec) return s except: return None def
(strings): best_string = None best_length = None for s in strings: if best_string is None or len(s) < best_length: best_string = s best_length = len(s) return best_string def fix_character_encoding(input_file, output_file): with open(input_file, 'rb') as f_in: ...
shortest_string
identifier_name
fix_csxml_character_encoding.py
import sys import logging codec_options = ['utf-8', 'latin_1'] logger = logging.getLogger(__name__) def try_decode(byte_string, codec): try: s = byte_string.decode(codec) return s except: return None def shortest_string(strings): best_string = None best_length = None ...
args = sys.argv[1:] if len(args) != 2: logger.error('Expected two arguments: the input file' ' and the output file') sys.exit(1) input_file = args[0] output_file = args[1] fix_character_encoding(input_file, output_file)
# Write result as ascii, with non-ascii characters escaped f_out.write(chosen_string.encode('utf-8')) if __name__ == '__main__':
random_line_split
index.tsx
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you...
* under the License. */ import { DatePicker as AntdDatePicker } from 'antd'; import { styled } from '@superset-ui/core'; const AntdRangePicker = AntdDatePicker.RangePicker; export const RangePicker = styled(AntdRangePicker)` border-radius: ${({ theme }) => theme.gridUnit}px; `; export const DatePicker = AntdDate...
* Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations
random_line_split
version.py
#!/usr/bin/python3 """Script to determine the Pywikibot version (tag, revision and date). .. versionchanged:: 7.0 version script was moved to the framework scripts folder """ # # (C) Pywikibot team, 2007-2021 # # Distributed under the terms of the MIT license. # import codecs import os import sys import pywikibot ...
pywikibot.output('Usernames for family {!r}:'.format(family)) for lang, username in usernames.items(): pywikibot.output('\t{}: {}'.format(lang, username)) if __name__ == '__main__': main()
continue
conditional_block
version.py
#!/usr/bin/python3 """Script to determine the Pywikibot version (tag, revision and date). .. versionchanged:: 7.0 version script was moved to the framework scripts folder """ # # (C) Pywikibot team, 2007-2021 # # Distributed under the terms of the MIT license. # import codecs import os import sys import pywikibot ...
if not usernames: continue pywikibot.output('Usernames for family {!r}:'.format(family)) for lang, username in usernames.items(): pywikibot.output('\t{}: {}'.format(lang, username)) if __name__ == '__main__': main()
'{}: {}'.format(environ_name, os.environ.get(environ_name, 'Not set') or "''")) pywikibot.output('Config base dir: ' + pywikibot.config.base_dir) for family, usernames in pywikibot.config.usernames.items():
random_line_split
version.py
#!/usr/bin/python3 """Script to determine the Pywikibot version (tag, revision and date). .. versionchanged:: 7.0 version script was moved to the framework scripts folder """ # # (C) Pywikibot team, 2007-2021 # # Distributed under the terms of the MIT license. # import codecs import os import sys import pywikibot ...
(*args: str) -> None: """Print pywikibot version and important settings.""" pywikibot.output('Pywikibot: ' + getversion()) pywikibot.output('Release version: ' + pywikibot.__version__) pywikibot.output('setuptools version: ' + setuptools.__version__) pywikibot.output('mwparserfromhell version: ' ...
main
identifier_name