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
confirmdialog.d.ts
import { ElementRef, AfterViewInit, OnDestroy, Renderer2 } from '@angular/core'; import { DomHandler } from '../dom/domhandler'; import { ConfirmationService, Confirmation } from '../common/api'; import { Subscription } from 'rxjs/Subscription'; export declare class ConfirmDialog implements AfterViewInit, OnDestroy { ...
visible: boolean; ngAfterViewInit(): void; center(): void; enableModality(): void; disableModality(): void; hide(event?: Event): void; moveOnTop(): void; ngOnDestroy(): void; accept(): void; reject(): void; } export declare class ConfirmDialogModule { }
constructor(el: ElementRef, domHandler: DomHandler, renderer: Renderer2, confirmationService: ConfirmationService);
random_line_split
confirmdialog.d.ts
import { ElementRef, AfterViewInit, OnDestroy, Renderer2 } from '@angular/core'; import { DomHandler } from '../dom/domhandler'; import { ConfirmationService, Confirmation } from '../common/api'; import { Subscription } from 'rxjs/Subscription'; export declare class ConfirmDialog implements AfterViewInit, OnDestroy { ...
{ }
ConfirmDialogModule
identifier_name
unwind-no-uwtable.rs
// run-pass // needs-unwind // ignore-windows target requires uwtable // ignore-wasm32-bare no proper panic=unwind support // compile-flags: -C panic=unwind -C force-unwind-tables=n use std::panic::{self, AssertUnwindSafe}; struct Increase<'a>(&'a mut u8); impl Drop for Increase<'_> { fn drop(&mut self) { ...
() { let mut count = 0; assert!(panic::catch_unwind(AssertUnwindSafe( #[inline(never)] || increase(&mut count) )).is_err()); assert_eq!(count, 1); }
main
identifier_name
unwind-no-uwtable.rs
// run-pass // needs-unwind // ignore-windows target requires uwtable // ignore-wasm32-bare no proper panic=unwind support // compile-flags: -C panic=unwind -C force-unwind-tables=n use std::panic::{self, AssertUnwindSafe}; struct Increase<'a>(&'a mut u8); impl Drop for Increase<'_> { fn drop(&mut self) { ...
#[inline(never)] fn increase(count: &mut u8) { let _increase = Increase(count); unwind(); } fn main() { let mut count = 0; assert!(panic::catch_unwind(AssertUnwindSafe( #[inline(never)] || increase(&mut count) )).is_err()); assert_eq!(count, 1); }
{ panic!(); }
identifier_body
unwind-no-uwtable.rs
// run-pass // needs-unwind // ignore-windows target requires uwtable // ignore-wasm32-bare no proper panic=unwind support // compile-flags: -C panic=unwind -C force-unwind-tables=n use std::panic::{self, AssertUnwindSafe}; struct Increase<'a>(&'a mut u8); impl Drop for Increase<'_> { fn drop(&mut self) { ...
#[inline(never)] fn increase(count: &mut u8) { let _increase = Increase(count); unwind(); } fn main() { let mut count = 0; assert!(panic::catch_unwind(AssertUnwindSafe( #[inline(never)] || increase(&mut count) )).is_err()); assert_eq!(count, 1); }
#[inline(never)] fn unwind() { panic!(); }
random_line_split
__init__.py
import re import json import logging import random import venusian from collections import namedtuple from collections import OrderedDict from zope.interface import providedBy, Interface from pyramid.compat import string_types from pyramid.config.views import DefaultViewMapper from pyramid.location import lineage from ...
html = re.search('<html\.*>', content) color = random.randint(0,0xFFFFFF) if html: pos = html.end() - 1 content = ('{0} style="border: 2px solid #{1:06x}" title="{2}"' '{3}').format(content[:pos], color, data['name'], ...
def __init__(self, layout): self.layout = layout def layout_info(self, layout, context, request, content): intr = layout.intr view = intr['view'] if view is not None: layout_factory = '%s.%s'%(view.__module__, view.__name__) else: layout_factory = 'No...
identifier_body
__init__.py
import re import json import logging import random import venusian from collections import namedtuple from collections import OrderedDict from zope.interface import providedBy, Interface from pyramid.compat import string_types from pyramid.config.views import DefaultViewMapper from pyramid.location import lineage from ...
(root, context, request, layoutname=''): chain = [] layout, layoutcontext = query_layout(root, context, request, layoutname) if layout is None: return chain chain.append((layout, layoutcontext)) contexts = {layoutname: layoutcontext} while layout is not None and layout.layout is not N...
query_layout_chain
identifier_name
__init__.py
import re import json import logging import random import venusian from collections import namedtuple from collections import OrderedDict from zope.interface import providedBy, Interface from pyramid.compat import string_types from pyramid.config.views import DefaultViewMapper from pyramid.location import lineage from ...
data = OrderedDict( (('name', intr['name']), ('parent-layout', intr['parent']), ('layout-factory', layout_factory), ('renderer', intr['renderer']), ('context', '%s.%s'%(context.__class__.__module__, context.__clas...
if view is not None: layout_factory = '%s.%s'%(view.__module__, view.__name__) else: layout_factory = 'None'
random_line_split
__init__.py
import re import json import logging import random import venusian from collections import namedtuple from collections import OrderedDict from zope.interface import providedBy, Interface from pyramid.compat import string_types from pyramid.config.views import DefaultViewMapper from pyramid.location import lineage from ...
else: layout_factory = 'None' data = OrderedDict( (('name', intr['name']), ('parent-layout', intr['parent']), ('layout-factory', layout_factory), ('renderer', intr['renderer']), ('context', '%s.%s'%(context.__class__.__module_...
layout_factory = '%s.%s'%(view.__module__, view.__name__)
conditional_block
ordered_set_queue.py
import collections from queue import Queue class OrderedSetQueue(Queue): """ A queue based on ordered set. This behaves just like a normal queue but does not allow the same item to be in the queue more than once. """ def _init(self, maxsize): self.queue = OrderedSet() def _put(self, i...
def pop(self, last=True): if not self: raise KeyError('set is empty') key = self.end[1][0] if last else self.end[2][0] self.discard(key) return key def __repr__(self): if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r...
yield curr[0] curr = curr[1]
conditional_block
ordered_set_queue.py
import collections from queue import Queue class OrderedSetQueue(Queue): """ A queue based on ordered set. This behaves just like a normal queue but does not allow the same item to be in the queue more than once. """ def _init(self, maxsize): self.queue = OrderedSet() def _put(self, i...
class OrderedSet(collections.MutableSet): """ Set that remembers original insertion order. Code from http://code.activestate.com/recipes/576694/ """ def __init__(self, iterable=None): self.end = end = [] end += [None, end, end] # sentinel node for doubly linked list ...
return self.queue.pop()
identifier_body
ordered_set_queue.py
import collections from queue import Queue class OrderedSetQueue(Queue): """ A queue based on ordered set. This behaves just like a normal queue but does not allow the same item to be in the queue more than once. """ def _init(self, maxsize): self.queue = OrderedSet() def _put(self, i...
nxt[1] = prev def __iter__(self): end = self.end curr = end[2] while curr is not end: yield curr[0] curr = curr[2] def __reversed__(self): end = self.end curr = end[1] while curr is not end: yield curr[0] ...
key, prev, nxt = self.map.pop(key) prev[2] = nxt
random_line_split
ordered_set_queue.py
import collections from queue import Queue class OrderedSetQueue(Queue): """ A queue based on ordered set. This behaves just like a normal queue but does not allow the same item to be in the queue more than once. """ def _init(self, maxsize): self.queue = OrderedSet() def _put(self, i...
(self): end = self.end curr = end[1] while curr is not end: yield curr[0] curr = curr[1] def pop(self, last=True): if not self: raise KeyError('set is empty') key = self.end[1][0] if last else self.end[2][0] self.discard(key) ...
__reversed__
identifier_name
poll.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
if (Array.isArray(value) && value.length === 0) { throw "Default assertion of poll: Value was array but it got length of '0'."; } } export async function assertWithPoll<T>( getValue: () => T, duration: number, step: number, assertForValue: (input: T) => void = defaultAssertion): Promi...
{ throw "Default assertion of poll: Excepted value not to be undefined."; }
conditional_block
poll.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
export async function poll<T>( getValue: () => Promise<T> | T, duration: number, step: number, expression: (input: T) => boolean = defaultPollExpression): Promise<T> { while (duration > 0) { let value = await getValue(); if (expression(value)) { return value; }...
{ while (duration > 0) { let value = await getValue(); if (expression(value)) { throw new Error("Polling succeeded within the alotted duration, but should not have."); } await sleep(step); duration -= step; } // Successfully never happened }
identifier_body
poll.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
<T>(value: T): boolean { return value !== undefined && ((Array.isArray(value) && value.length > 0) || (!Array.isArray(value) && !!value)); } export async function pollDoesNotHappen<T>( getValue: () => T, duration: number, step: number, expression: (input: T) => boolean = defaultPollExpression): Pro...
defaultPollExpression
identifier_name
poll.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
throw assertResult; } function defaultPollExpression<T>(value: T): boolean { return value !== undefined && ((Array.isArray(value) && value.length > 0) || (!Array.isArray(value) && !!value)); } export async function pollDoesNotHappen<T>( getValue: () => T, duration: number, step: number, expres...
duration -= step; }
random_line_split
FunctionLogOptionsCallout.tsx
import React, { useContext } from 'react'; import { LoggingOptions } from '../function-editor/FunctionEditor.types'; import { Callout, DirectionalHint, PrimaryButton, DefaultButton } from 'office-ui-fabric-react'; import { calloutStyle } from './FunctionLog.styles'; import { useTranslation } from 'react-i18next'; impor...
onCloseDialog(); }; return ( <Callout role="alertdialog" gapSpace={0} target={`.editor-logging-dropdown`} onDismiss={onCloseDialog} setInitialFocus={true} directionalHint={DirectionalHint.bottomLeftEdge} isBeakVisible={true}> <div className={calloutStyle}> ...
{ setSelectedLoggingOption(LoggingOptions.fileBased); LogService.trackEvent(LogCategories.functionLog, 'fileBased-logging-selected', { resourceId: siteStateContext.resourceId, sessionId: Url.getParameterByName(null, 'sessionId'), }); }
conditional_block
FunctionLogOptionsCallout.tsx
import React, { useContext } from 'react'; import { LoggingOptions } from '../function-editor/FunctionEditor.types'; import { Callout, DirectionalHint, PrimaryButton, DefaultButton } from 'office-ui-fabric-react'; import { calloutStyle } from './FunctionLog.styles'; import { useTranslation } from 'react-i18next'; impor...
onDismiss={onCloseDialog} setInitialFocus={true} directionalHint={DirectionalHint.bottomLeftEdge} isBeakVisible={true}> <div className={calloutStyle}> <div>{t('functionEditor_fileBasedLogsCalloutMessage')}</div> <div className={buttonsWrapperStyle}> <PrimaryButton...
<Callout role="alertdialog" gapSpace={0} target={`.editor-logging-dropdown`}
random_line_split
uuid.py
# Copyright 2013 OpenStack Foundation # # 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...
def _get_token_id(self, token_data): return uuid.uuid4().hex
random_line_split
uuid.py
# Copyright 2013 OpenStack Foundation # # 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...
def __init__(self, *args, **kwargs): super(Provider, self).__init__(*args, **kwargs) def _get_token_id(self, token_data): return uuid.uuid4().hex
identifier_body
uuid.py
# Copyright 2013 OpenStack Foundation # # 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...
(common.BaseProvider): def __init__(self, *args, **kwargs): super(Provider, self).__init__(*args, **kwargs) def _get_token_id(self, token_data): return uuid.uuid4().hex
Provider
identifier_name
view_tag.py
from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class
(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.ur...
ViewNode
identifier_name
view_tag.py
from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token):
def render(self, context): print('render view tag...') if 'request' not in context: return "" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do n...
self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: ...
identifier_body
view_tag.py
from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = ...
tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find("=") if equals == -1: self.args.append(token) else: self.kwargs[str(token[:equals])] = token[equals + 1:] def render(self,...
raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0])
conditional_block
view_tag.py
from django.template import Library, Node, TemplateSyntaxError, Variable from django.conf import settings from django.core import urlresolvers import hashlib import re register = Library()
class ViewNode(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0]) tag_name = tokens.pop(0) ...
random_line_split
de96b7a322c512a247dbf49cad92f67ae6c33fd6.js
"use strict";var assert;module.watch(require('assert'),{default(v){assert=v}},0);var unhexArray;module.watch(require('./testutil'),{unhexArray(v){unhexArray=v}},1);var table;module.watch(require('../src/table'),{default(v){table=v}},2); describe('table.js', function() { it('should make a ScriptList table', funct...
langSysRecords: [] } }, { tag: 'latn', script: { defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [0, 1, 2] }, langSysRecords: [{ tag: 'URD '...
},
random_line_split
de96b7a322c512a247dbf49cad92f67ae6c33fd6.js
"use strict";var assert;module.watch(require('assert'),{default(v){assert=v}},0);var unhexArray;module.watch(require('./testutil'),{unhexArray(v)
},1);var table;module.watch(require('../src/table'),{default(v){table=v}},2); describe('table.js', function() { it('should make a ScriptList table', function() { // https://www.microsoft.com/typography/OTSPEC/chapter2.htm Examples 1 & 2 var expectedData = unhexArray( '0003 68616E69 00...
{unhexArray=v}
identifier_body
de96b7a322c512a247dbf49cad92f67ae6c33fd6.js
"use strict";var assert;module.watch(require('assert'),{
(v){assert=v}},0);var unhexArray;module.watch(require('./testutil'),{unhexArray(v){unhexArray=v}},1);var table;module.watch(require('../src/table'),{default(v){table=v}},2); describe('table.js', function() { it('should make a ScriptList table', function() { // https://www.microsoft.com/typography/OTSPEC/...
default
identifier_name
adminPickupManage.component.ts
'use strict'; const angular = require('angular'); import {AdminPickupBase} from './adminPickupBase' export class AdminPickupManageComponent extends AdminPickupBase{ editUserEvent: IPickupUserEvent = null; pickupEventAlternatives:IPickupEvent[]; /*ngInjector*/ constructor($http, PickupUtils, PickupOptionsServ...
} } export default angular.module('terrappApp.adminPickups') .component('adminPickupManage', { template: require('./adminPickupManage.html'), controller: AdminPickupManageComponent, controllerAs: '$ctrl', bindings: { resolve: '<', close: '&', dismiss: '&' }, }).name;
{ userEvent.pickupEventOverride = override; }
conditional_block
adminPickupManage.component.ts
'use strict'; const angular = require('angular'); import {AdminPickupBase} from './adminPickupBase' export class AdminPickupManageComponent extends AdminPickupBase{ editUserEvent: IPickupUserEvent = null; pickupEventAlternatives:IPickupEvent[]; /*ngInjector*/ constructor($http, PickupUtils, PickupOptionsServ...
setEditUserEvent(userEvent) { if (!userEvent || (this.editUserEvent && this.editUserEvent._id === userEvent._id)) { this.editUserEvent = null; } else { this.editUserEvent = _.cloneDeep(userEvent); } } setPickupOverride(userEvent, original, override) { if (original._id === override._i...
}
random_line_split
adminPickupManage.component.ts
'use strict'; const angular = require('angular'); import {AdminPickupBase} from './adminPickupBase' export class AdminPickupManageComponent extends AdminPickupBase{ editUserEvent: IPickupUserEvent = null; pickupEventAlternatives:IPickupEvent[]; /*ngInjector*/ constructor($http, PickupUtils, PickupOptionsServ...
(userEvent) { if (!userEvent || (this.editUserEvent && this.editUserEvent._id === userEvent._id)) { this.editUserEvent = null; } else { this.editUserEvent = _.cloneDeep(userEvent); } } setPickupOverride(userEvent, original, override) { if (original._id === override._id) { userEve...
setEditUserEvent
identifier_name
adminPickupManage.component.ts
'use strict'; const angular = require('angular'); import {AdminPickupBase} from './adminPickupBase' export class AdminPickupManageComponent extends AdminPickupBase{ editUserEvent: IPickupUserEvent = null; pickupEventAlternatives:IPickupEvent[]; /*ngInjector*/ constructor($http, PickupUtils, PickupOptionsServ...
setPickupOverride(userEvent, original, override) { if (original._id === override._id) { userEvent.pickupEventOverride = null; } else { userEvent.pickupEventOverride = override; } } } export default angular.module('terrappApp.adminPickups') .component('adminPickupManage', { templat...
{ if (!userEvent || (this.editUserEvent && this.editUserEvent._id === userEvent._id)) { this.editUserEvent = null; } else { this.editUserEvent = _.cloneDeep(userEvent); } }
identifier_body
Business.js
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdBusiness(props)
export default MdBusiness;
{ return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M24 14h20v28H4V6h20v8zM12 38v-4H8v4h4zm0-8v-4H8v4h4zm0-8v-4H8v4h4zm0-8v-4H8v4h4zm8 24v-4h-4v4h4zm0-8v-4h-4v4h4zm0-8v-4h-4v4h4zm0-8v-4h-4v4h4zm20 24V18H24v4h4v4h-4v4h4v4h-4v4h16zm-4-16h-4v4h4v-4zm0 8h-4v4h4v-4z" /> </IconBase> ); }
identifier_body
Business.js
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdBusiness(props) {
); } export default MdBusiness;
return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M24 14h20v28H4V6h20v8zM12 38v-4H8v4h4zm0-8v-4H8v4h4zm0-8v-4H8v4h4zm0-8v-4H8v4h4zm8 24v-4h-4v4h4zm0-8v-4h-4v4h4zm0-8v-4h-4v4h4zm0-8v-4h-4v4h4zm20 24V18H24v4h4v4h-4v4h4v4h-4v4h16zm-4-16h-4v4h4v-4zm0 8h-4v4h4v-4z" /> </IconBase>
random_line_split
Business.js
import React from 'react'; import IconBase from '@suitejs/icon-base'; function
(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M24 14h20v28H4V6h20v8zM12 38v-4H8v4h4zm0-8v-4H8v4h4zm0-8v-4H8v4h4zm0-8v-4H8v4h4zm8 24v-4h-4v4h4zm0-8v-4h-4v4h4zm0-8v-4h-4v4h4zm0-8v-4h-4v4h4zm20 24V18H24v4h4v4h-4v4h4v4h-4v4h16zm-4-16h-4v4h4v-4zm0 8h-4v4h4v-4z" /> </IconBase> ); } ...
MdBusiness
identifier_name
ButtonStory.tsx
import { css } from 'glamor' import React from 'react' import { Button, Card, List, ListItem, ResourceProvider, ThemeProvider, } from '../src/' const CollapsibleStory = () => (
margin: '10px 10px 10px 10px', })} > <List> <ListItem alignH="space-around"> <Button>Confirm</Button> <Button secondary>Cancel</Button> </ListItem> <ListItem alignH="space-around"> <Button disabled>Confirm</Button> ...
<ThemeProvider> <ResourceProvider> <Card {...css({ width: '300px',
random_line_split
metadata.py
""" match = self.pattern.match(self.value) module = import_module(match.group('module')) attrs = filter(None, (match.group('attr') or '').split('.')) return functools.reduce(getattr, attrs, module) @property def extras(self): match = self.pattern.match(self.value) ...
class DistributionFinder(MetaPathFinder): """ A MetaPathFinder capable of discovering installed distributions. """ class Context: name = None """ Specific name for which a distribution finder should match. """ def __init__(self, **kwargs): vars(s...
yield dep + parse_condition(section)
conditional_block
metadata.py
-like object :return: a concrete Distribution instance for the path """ return PathDistribution(pathlib.Path(path)) @staticmethod def _discover_resolvers(): """Search the meta_path for resolvers.""" declared = ( getattr(finder, 'find_distributions', None) ...
for group, eps in grouped }
random_line_split
metadata.py
, group) for group in config.sections() for name, value in config.items(group) ] @classmethod def _from_text(cls, text): config = ConfigParser(delimiters='=') # case sensitive: https://stackoverflow.com/q/1611799/812183 config.optionxform = str ...
@classmethod def find_distributions(cls, context=DistributionFinder.Context()): """ Find distributions. Return an iterable of all Distribution instances capable of loading the metadata for packages matching ``context.name`` (or all names if ``None`` indicated) along the path...
identifier_body
metadata.py
""" match = self.pattern.match(self.value) module = import_module(match.group('module')) attrs = filter(None, (match.group('attr') or '').split('.')) return functools.reduce(getattr, attrs, module) @property def extras(self): match = self.pattern.match(self.value...
(lines): section = None for line in filter(None, lines): section_match = re.match(r'\[(.*)\]$', line) if section_match: section = section_match.group(1) continue yield locals() @staticmethod def _convert_egg_info_reqs_to_simple...
_read_sections
identifier_name
load-balancer-weighted-target.ts
{ throw new Error('Weighted target config must have a targets map'); } for (const key of obj.targets) { const targetObj = obj.targets[key]; if (!('weight' in targetObj && typeof targetObj.weight === 'number')) { throw new Error(`Weighted target ${key} must have a numeric weight`...
this.targetList = Array.from(lbConfig.getTargets().keys());
random_line_split
load-balancer-weighted-target.ts
TargetPicker implements Picker { private rangeTotal: number; constructor(private readonly pickerList: WeightedPicker[]) { this.rangeTotal = pickerList[pickerList.length - 1].rangeEnd; } pick(pickArgs: PickArgs): PickResult { // num | 0 is equivalent to floor(num) const selection = (Math.rando...
{ for (const targetName of this.targetList) { this.targets.get(targetName)?.resetBackoff(); } }
identifier_body
load-balancer-weighted-target.ts
availablePicker; import SubchannelAddress = experimental.SubchannelAddress; import subchannelAddressToString = experimental.subchannelAddressToString; import validateLoadBalancingConfig = experimental.validateLoadBalancingConfig; const TRACER_NAME = 'weighted_target'; function trace(text: string): void { ex...
() { return this.targets; } toJsonObject(): object { const targetsField: {[key: string]: object} = {}; for (const [targetName, targetValue] of this.targets.entries()) { targetsField[targetName] = { weight: targetValue.weight, child_policy: targetValue.child_policy.map(pol...
getTargets
identifier_name
load-balancer-weighted-target.ts
Picker; import SubchannelAddress = experimental.SubchannelAddress; import subchannelAddressToString = experimental.subchannelAddressToString; import validateLoadBalancingConfig = experimental.validateLoadBalancingConfig; const TRACER_NAME = 'weighted_target'; function trace(text: string): void { experimenta...
else { connectivityState = ConnectivityState.TRANSIENT_FAILURE; } let picker: Picker; switch (connectivityState) { case ConnectivityState.READY: picker = new WeightedTargetPicker(pickerList); break; case ConnectivityState.CONNECTING: case ConnectivityState...
{ connectivityState = ConnectivityState.IDLE; }
conditional_block
scheduler.rs
#![allow(unused)] extern crate fringe; use self::fringe::generator::{Generator, Yielder}; use self::fringe::OwnedStack; use alloc::vec::Vec; use time::{Duration, Instant}; #[derive(Debug)] pub struct WaitRequest { timeout: Option<Instant>, event: Option<WaitEvent>, } #[derive(Debug)] pub enum WaitResult { ...
<F: FnOnce(Io) + Send + 'a>(&mut self, stack_size: usize, f: F) { let stack = OwnedStack::new(stack_size); let thread = Thread { generator: Generator::unsafe_new(stack, move |yielder, _| f(Io(yielder))), waiting_for: WaitRequest { timeout: None, ev...
spawn
identifier_name
scheduler.rs
#![allow(unused)] extern crate fringe; use self::fringe::generator::{Generator, Yielder}; use self::fringe::OwnedStack; use alloc::vec::Vec; use time::{Duration, Instant}; #[derive(Debug)] pub struct WaitRequest { timeout: Option<Instant>, event: Option<WaitEvent>, } #[derive(Debug)] pub enum WaitResult { ...
} if event.completed() => { thread.generator.resume(WaitResult::Completed) } WaitRequest { timeout: None, event: None, } => ...
thread.generator.resume(WaitResult::TimedOut) } WaitRequest { event: Some(ref event), ..
random_line_split
extract_i18n_spec.ts
* found in the LICENSE file at https://angular.io/license */ import * as fs from 'fs'; import * as path from 'path';
import {mainXi18n} from '../src/extract_i18n'; import {isInBazel, makeTempDir, setup} from './test_support'; function getNgRootDir() { const moduleFilename = module.filename.replace(/\\/g, '/'); const distIndex = moduleFilename.indexOf('/dist/all'); return moduleFilename.substr(0, distIndex); } const EXPECTED...
import * as ts from 'typescript';
random_line_split
extract_i18n_spec.ts
* found in the LICENSE file at https://angular.io/license */ import * as fs from 'fs'; import * as path from 'path'; import * as ts from 'typescript'; import {mainXi18n} from '../src/extract_i18n'; import {isInBazel, makeTempDir, setup} from './test_support'; function getNgRootDir()
const EXPECTED_XMB = `<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE messagebundle [ <!ELEMENT messagebundle (msg)*> <!ATTLIST messagebundle class CDATA #IMPLIED> <!ELEMENT msg (#PCDATA|ph|source)*> <!ATTLIST msg id CDATA #IMPLIED> <!ATTLIST msg seq CDATA #IMPLIED> <!ATTLIST msg name CDATA #IMPLIED> <!ATTLIST msg...
{ const moduleFilename = module.filename.replace(/\\/g, '/'); const distIndex = moduleFilename.indexOf('/dist/all'); return moduleFilename.substr(0, distIndex); }
identifier_body
extract_i18n_spec.ts
* found in the LICENSE file at https://angular.io/license */ import * as fs from 'fs'; import * as path from 'path'; import * as ts from 'typescript'; import {mainXi18n} from '../src/extract_i18n'; import {isInBazel, makeTempDir, setup} from './test_support'; function getNgRootDir() { const moduleFilename = mo...
() { write('src/basic.html', [ `<div title="translate me" i18n-title="meaning|desc"></div>`, `<p id="welcomeMessage"><!--i18n-->Welcome<!--/i18n--></p>`, ].join('\n')); write('src/module.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'basic', ...
writeSources
identifier_name
StreamService.py
from Source import Source from Components.Element import cached from Components.SystemInfo import SystemInfo from enigma import eServiceReference StreamServiceList = [] class StreamService(Source): def __init__(self, navcore): Source.__init__(self) self.ref = None self.__service = None self.navcore = navcore...
if self.__service.__deref__() in StreamServiceList: StreamServiceList.remove(self.__service.__deref__()) self.navcore.stopRecordService(self.__service) self.__service = None self.ref = None
conditional_block
StreamService.py
from Source import Source from Components.Element import cached from Components.SystemInfo import SystemInfo from enigma import eServiceReference StreamServiceList = [] class StreamService(Source): def __init__(self, navcore): Source.__init__(self) self.ref = None self.__service = None self.navcore = navcore...
(self, event): pass @cached def getService(self): return self.__service service = property(getService) def handleCommand(self, cmd): print "[StreamService] handle command", cmd self.ref = eServiceReference(cmd) def recordEvent(self, service, event): if service is self.__service: return print "[S...
serviceEvent
identifier_name
StreamService.py
from Source import Source from Components.Element import cached from Components.SystemInfo import SystemInfo from enigma import eServiceReference StreamServiceList = [] class StreamService(Source): def __init__(self, navcore): Source.__init__(self) self.ref = None self.__service = None self.navcore = navcore...
def execBegin(self): if self.ref is None: print "[StreamService] has no service ref set" return print "[StreamService]e execBegin", self.ref.toString() if SystemInfo["CanNotDoSimultaneousTranscodeAndPIP"]: from Screens.InfoBar import InfoBar if InfoBar.instance and hasattr(InfoBar.instance.session,...
if service is self.__service: return print "[StreamService] RECORD event for us:", service self.changed((self.CHANGED_ALL, ))
identifier_body
StreamService.py
from Source import Source from Components.Element import cached from Components.SystemInfo import SystemInfo from enigma import eServiceReference StreamServiceList = [] class StreamService(Source): def __init__(self, navcore): Source.__init__(self) self.ref = None self.__service = None self.navcore = navcore...
self.__service = self.navcore.recordService(self.ref) self.navcore.record_event.append(self.recordEvent) if self.__service is not None: if self.__service.__deref__() not in StreamServiceList: StreamServiceList.append(self.__service.__deref__()) self.__service.prepareStreaming() self.__service.start()...
hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP() print "[StreamService] try to disable pip before start stream" if hasattr(InfoBar.instance.session, 'pip'): del InfoBar.instance.session.pip InfoBar.instance.session.pipshown = False
random_line_split
model.py
# The content of this file was generated using the Python profile of libCellML 0.2.0. from enum import Enum from math import * __version__ = "0.3.0" LIBCELLML_VERSION = "0.2.0" STATE_COUNT = 1 VARIABLE_COUNT = 2 class VariableType(Enum): VARIABLE_OF_INTEGRATION = 1 STATE = 2 CONSTANT = 3 COMPUTED_...
variables[0] = 2.0*voi variables[1] = 3.0*variables[0]
identifier_body
model.py
# The content of this file was generated using the Python profile of libCellML 0.2.0. from enum import Enum from math import * __version__ = "0.3.0" LIBCELLML_VERSION = "0.2.0" STATE_COUNT = 1 VARIABLE_COUNT = 2 class VariableType(Enum): VARIABLE_OF_INTEGRATION = 1 STATE = 2 CONSTANT = 3 COMPUTED_...
(): return [nan]*VARIABLE_COUNT def initialise_states_and_constants(states, variables): states[0] = 0.0 def compute_computed_constants(variables): pass def compute_rates(voi, states, rates, variables): rates[0] = 1.0 def compute_variables(voi, states, rates, variables): variables[0] = 2.0*vo...
create_variables_array
identifier_name
model.py
# The content of this file was generated using the Python profile of libCellML 0.2.0. from enum import Enum from math import * __version__ = "0.3.0" LIBCELLML_VERSION = "0.2.0" STATE_COUNT = 1 VARIABLE_COUNT = 2 class VariableType(Enum): VARIABLE_OF_INTEGRATION = 1 STATE = 2 CONSTANT = 3 COMPUTED_...
def compute_rates(voi, states, rates, variables): rates[0] = 1.0 def compute_variables(voi, states, rates, variables): variables[0] = 2.0*voi variables[1] = 3.0*variables[0]
pass
random_line_split
lib.rs
#![deny(unused)] #![feature(collections, hash, io, libc, os, path, std_misc, unicode, env, core)] #![cfg_attr(test, deny(warnings))] extern crate libc; extern crate "rustc-serialize" as rustc_serialize; extern crate regex; extern crate term; extern crate time; #[macro_use] extern crate log; extern crate curl; extern ...
let json = try!(json_from_stdin::<U>()); exec(flags, json, shell) } pub fn execute_main_without_stdin<T, V>( exec: fn(T, &Config) -> CliResult<Option<V>>, options_first: bool, usage: &str) whe...
args: &[String], options_first: bool) -> CliResult<Option<V>> where V: Encodable, T: Decodable, U: Decodable { let flags = try!(flags_from_args::<T>(usage, args, options_first));
random_line_split
lib.rs
#![deny(unused)] #![feature(collections, hash, io, libc, os, path, std_misc, unicode, env, core)] #![cfg_attr(test, deny(warnings))] extern crate libc; extern crate "rustc-serialize" as rustc_serialize; extern crate regex; extern crate term; extern crate time; #[macro_use] extern crate log; extern crate curl; extern ...
print(cause.to_string(), shell); err = cause.cause(); } fn print(error: String, shell: &mut MultiShell) { let _ = shell.err().say("\nCaused by:", BLACK); let _ = shell.err().say(format!(" {}", error), BLACK); } } pub fn version() -> String { format!("cargo {}", match ...
{ return false }
conditional_block
lib.rs
#![deny(unused)] #![feature(collections, hash, io, libc, os, path, std_misc, unicode, env, core)] #![cfg_attr(test, deny(warnings))] extern crate libc; extern crate "rustc-serialize" as rustc_serialize; extern crate regex; extern crate term; extern crate time; #[macro_use] extern crate log; extern crate curl; extern ...
pub fn call_main<T, U, V>( exec: fn(T, U, &Config) -> CliResult<Option<V>>, shell: &Config, usage: &str, args: &[String], options_first: bool) -> CliResult<Option<V>> where V: Encodable, T: Decodable, U: Decodable { let flags = try!(flags_from_args::...
{ process::<V, _>(|rest, shell| { call_main(exec, shell, usage, rest, options_first) }); }
identifier_body
lib.rs
#![deny(unused)] #![feature(collections, hash, io, libc, os, path, std_misc, unicode, env, core)] #![cfg_attr(test, deny(warnings))] extern crate libc; extern crate "rustc-serialize" as rustc_serialize; extern crate regex; extern crate term; extern crate time; #[macro_use] extern crate log; extern crate curl; extern ...
<'a, T>(usage: &str, args: &[String], options_first: bool) -> CliResult<T> where T: Decodable { let docopt = Docopt::new(usage).unwrap() .options_first(options_first) .argv(args.iter().map(|s| s.as_slice())) ...
flags_from_args
identifier_name
LoadingJobSpecsState.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 ...
loadingError: null, apiReturnedNoJobSpecs: true, }); } else { this.setState({ isLoading: false, loadingError: null, apiReturnedNoJobSpecs: false, }, () => { this.transitionToLoadingFreshJob(jobSpecs); }); } } transitionToLoadingExistingJob(jobSpecs: APIJobSpecSummary[], existi...
routeParams["based-on"]); }); } else if (jobSpecs.length === 0) { this.setState({ isLoading: false,
random_line_split
LoadingJobSpecsState.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 ...
(this.state.isLoading) { return LoadingJobSpecsState.renderLoadingMessage(); } else if (this.state.loadingError !== null) { return this.renderErrorMessage(this.state.loadingError); } else if (this.state.apiReturnedNoJobSpecs) { return LoadingJobSpecsState.renderNoJobSpecsAvailableMessage(); } else { ...
if
identifier_name
LoadingJobSpecsState.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 ...
static renderNoJobSpecsAvailableMessage() { return ( <div className="ui info icon message"> <i className="info circle icon"/> <div className="content"> <div className="header"> No jobs yet! </div> <p> The server doesn't appear to have any jobs you can submit. This is pro...
{ return { spec: null, name: "default", inputs: {}, }; }
identifier_body
number_pipe.ts
import { isNumber, isPresent, isBlank, StringWrapper, NumberWrapper, RegExpWrapper, BaseException, CONST, FunctionWrapper } from 'angular2/src/facade/lang'; import {NumberFormatter, NumberFormatStyle} from 'angular2/src/facade/intl'; import {ListWrapper} from 'angular2/src/facade/collection'; import {...
var minInt = 1, minFraction = 0, maxFraction = 3; if (isPresent(digits)) { var parts = RegExpWrapper.firstMatch(_re, digits); if (isBlank(parts)) { throw new BaseException(`${digits} is not a valid digit info for number pipes`); } if (isPresent(parts[1])) { // min integer digits...
export class NumberPipe extends BasePipe implements PipeFactory { static _format(value: number, style: NumberFormatStyle, digits: string, currency: string = null, currencyAsSymbol: boolean = false): string {
random_line_split
number_pipe.ts
import { isNumber, isPresent, isBlank, StringWrapper, NumberWrapper, RegExpWrapper, BaseException, CONST, FunctionWrapper } from 'angular2/src/facade/lang'; import {NumberFormatter, NumberFormatStyle} from 'angular2/src/facade/intl'; import {ListWrapper} from 'angular2/src/facade/collection'; import {...
(obj): boolean { return isNumber(obj); } create(cdRef: ChangeDetectorRef): Pipe { return this; } } /** * Formats a number as local text. i.e. group sizing and seperator and other locale-specific * configurations are based on the active locale. * * # Usage * * expression | number[:digitInfo] * * where `e...
supports
identifier_name
number_pipe.ts
import { isNumber, isPresent, isBlank, StringWrapper, NumberWrapper, RegExpWrapper, BaseException, CONST, FunctionWrapper } from 'angular2/src/facade/lang'; import {NumberFormatter, NumberFormatStyle} from 'angular2/src/facade/intl'; import {ListWrapper} from 'angular2/src/facade/collection'; import {...
return NumberFormatter.format(value, defaultLocale, style, { minimumIntegerDigits: minInt, minimumFractionDigits: minFraction, maximumFractionDigits: maxFraction, currency: currency, currencyAsSymbol: currencyAsSymbol }); } supports(obj): boolean { return isNumber(obj); } ...
{ var parts = RegExpWrapper.firstMatch(_re, digits); if (isBlank(parts)) { throw new BaseException(`${digits} is not a valid digit info for number pipes`); } if (isPresent(parts[1])) { // min integer digits minInt = NumberWrapper.parseIntAutoRadix(parts[1]); } if (is...
conditional_block
ProductsListWindow.js
var // get util library util = require("core/Util"), // get product manager ProductManager = require("core/ProductManager"); function ProductListWindow() { var Window = Ti.UI.createWindow({ title : L("products"), navBarHidden : false, barColor : Theme.TabGroup.BarColor, navTintCo...
products[i].name, products[i].imgs.thumb, products[i].desc.short, products[i].id ) ); } return productGroup; } /* * Assemble product groups for table view * * @param {Object} groups: the groups object containing product arrays for each group/section */ function displayProducts...
}); for(var i=0,l=products.length;i<l;i++){ productGroup.add( createRow(
random_line_split
ProductsListWindow.js
var // get util library util = require("core/Util"), // get product manager ProductManager = require("core/ProductManager"); function ProductListWindow() { var Window = Ti.UI.createWindow({ title : L("products"), navBarHidden : false, barColor : Theme.TabGroup.BarColor, navTintC...
(name, products){ var productGroupHeader = Ti.UI.createLabel({ text : " "+name, //add space for padding (border not working for left padding) textAlign : Ti.UI.TEXT_ALIGNMENT_LEFT, color : Theme.ProductsList.HeaderColor, backgroundColor : Theme.ProductsList.Heade...
createProductGroup
identifier_name
ProductsListWindow.js
var // get util library util = require("core/Util"), // get product manager ProductManager = require("core/ProductManager"); function ProductListWindow() { var Window = Ti.UI.createWindow({ title : L("products"), navBarHidden : false, barColor : Theme.TabGroup.BarColor, navTintC...
text : name, minimumFontSize : 12, color : Theme.ProductsList.TitleColor, height : Ti.UI.SIZE, left : 2, top : 4, font : { fontSize : Theme.ProductsList.TitleFontSize, fontWeight : Theme.ProductsList.TitleFontWeight } })...
{ var row = Ti.UI.createTableViewRow({ className : "product_rows", backgroundColor : Theme.ProductsList.RowsBackgroundColor, selectedBackgroundColor : Theme.ProductsList.SelectedBackgroundColor, hasChild : true }), img = Ti.UI.createImageView({ image : image, left : 1, ...
identifier_body
ProductsListWindow.js
var // get util library util = require("core/Util"), // get product manager ProductManager = require("core/ProductManager"); function ProductListWindow() { var Window = Ti.UI.createWindow({ title : L("products"), navBarHidden : false, barColor : Theme.TabGroup.BarColor, navTintC...
else{ img.width = 81; bodyView.left = 82; bodyView.height = Ti.UI.SIZE; } row.add(bodyView); // handle featured item click event row.addEventListener( "click", function(e){ Ti.App.fireEvent( "APP:SHOW_PRODUCT", { "itemId" : itemId, "tab" : "Products" } ); } ); ...
{ img.width = Theme.ProductsList.ImageWidth + "dip"; img.height = Theme.ProductsList.ImageHeight + "dip"; bodyView.left = (Theme.ProductsList.ImageWidth + 1) + "dip"; bodyView.right = "3dip"; bodyView.top = 0; bodyView.bottom = 0; body.height = Ti.UI.SIZE; }
conditional_block
plot_throughput_factor_experiment.py
modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions ...
if self.whisk_bott is not None: ax.broken_barh([(index - w2, width)], (self.whisk_bott,0), facecolor="white", edgecolor=whisker_color, lw=0.5) ax.broken_barh([(index , 0)], (self.whisk_bott,self.bott-self.w...
ax.broken_barh([(index - w2, width)], (self.whisk_top,0), facecolor="white", edgecolor=whisker_color, lw=0.5) ax.broken_barh([(index , 0)], (self.whisk_top, self.top-self.whisk_top), edgecolor=box_col...
conditional_block
plot_throughput_factor_experiment.py
modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions ...
###################################### if len(sys.argv) < 2: print "usage: plot_switch_experiment.py <input dir1> <input1 label> " \ "<input dir2> <input2 label> ... <output file>" sys.exit(1) paper_mode = True if paper_mode: set_paper_rcs() # arg processing if (len(sys.argv) - 1) % 2 == 1: # odd n...
base_worst = 4.0 * 3 #base_worst = 0.566 #packet_time = (plength + 18.0) * 8.0 / 10.0 / 1000.0 packet_time = plength * 8.0 / 10.0 / 1000.0 tmp = [x * (packet_time * trainlength) for x in setups] worst = [x + base_worst for x in tmp] for i in range(len(worst)): print "WORST CASE %d: %f" % (setups[i], wo...
identifier_body
plot_throughput_factor_experiment.py
, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the follo...
(setups, trainlength, plength): base_worst = 4.0 * 3 #base_worst = 0.566 #packet_time = (plength + 18.0) * 8.0 / 10.0 / 1000.0 packet_time = plength * 8.0 / 10.0 / 1000.0 tmp = [x * (packet_time * trainlength) for x in setups] worst = [x + base_worst for x in tmp] for i in range(len(worst)): print "W...
worst_case_approx
identifier_name
plot_throughput_factor_experiment.py
modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions ...
# parsing data = [] negs_ignored = 0 for indir in inputdirs: ds = [] for line in open(indir).readlines(): #for line in open(indir).readlines(): if line.strip() == "": continue val = float(line.strip()) / 1000.0 if val > 0: ds.append(val) else: negs_ignored += 1 data.append(ds)...
random_line_split
test_init.py
"""Test Agent DVR integration.""" from unittest.mock import AsyncMock, patch from agent import AgentError from homeassistant.components.agent_dvr.const import DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from . import CONF_DATA, create_entry from test...
(hass: HomeAssistant): """Test that it throws ConfigEntryNotReady when exception occurs during setup.""" entry = create_entry(hass) with patch( "homeassistant.components.agent_dvr.Agent.update", side_effect=AgentError, ): await hass.config_entries.async_setup(entry.entry_id) ...
test_async_setup_entry_not_ready
identifier_name
test_init.py
"""Test Agent DVR integration.""" from unittest.mock import AsyncMock, patch
from homeassistant.components.agent_dvr.const import DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from . import CONF_DATA, create_entry from tests.components.agent_dvr import init_integration from tests.test_util.aiohttp import AiohttpClientMocker asy...
from agent import AgentError
random_line_split
test_init.py
"""Test Agent DVR integration.""" from unittest.mock import AsyncMock, patch from agent import AgentError from homeassistant.components.agent_dvr.const import DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from . import CONF_DATA, create_entry from test...
def _patch_init_agent(mocked_agent): return patch( "homeassistant.components.agent_dvr.Agent", return_value=mocked_agent, ) async def test_setup_config_and_unload( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ): """Test setup and unload.""" entry = await init_integra...
mocked_agent = AsyncMock() mocked_agent.is_available = available return mocked_agent
identifier_body
cmp.rs
use rational_sequences::RationalSequence; use std::cmp::Ordering; impl<T: Eq + Ord> PartialOrd for RationalSequence<T> { /// Compares a `RationalSequence` to another `RationalSequence`. /// /// See the documentation for the `Ord` implementation. #[inline] fn partial_cmp(&self, other: &RationalSeque...
/// assert!( /// RationalSequence::from_slice(&[1, 2, 3]) < /// RationalSequence::from_slices(&[1, 2], &[3, 4]) /// ); /// ``` fn cmp(&self, other: &RationalSequence<T>) -> Ordering { if self == other { Ordering::Equal } else { Iterator::cmp(se...
random_line_split
cmp.rs
use rational_sequences::RationalSequence; use std::cmp::Ordering; impl<T: Eq + Ord> PartialOrd for RationalSequence<T> { /// Compares a `RationalSequence` to another `RationalSequence`. /// /// See the documentation for the `Ord` implementation. #[inline] fn partial_cmp(&self, other: &RationalSeque...
} }
{ Iterator::cmp(self.iter(), other.iter()) }
conditional_block
cmp.rs
use rational_sequences::RationalSequence; use std::cmp::Ordering; impl<T: Eq + Ord> PartialOrd for RationalSequence<T> { /// Compares a `RationalSequence` to another `RationalSequence`. /// /// See the documentation for the `Ord` implementation. #[inline] fn partial_cmp(&self, other: &RationalSeque...
}
{ if self == other { Ordering::Equal } else { Iterator::cmp(self.iter(), other.iter()) } }
identifier_body
cmp.rs
use rational_sequences::RationalSequence; use std::cmp::Ordering; impl<T: Eq + Ord> PartialOrd for RationalSequence<T> { /// Compares a `RationalSequence` to another `RationalSequence`. /// /// See the documentation for the `Ord` implementation. #[inline] fn partial_cmp(&self, other: &RationalSeque...
(&self, other: &RationalSequence<T>) -> Ordering { if self == other { Ordering::Equal } else { Iterator::cmp(self.iter(), other.iter()) } } }
cmp
identifier_name
panel.js
/** * @ignore * single tab panel. * @author yiminghe@gmail.com */ var Container = require('component/container'); /** * KISSY.Tabs.Panel.xclass: 'tabs-panel'. * @class KISSY.Tabs.Panel * @extends KISSY.Component.Container */ module.exports = Container.extend({ isTabsPanel: 1, beforeCreateDom: function...
}, _onSetSelected: function (v) { var el = this.$el; var selectedCls = this.getBaseCssClasses('selected'); el[v ? 'addClass' : 'removeClass'](selectedCls) .attr('aria-hidden', !v); } }, { ATTRS: { allowTextSelection: { value: true }, ...
{ renderData.elAttrs['aria-hidden'] = false; }
conditional_block
panel.js
* single tab panel. * @author yiminghe@gmail.com */ var Container = require('component/container'); /** * KISSY.Tabs.Panel.xclass: 'tabs-panel'. * @class KISSY.Tabs.Panel * @extends KISSY.Component.Container */ module.exports = Container.extend({ isTabsPanel: 1, beforeCreateDom: function (renderData) {...
/** * @ignore
random_line_split
OrgCommonService.ts
'use strict'; import angular, { IRootScopeService } from 'angular'; import _ from 'lodash'; import { ICapabilitiesService } from '../../../capabilities/client/services/CapabilitiesService'; import { ICapability } from '../../../capabilities/shared/ICapabilityDTO'; import { IOrg } from '../../shared/IOrgDTO'; export i...
public isOrgCapable(org: IOrg): boolean { const orgCapabilities = this.getOrgCapabilities(org); const overlap = _.intersectionWith(this.allCapabilities, orgCapabilities, (cap1, cap2) => cap1.code === cap2.code); return overlap.length === this.allCapabilities.length; } private getOrgCapabilities(org: IOrg): ...
{ return org.members.length >= 2 && org.isAcceptedTerms && this.isOrgCapable(org); }
identifier_body
OrgCommonService.ts
'use strict'; import angular, { IRootScopeService } from 'angular'; import _ from 'lodash'; import { ICapabilitiesService } from '../../../capabilities/client/services/CapabilitiesService'; import { ICapability } from '../../../capabilities/shared/ICapabilityDTO'; import { IOrg } from '../../shared/IOrgDTO'; export i...
} // Checks that the given org has met the RFQ by checking: // - that the org has at least 2 team members // - that the org team members collectively cover all capabilities // - that the org has accepted the terms of the RFQ public hasOrgMetRFQ(org: IOrg): boolean { return org.members.length >= 2 && org.isAcce...
this.allCapabilities = this.CapabilitiesService.list(); this.$rootScope.$on('capabilitiesChanged', () => { this.allCapabilities = this.CapabilitiesService.list(); });
random_line_split
OrgCommonService.ts
'use strict'; import angular, { IRootScopeService } from 'angular'; import _ from 'lodash'; import { ICapabilitiesService } from '../../../capabilities/client/services/CapabilitiesService'; import { ICapability } from '../../../capabilities/shared/ICapabilityDTO'; import { IOrg } from '../../shared/IOrgDTO'; export i...
implements IOrgCommonService { private allCapabilities: ICapability[]; constructor(private $rootScope: IRootScopeService, private CapabilitiesService: ICapabilitiesService) { this.allCapabilities = this.CapabilitiesService.list(); this.$rootScope.$on('capabilitiesChanged', () => { this.allCapabilities = this...
OrgCommonService
identifier_name
index.tsx
import React from 'react' import * as Kb from '../../common-adapters' import * as Styles from '../../styles' import * as TeamsGen from '../../actions/teams-gen' import * as Container from '../../util/container' import * as Constants from '../../constants/teams' import * as Types from '../../constants/types/teams' impor...
return ( <Kb.Modal mode="Default" banners={ error ? [ <Kb.Banner color="red" key="err"> {error} </Kb.Banner>, ] : undefined } onClose={onClose} footer={{ content: ( <Kb.ButtonBar fu...
}, [waiting, wasWaiting, nav, dispatch, error])
random_line_split
bulletChart.js
"use strict"; //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var bullet = nv.models.bullet() ; var orient = 'left' // TODO top & bottom , reverse = false ...
var rangez = ranges.call(this, d, i).slice().sort(d3.descending), markerz = markers.call(this, d, i).slice().sort(d3.descending), measurez = measures.call(this, d, i).slice().sort(d3.descending); // Setup containers and skeleton of chart var wrap = ...
{ container.selectAll('.nv-noData').remove(); }
conditional_block
bulletChart.js
"use strict"; //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var bullet = nv.models.bullet() ; var orient = 'left' // TODO top & bottom , reverse = false ...
var gEnter = wrapEnter.append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-bulletWrap'); gEnter.append('g').attr('class', 'nv-titles'); wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); // Compu...
var wrap = container.selectAll('g.nv-wrap.nv-bulletChart').data([d]); var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bulletChart');
random_line_split
bulletChart.js
{ "use strict"; //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var bullet = nv.models.bullet() ; var orient = 'left' // TODO top & bottom , reverse = false...
(selection) { selection.each(function(d, i) { var container = d3.select(this); nv.utils.initSVG(container); var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = height -...
chart
identifier_name
bulletChart.js
{ "use strict"; //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var bullet = nv.models.bullet() ; var orient = 'left' // TODO top & bottom , reverse = false...
.style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', 18 + margin.top + availableHeight / 2) .text(function(d) { return d }); return chart; } else {...
{ selection.each(function(d, i) { var container = d3.select(this); nv.utils.initSVG(container); var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight = height - margin.top ...
identifier_body
chap06.rs
/* * Chap.6 Enum and Pattern Matching * */ #[derive(Debug)] enum MonitorState { Success, Warning, Error, } #[derive(Debug)]
state: MonitorState, } #[derive(Debug)] enum ServicePort { HTTP(u32), HTTPS(u32), } #[derive(Debug)] enum Service { API(String, ServicePort), Frontend(String, ServicePort), } #[derive(Debug)] enum NamedPort { HTTPS = 443, } #[derive(Debug)] enum ServiceAction { Reload, //...
struct Monitor { service: String,
random_line_split
chap06.rs
/* * Chap.6 Enum and Pattern Matching * */ #[derive(Debug)] enum MonitorState { Success, Warning, Error, } #[derive(Debug)] struct Monitor { service: String, state: MonitorState, } #[derive(Debug)] enum ServicePort { HTTP(u32), HTTPS(u32), } #[derive(Debug)] enum Service { API(Str...
(num: Option<i32>) -> i32 { match num { None => 0, Some(i) => i, } }
handle_option_normalization
identifier_name
analytics.service.ts
import { Injectable } from '@angular/core'; import { PlatformService } from './platform.service'; import { environment } from '../../environments/environment'; @Injectable() export class AnalyticsService { dataLayer; private _debug = true; constructor( private platform: PlatformService ) { // grab glo...
// tslint:disable-next-line environment.production || !this._debug ? null : console.debug.apply(console, [ 'analytics: ', ...args]); } }
private debug(...args) {
random_line_split
analytics.service.ts
import { Injectable } from '@angular/core'; import { PlatformService } from './platform.service'; import { environment } from '../../environments/environment'; @Injectable() export class AnalyticsService { dataLayer; private _debug = true; constructor( private platform: PlatformService )
/** * Pushes the event to the global dataLayer array that * Google Tag Manager is watching. * @param id string of the event name * @param data object of event data */ trackEvent(id: string, data: any = {}) { // do not track unless in production if (!environment.production) { this.debu...
{ // grab global dataLayer from window this.dataLayer = platform.nativeWindow.dataLayer; }
identifier_body
analytics.service.ts
import { Injectable } from '@angular/core'; import { PlatformService } from './platform.service'; import { environment } from '../../environments/environment'; @Injectable() export class AnalyticsService { dataLayer; private _debug = true; constructor( private platform: PlatformService ) { // grab glo...
const event = { event: id, ...data }; this.dataLayer.push(event); } private debug(...args) { // tslint:disable-next-line environment.production || !this._debug ? null : console.debug.apply(console, [ 'analytics: ', ...args]); } }
{ throw Error('dataLayer does not exist'); }
conditional_block
analytics.service.ts
import { Injectable } from '@angular/core'; import { PlatformService } from './platform.service'; import { environment } from '../../environments/environment'; @Injectable() export class AnalyticsService { dataLayer; private _debug = true; constructor( private platform: PlatformService ) { // grab glo...
(id: string, data: any = {}) { // do not track unless in production if (!environment.production) { this.debug(`tracking ${id}`, data); return; } if (!this.dataLayer) { throw Error('dataLayer does not exist'); } const event = { event: id, ...data }; this.dataLayer.push(event); } ...
trackEvent
identifier_name
data.py
digest()) def Bits2Target(bits): return struct.unpack('<L', bits[:3] + b'\0')[0] * 2**(8*(bits[3] - 3)) class ChecksummedType(pack.Type): def __init__(self, inner, checksum_func=lambda data: hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]): self.inner = inner self.checksum_func = ch...
data = self.inner.pack(item) return (file, data), self.checksum_func(data) class FloatingInteger(object): __slots__ = ['bits', '_target'] @classmethod def from_target_upper_bound(cls, target): n = math.natural_to_string(target) if n and ord(n[0]) >= 128: n =...
def write(self, file, item):
random_line_split
data.py
(data): if data == '04ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664b'.decode('hex'): return 0x384f570ccc88ac2e7e00b026d1690a3fca63dd0 # hack for people who don't have openssl - this is the only value that p2pool ever hashes ...
hash160
identifier_name