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
self-impl-2.rs
// run-pass #![allow(dead_code)] #![allow(unused_variables)] // Test that we can use `Self` types in impls in the expected way. // pretty-expanded FIXME #23616 struct Foo; // Test uses on inherent impl. impl Foo { fn foo(_x: Self, _y: &Self, _z: Box<Self>) -> Self { Foo } fn baz()
fn empty() {} } // Test uses when implementing a trait and with a type parameter. pub struct Baz<X> { pub f: X, } trait SuperBar { type SuperQux; } trait Bar<X>: SuperBar { type Qux; fn bar(x: Self, y: &Self, z: Box<Self>, _: Self::SuperQux) -> Self; fn dummy(&self, x: X) { } } impl Super...
{ // Test that Self cannot be shadowed. type Foo = i32; // There is no empty method on i32. Self::empty(); let _: Self = Foo; }
identifier_body
025.py
#!/usr/bin/env python #coding:utf-8 """ 1000-digit Fibonacci number The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term...
port time tStart=time.time() answer() print 'run time=',time.time()-tStart # 4782 # run time= 0.0710821151733
for i in Fibonacci(): a+=1 if len(str(i))>=1000: print a break im
identifier_body
025.py
#!/usr/bin/env python #coding:utf-8 """ 1000-digit Fibonacci number
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the first term in the Fibonacci sequence to contain 1000 digits? """ def ...
The Fibonacci sequence is defined by the recurrence relation:
random_line_split
025.py
#!/usr/bin/env python #coding:utf-8 """ 1000-digit Fibonacci number The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term...
port time tStart=time.time() answer() print 'run time=',time.time()-tStart # 4782 # run time= 0.0710821151733
t a break im
conditional_block
025.py
#!/usr/bin/env python #coding:utf-8 """ 1000-digit Fibonacci number The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term...
a=0 for i in Fibonacci(): a+=1 if len(str(i))>=1000: print a break import time tStart=time.time() answer() print 'run time=',time.time()-tStart # 4782 # run time= 0.0710821151733
er():
identifier_name
intersect.py
# # intersect.py # PolyBoRi # # Created by Michael Brickenstein on 2008-09-24. # Copyright 2008 The PolyBoRi Team # from .gbcore import groebner_basis from .statistics import used_vars_set from itertools import chain def intersect(i, j, **gb_opts): """ This functions intersects two ideals. The first ring...
import doctest doctest.testmod() if __name__ == "__main__": _test()
random_line_split
intersect.py
# # intersect.py # PolyBoRi # # Created by Michael Brickenstein on 2008-09-24. # Copyright 2008 The PolyBoRi Team # from .gbcore import groebner_basis from .statistics import used_vars_set from itertools import chain def
(i, j, **gb_opts): """ This functions intersects two ideals. The first ring variable is used as helper variable for this intersection. It is assumed, that it doesn't occur in the ideals, and that we have an elimination ordering for this variables. Both assumptions are checked. >>> from brial.fronten...
intersect
identifier_name
intersect.py
# # intersect.py # PolyBoRi # # Created by Michael Brickenstein on 2008-09-24. # Copyright 2008 The PolyBoRi Team # from .gbcore import groebner_basis from .statistics import used_vars_set from itertools import chain def intersect(i, j, **gb_opts):
gb = groebner_basis(list(chain((t * p for p in i), ((1 + t) * p for p in j ))), **gb_opts) return [p for p in gb if p.navigation().value() > t.index()] def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
""" This functions intersects two ideals. The first ring variable is used as helper variable for this intersection. It is assumed, that it doesn't occur in the ideals, and that we have an elimination ordering for this variables. Both assumptions are checked. >>> from brial.frontend import declare_ring ...
identifier_body
intersect.py
# # intersect.py # PolyBoRi # # Created by Michael Brickenstein on 2008-09-24. # Copyright 2008 The PolyBoRi Team # from .gbcore import groebner_basis from .statistics import used_vars_set from itertools import chain def intersect(i, j, **gb_opts): """ This functions intersects two ideals. The first ring...
if not t > uv: raise ValueError("need elimination ordering for first ring variable") gb = groebner_basis(list(chain((t * p for p in i), ((1 + t) * p for p in j ))), **gb_opts) return [p for p in gb if p.navigation().value() > t.index()] def _test(): import doctest doctest.testmod(...
raise ValueError("First ring variable has to be reserved as helper variable t")
conditional_block
mempool_limit.py
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mempool limiting together/eviction with the wallet.""" from test_framework.test_framework import ...
(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 self.extra_args = [["-maxmempool=5", "-mintxfee=0.00001", "-spendzeroconfchange=0"]] def run_test(self): txouts = gen_return_txouts() relayfee = self.nodes[0].getnetworkin...
MempoolLimitTest
identifier_name
mempool_limit.py
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mempool limiting together/eviction with the wallet.""" from test_framework.test_framework import ...
tx = self.nodes[0].createrawtransaction(inputs, outputs) self.nodes[0].settxfee(relayfee) # specifically fund this tx with low fee txF = self.nodes[0].fundrawtransaction(tx) self.nodes[0].settxfee(0) # return to automatic fee selection txFS = self.nodes[0].signrawtransaction(txF[...
def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 self.extra_args = [["-maxmempool=5", "-mintxfee=0.00001", "-spendzeroconfchange=0"]] def run_test(self): txouts = gen_return_txouts() relayfee = self.nodes[0].getnetworkinfo()['relayfee'] se...
identifier_body
mempool_limit.py
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mempool limiting together/eviction with the wallet.""" from test_framework.test_framework import ...
MempoolLimitTest().main()
conditional_block
mempool_limit.py
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mempool limiting together/eviction with the wallet.""" from test_framework.test_framework import ...
self.extra_args = [["-maxmempool=5", "-mintxfee=0.00001", "-spendzeroconfchange=0"]] def run_test(self): txouts = gen_return_txouts() relayfee = self.nodes[0].getnetworkinfo()['relayfee'] self.log.info('Check that mempoolminfee is minrelytxfee') assert_equal(self.nodes[0].g...
self.num_nodes = 1
random_line_split
move_to_front_algo.py
from __future__ import print_function from string import ascii_lowercase SYMBOLTABLE = list(ascii_lowercase) def move2front_encode(strng, symboltable): sequence, pad = [], symboltable[::] for char in strng: indx = pad.index(char) sequence.append(indx) pad = [pad.pop(indx)] + pad re...
return ''.join(chars) if __name__ == '__main__': for s in ['broood', 'bananaaa', 'hiphophiphop']: encode = move2front_encode(s, SYMBOLTABLE) print('%14r encodes to %r' % (s, encode), end=', ') decode = move2front_decode(encode, SYMBOLTABLE) print('which decodes back to %r' % de...
char = pad[indx] chars.append(char) pad = [pad.pop(indx)] + pad
conditional_block
move_to_front_algo.py
from __future__ import print_function from string import ascii_lowercase SYMBOLTABLE = list(ascii_lowercase) def move2front_encode(strng, symboltable): sequence, pad = [], symboltable[::] for char in strng: indx = pad.index(char) sequence.append(indx) pad = [pad.pop(indx)] + pad re...
if __name__ == '__main__': for s in ['broood', 'bananaaa', 'hiphophiphop']: encode = move2front_encode(s, SYMBOLTABLE) print('%14r encodes to %r' % (s, encode), end=', ') decode = move2front_decode(encode, SYMBOLTABLE) print('which decodes back to %r' % decode)
chars, pad = [], symboltable[::] for indx in sequence: char = pad[indx] chars.append(char) pad = [pad.pop(indx)] + pad return ''.join(chars)
identifier_body
move_to_front_algo.py
from __future__ import print_function from string import ascii_lowercase SYMBOLTABLE = list(ascii_lowercase) def move2front_encode(strng, symboltable): sequence, pad = [], symboltable[::] for char in strng: indx = pad.index(char) sequence.append(indx) pad = [pad.pop(indx)] + pad re...
print('which decodes back to %r' % decode)
random_line_split
move_to_front_algo.py
from __future__ import print_function from string import ascii_lowercase SYMBOLTABLE = list(ascii_lowercase) def
(strng, symboltable): sequence, pad = [], symboltable[::] for char in strng: indx = pad.index(char) sequence.append(indx) pad = [pad.pop(indx)] + pad return sequence def move2front_decode(sequence, symboltable): chars, pad = [], symboltable[::] for indx in sequence: ...
move2front_encode
identifier_name
DropdownMenuItem.tsx
import * as React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { prefix, getUnhandledProps, defaultProps } from '../utils'; export interface DropdownMenuItemProps { classPrefix: string; componentClass?: React.ElementType; active?: boolean; disabled?: boolean; ...
}; render() { const { active, onKeyDown, disabled, focus, children, className, classPrefix, componentClass: Component, ...rest } = this.props; const addPrefix = prefix(classPrefix); const classes = classNames(classPrefix, { [addPrefix('a...
{ onSelect(value, event); }
conditional_block
DropdownMenuItem.tsx
import * as React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { prefix, getUnhandledProps, defaultProps } from '../utils'; export interface DropdownMenuItemProps { classPrefix: string; componentClass?: React.ElementType; active?: boolean; disabled?: boolean; ...
extends React.Component<DropdownMenuItemProps> { static propTypes = { classPrefix: PropTypes.string.isRequired, active: PropTypes.bool, disabled: PropTypes.bool, value: PropTypes.any, onSelect: PropTypes.func, onKeyDown: PropTypes.func, focus: PropTypes.bool, title: PropTypes.string, ...
DropdownMenuItem
identifier_name
DropdownMenuItem.tsx
import * as React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { prefix, getUnhandledProps, defaultProps } from '../utils'; export interface DropdownMenuItemProps { classPrefix: string; componentClass?: React.ElementType; active?: boolean; disabled?: boolean; ...
const unhandled = getUnhandledProps(DropdownMenuItem, rest); return ( <Component {...unhandled} className={className} role="listitem"> <a className={classes} tabIndex={-1} onKeyDown={disabled ? null : onKeyDown} onClick={this.handleClick} > ...
{ const { active, onKeyDown, disabled, focus, children, className, classPrefix, componentClass: Component, ...rest } = this.props; const addPrefix = prefix(classPrefix); const classes = classNames(classPrefix, { [addPrefix('active')]: active, ...
identifier_body
DropdownMenuItem.tsx
import * as React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { prefix, getUnhandledProps, defaultProps } from '../utils'; export interface DropdownMenuItemProps { classPrefix: string; componentClass?: React.ElementType; active?: boolean; disabled?: boolean; ...
})(DropdownMenuItem);
classPrefix: 'dropdown-menu-item'
random_line_split
home.component.ts
import { Component, Injectable, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { UserService } from '../../service/user.service'; import template from './home.component.html'; import { googlePlacesAPI } from '../../config'; import { CovoiturageListComponent } from '../covoiturage/covoit...
onActivate(component) { if (component instanceof CovoiturageListComponent) { this.listCom = component; } else { this.listCom = null; } } resetSearch(input) { if (this.listCom) { this.listCom.resetSearch(); } else { th...
{ this.userService.logout(); this.router.navigate(['/login']); }
identifier_body
home.component.ts
import { Component, Injectable, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { UserService } from '../../service/user.service';
@Component({ selector: 'app-home', template, styles: [ '#main_search .prompt{border-radius : 0rem;}' ] }) @Injectable() export class HomeComponent implements OnInit { error: string; listCom: CovoiturageListComponent; response: {}; constructor(private router: Router, pri...
import template from './home.component.html'; import { googlePlacesAPI } from '../../config'; import { CovoiturageListComponent } from '../covoiturage/covoit.component';
random_line_split
home.component.ts
import { Component, Injectable, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { UserService } from '../../service/user.service'; import template from './home.component.html'; import { googlePlacesAPI } from '../../config'; import { CovoiturageListComponent } from '../covoiturage/covoit...
(query) { this.listCom.search(query); } }
callSearch
identifier_name
home.component.ts
import { Component, Injectable, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { UserService } from '../../service/user.service'; import template from './home.component.html'; import { googlePlacesAPI } from '../../config'; import { CovoiturageListComponent } from '../covoiturage/covoit...
}) } } }); } logout() { this.userService.logout(); this.router.navigate(['/login']); } onActivate(component) { if (component instanceof CovoiturageListComponent) { this.listCom = component; } else ...
{ this.callSearch(query); }
conditional_block
multi_map_lock_codec.py
from hazelcast.serialization.bits import * from hazelcast.protocol.builtin import FixSizedTypesCodec from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer from hazelcast.protocol.builtin import StringCodec from hazelcast.protocol.builtin import DataCodec # hex: 0x021...
(name, key, thread_id, ttl, reference_id): buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE) FixSizedTypesCodec.encode_long(buf, _REQUEST_THREAD_ID_OFFSET, thread_id) FixSizedTypesCodec.encode_long(buf, _REQUEST_TTL_OFFSET, ttl) FixSizedTypesCodec.encode_long(buf, _REQUEST_...
encode_request
identifier_name
multi_map_lock_codec.py
from hazelcast.serialization.bits import * from hazelcast.protocol.builtin import FixSizedTypesCodec from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer from hazelcast.protocol.builtin import StringCodec from hazelcast.protocol.builtin import DataCodec # hex: 0x021...
def encode_request(name, key, thread_id, ttl, reference_id): buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE) FixSizedTypesCodec.encode_long(buf, _REQUEST_THREAD_ID_OFFSET, thread_id) FixSizedTypesCodec.encode_long(buf, _REQUEST_TTL_OFFSET, ttl) FixSizedTypesCodec.encode...
_REQUEST_THREAD_ID_OFFSET = REQUEST_HEADER_SIZE _REQUEST_TTL_OFFSET = _REQUEST_THREAD_ID_OFFSET + LONG_SIZE_IN_BYTES _REQUEST_REFERENCE_ID_OFFSET = _REQUEST_TTL_OFFSET + LONG_SIZE_IN_BYTES _REQUEST_INITIAL_FRAME_SIZE = _REQUEST_REFERENCE_ID_OFFSET + LONG_SIZE_IN_BYTES
random_line_split
multi_map_lock_codec.py
from hazelcast.serialization.bits import * from hazelcast.protocol.builtin import FixSizedTypesCodec from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer from hazelcast.protocol.builtin import StringCodec from hazelcast.protocol.builtin import DataCodec # hex: 0x021...
buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE) FixSizedTypesCodec.encode_long(buf, _REQUEST_THREAD_ID_OFFSET, thread_id) FixSizedTypesCodec.encode_long(buf, _REQUEST_TTL_OFFSET, ttl) FixSizedTypesCodec.encode_long(buf, _REQUEST_REFERENCE_ID_OFFSET, reference_id) StringCo...
identifier_body
AndroidPhoneNotify.py
# -*- coding: utf-8 -*- from time import time from module.network.RequestFactory import getURL from module.plugins.Hook import Hook class AndroidPhoneNotify(Hook): __name__ = "AndroidPhoneNotify" __type__ = "hook" __version__ = "0.04" __config__ = [("apikey" , "str" , "API key" ...
apikey = self.getConfig("apikey") if not apikey: return False if self.core.isClientConnected() and not self.getConfig("force"): return False getURL("http://www.notifymyandroid.com/publicapi/notify", get={'apikey' : apikey, 'applic...
identifier_body
AndroidPhoneNotify.py
# -*- coding: utf-8 -*- from time import time from module.network.RequestFactory import getURL from module.plugins.Hook import Hook class AndroidPhoneNotify(Hook): __name__ = "AndroidPhoneNotify" __type__ = "hook" __version__ = "0.04" __config__ = [("apikey" , "str" , "API key" ...
(self, event, msg=""): apikey = self.getConfig("apikey") if not apikey: return False if self.core.isClientConnected() and not self.getConfig("force"): return False getURL("http://www.notifymyandroid.com/publicapi/notify", get={'apikey' : apik...
notify
identifier_name
AndroidPhoneNotify.py
# -*- coding: utf-8 -*- from time import time from module.network.RequestFactory import getURL from module.plugins.Hook import Hook class AndroidPhoneNotify(Hook): __name__ = "AndroidPhoneNotify" __type__ = "hook" __version__ = "0.04" __config__ = [("apikey" , "str" , "API key" ...
else: self.notify(_("All packages finished")) def notify(self, event, msg=""): apikey = self.getConfig("apikey") if not apikey: return False if self.core.isClientConnected() and not self.getConfig("force"): return False getURL("http:/...
self.notify(_("Package failed"), _("One or more packages was not completed successfully"))
conditional_block
AndroidPhoneNotify.py
# -*- coding: utf-8 -*- from time import time from module.network.RequestFactory import getURL from module.plugins.Hook import Hook class AndroidPhoneNotify(Hook): __name__ = "AndroidPhoneNotify" __type__ = "hook" __version__ = "0.04" __config__ = [("apikey" , "str" , "API key" ...
self.notify(_("Package failed"), _("One or more packages was not completed successfully")) else: self.notify(_("All packages finished")) def notify(self, event, msg=""): apikey = self.getConfig("apikey") if not apikey: return False if self.core...
if any(True for pdata in self.core.api.getQueue() if pdata.linksdone < pdata.linkstotal):
random_line_split
records.py
""" Records for SMART Reference EMR Ben Adida & Josh Mandel """ from base import * from django.utils import simplejson from django.conf import settings from smart.common.rdf_tools.rdf_ontology import ontology from smart.common.rdf_tools.util import rdf, foaf, vcard, sp, serialize_rdf, parse_rdf, bound_graph, URIRef, ...
}""" r = list(s.query(q)) assert len(r) == 1, "Expected one alert in post, found %s" % len(r) (notes, severity) = r[0] assert type(notes) == Literal spcodes = Namespace("http://smartplatforms.org/terms/code/alertLevel#") assert severity in [spcodes.information, ...
?a rdf:type sp:Alert. ?a sp:notes ?notes. ?a sp:severity ?scv. ?scv sp:code ?severity.
random_line_split
records.py
""" Records for SMART Reference EMR Ben Adida & Josh Mandel """ from base import * from django.utils import simplejson from django.conf import settings from smart.common.rdf_tools.rdf_ontology import ontology from smart.common.rdf_tools.util import rdf, foaf, vcard, sp, serialize_rdf, parse_rdf, bound_graph, URIRef, ...
m = parse_rdf(res) record_list = [] q = """ PREFIX sp:<http://smartplatforms.org/terms#> PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX dcterms:<http://purl.org/dc/terms/> PREFIX v:<http://www.w3.org/2006/vcard/ns#> PREFIX foaf:<http://xmlns.com/foaf/0.1/> SELECT ?gn ?fn ?do...
return None
conditional_block
records.py
""" Records for SMART Reference EMR Ben Adida & Josh Mandel """ from base import * from django.utils import simplejson from django.conf import settings from smart.common.rdf_tools.rdf_ontology import ontology from smart.common.rdf_tools.util import rdf, foaf, vcard, sp, serialize_rdf, parse_rdf, bound_graph, URIRef, ...
# Not an OAuth token, but an opaque token that can be used to support # auto-login via a direct link to a smart_ui_server. class RecordDirectAccessToken(Object): record = models.ForeignKey( Record, related_name='direct_access_tokens', null=False) account = models.ForeignKey( Account, related_...
app_label = APP_LABEL unique_together = (('account', 'app'),)
identifier_body
records.py
""" Records for SMART Reference EMR Ben Adida & Josh Mandel """ from base import * from django.utils import simplejson from django.conf import settings from smart.common.rdf_tools.rdf_ontology import ontology from smart.common.rdf_tools.util import rdf, foaf, vcard, sp, serialize_rdf, parse_rdf, bound_graph, URIRef, ...
(Account): records = models.ManyToManyField(Record, related_name="+")
LimitedAccount
identifier_name
course-add.component.ts
import { Component, ViewEncapsulation, OnInit, OnDestroy, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { NgForm } from '@angular/forms'; import { uniqBy } from 'lodash'; // ngrx example import { Store } from '@ngrx/store'; import {...
() { const sub = this.route.params.subscribe((params) => { this.courseId = params['id']; if (this.courseId) { // console.log('<<<<<<<<<<<< edit >>>>>>>>>>>>'); this.subscribeCourse(); // } else { // this.store.dispatch({ type: INIT_COURSE}); // console.log('<<<<<<<<<<<< add >>>>>>>>>>>>>'); ...
subscribeCourseId
identifier_name
course-add.component.ts
import { Component, ViewEncapsulation, OnInit, OnDestroy, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { NgForm } from '@angular/forms'; import { uniqBy } from 'lodash'; // ngrx example import { Store } from '@ngrx/store'; import {...
private subscribeCourse() { this.loaderService.show(); const sub = this.courseService.getById(+this.courseId) .subscribe( (resp) => { // this.formModel = resp; this.store.dispatch({ type: COURSE_LOADED, payload: { course: resp } }); this.authors = uniqBy(this.a...
{ const sub = this.route.params.subscribe((params) => { this.courseId = params['id']; if (this.courseId) { // console.log('<<<<<<<<<<<< edit >>>>>>>>>>>>'); this.subscribeCourse(); // } else { // this.store.dispatch({ type: INIT_COURSE}); // console.log('<<<<<<<<<<<< add >>>>>>>>>>>>>'); ...
identifier_body
course-add.component.ts
import { Component, ViewEncapsulation, OnInit, OnDestroy, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { NgForm } from '@angular/forms'; import { uniqBy } from 'lodash'; // ngrx example import { Store } from '@ngrx/store'; import {...
payload: { course: resp } }); this.authors = uniqBy(this.authors.concat(resp.authors), 'id'); this.loaderService.hide(); this.ref.markForCheck(); // set dynamic breadcrumb for this route this.breadcrumbService.changeBreadcrumb(this.route.snapshot, resp.name); }, ...
// this.formModel = resp; this.store.dispatch({ type: COURSE_LOADED,
random_line_split
course-add.component.ts
import { Component, ViewEncapsulation, OnInit, OnDestroy, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { NgForm } from '@angular/forms'; import { uniqBy } from 'lodash'; // ngrx example import { Store } from '@ngrx/store'; import {...
else { this.addCourse(courseForm); } } private updateCourse(courseForm: NgForm) { const sub = this.courseService.update(+this.courseId, courseForm.value) .subscribe( (resp) => { console.log('course edited', resp); this.store.dispatch({ type: COURSE_SAVED, payload: { course...
{ this.updateCourse(courseForm); }
conditional_block
SwatchesColor.js
import React from 'react'; import reactCSS from 'reactcss'; import { Swatch } from 'react-color/lib/components/common'; export const SwatchesColor = ({ color, onClick = () => {}, onSwatchHover, first,
active, }) => { const styles = reactCSS( { default: { color: { width: '40px', height: '24px', cursor: 'pointer', background: color, marginBottom: '1px', }, check: { fill: '#fff', marginLeft: '8px', disp...
last,
random_line_split
definitions.py
from django.template import loader from regulations.generator.layers.base import InlineLayer from regulations.generator.section_url import SectionUrl from regulations.generator.layers import utils from ..node_types import to_markup_id class DefinitionsLayer(InlineLayer): shorthand = 'terms' data_source = 'te...
def replacement_for(self, original, data): """ Create the link that takes you to the definition of the term. """ citation = data['ref'] # term = term w/o pluralization term = self.layer['referenced'][citation]['term'] citation = self.layer['referenced'][citation]['reference...
def_struct['reference_split'] = def_struct['reference'].split('-')
conditional_block
definitions.py
from django.template import loader from regulations.generator.layers.base import InlineLayer from regulations.generator.section_url import SectionUrl from regulations.generator.layers import utils from ..node_types import to_markup_id class DefinitionsLayer(InlineLayer): shorthand = 'terms' data_source = 'te...
(self, original, data): """ Create the link that takes you to the definition of the term. """ citation = data['ref'] # term = term w/o pluralization term = self.layer['referenced'][citation]['term'] citation = self.layer['referenced'][citation]['reference_split'] key = (o...
replacement_for
identifier_name
definitions.py
from django.template import loader from regulations.generator.layers.base import InlineLayer from regulations.generator.section_url import SectionUrl from regulations.generator.layers import utils from ..node_types import to_markup_id class DefinitionsLayer(InlineLayer): shorthand = 'terms' data_source = 'te...
""" Create the link that takes you to the definition of the term. """ citation = data['ref'] # term = term w/o pluralization term = self.layer['referenced'][citation]['term'] citation = self.layer['referenced'][citation]['reference_split'] key = (original, tuple(citation)) ...
identifier_body
definitions.py
from django.template import loader from regulations.generator.layers.base import InlineLayer from regulations.generator.section_url import SectionUrl from regulations.generator.layers import utils from ..node_types import to_markup_id class DefinitionsLayer(InlineLayer): shorthand = 'terms' data_source = 'te...
term = self.layer['referenced'][citation]['term'] citation = self.layer['referenced'][citation]['reference_split'] key = (original, tuple(citation)) if key not in self.rendered: context = {'citation': { 'url': self.rev_urls.fetch(citation, self.version, ...
citation = data['ref'] # term = term w/o pluralization
random_line_split
make_release.py
from __future__ import print_function import os import sys from subprocess import Popen, PIPE from getpass import getpass from shutil import rmtree import argparse # inspired by https://github.com/mitsuhiko/flask/blob/master/scripts/make-release.py def set_filename_version(filename, version_number): with open(f...
(version_str): info('Setting __init__.py version to %s', version_str) set_filename_version('eralchemy/version.py', version_str) def rm(filename): info('Delete {}'.format(filename)) rmtree(filename, ignore_errors=True) def build_and_upload(): rm('ERAlchemy.egg-info') rm('build') rm('dist'...
set_init_version
identifier_name
make_release.py
from __future__ import print_function import os import sys from subprocess import Popen, PIPE from getpass import getpass from shutil import rmtree import argparse # inspired by https://github.com/mitsuhiko/flask/blob/master/scripts/make-release.py def set_filename_version(filename, version_number): with open(f...
major, minor, fix = parse_args() next_version = get_next_version(major, minor, fix, current_version) next_version_str = version_lst_to_str(next_version) tags = get_git_tags() if next_version_str in tags: fail('Version "%s" is already tagged', next_version_str) if not git_is_clean(): ...
current_version = get_current_version()
random_line_split
make_release.py
from __future__ import print_function import os import sys from subprocess import Popen, PIPE from getpass import getpass from shutil import rmtree import argparse # inspired by https://github.com/mitsuhiko/flask/blob/master/scripts/make-release.py def set_filename_version(filename, version_number): with open(f...
def get_current_version(): with open('eralchemy/version.py') as f: lines = f.readlines() namespace = {} exec(lines[0], namespace) return version_str_to_lst(namespace['version']) def get_git_tags(): return set(Popen(['git', 'tag'], stdout=PIPE).communicate()[0].splitlines()) ...
""" Parse the args, returns if the type of update: Major, minor, fix """ parser = argparse.ArgumentParser() parser.add_argument('-M', action='store_true') parser.add_argument('-m', action='store_true') parser.add_argument('-f', action='store_true') args = parser.parse_args() major, minor...
identifier_body
make_release.py
from __future__ import print_function import os import sys from subprocess import Popen, PIPE from getpass import getpass from shutil import rmtree import argparse # inspired by https://github.com/mitsuhiko/flask/blob/master/scripts/make-release.py def set_filename_version(filename, version_number): with open(f...
if not git_is_clean(): fail('You have uncommitted changes in git') set_init_version(next_version_str) make_git_commit('Bump version number to %s', next_version_str) make_git_tag('v' + next_version_str) build_and_upload() if __name__ == '__main__': main()
fail('Version "%s" is already tagged', next_version_str)
conditional_block
areas.rs
use spin::Once; static AREAS: Once<Areas> = Once::new(); #[derive(Debug)] struct Areas { areas: [Area; 16], count: usize, } //TODO Do we align the base and length here, // provide methods for it, // or leave it up to the user #[derive(Copy, Clone, Debug)] pub struct Area { pub base: u64, pub...
fn add_area(&mut self, base: u64, length: u64) { self.areas[self.count] = Area{base:base, length: length}; self.count += 1; } fn iter(&'static self) -> AreaIter { AreaIter {i: 0, areas: self} } } impl Iterator for AreaIter { type Item = &'static Area; fn next(&mut self)...
}
random_line_split
areas.rs
use spin::Once; static AREAS: Once<Areas> = Once::new(); #[derive(Debug)] struct Areas { areas: [Area; 16], count: usize, } //TODO Do we align the base and length here, // provide methods for it, // or leave it up to the user #[derive(Copy, Clone, Debug)] pub struct Area { pub base: u64, pub...
} areas }); //TODO I'm not sure if I want this here // We should probably move this to a print function, or something. println!("Areas"); for area in memory_areas() { println!(" start: 0x{:x}, length: 0x{:x}", area.base, area.length); } }
{ areas.add_area(area.start, area.length); }
conditional_block
areas.rs
use spin::Once; static AREAS: Once<Areas> = Once::new(); #[derive(Debug)] struct Areas { areas: [Area; 16], count: usize, } //TODO Do we align the base and length here, // provide methods for it, // or leave it up to the user #[derive(Copy, Clone, Debug)] pub struct Area { pub base: u64, pub...
} impl Iterator for AreaIter { type Item = &'static Area; fn next(&mut self) -> Option<Self::Item> { if self.i < self.areas.count { let item = &self.areas.areas[self.i]; self.i += 1; Some(item) } else { None } } } fn areas() -> &'sta...
{ AreaIter {i: 0, areas: self} }
identifier_body
areas.rs
use spin::Once; static AREAS: Once<Areas> = Once::new(); #[derive(Debug)] struct Areas { areas: [Area; 16], count: usize, } //TODO Do we align the base and length here, // provide methods for it, // or leave it up to the user #[derive(Copy, Clone, Debug)] pub struct Area { pub base: u64, pub...
() -> Areas { Areas { areas: [Area{base:0, length: 0};16], count: 0, } } fn add_area(&mut self, base: u64, length: u64) { self.areas[self.count] = Area{base:base, length: length}; self.count += 1; } fn iter(&'static self) -> AreaIter { Ar...
new
identifier_name
dominators.rs
to be the *immediate dominator* of a node **B** iff it //! strictly dominates **B** and there does not exist any node **C** where **A** //! dominates **C** and **C** dominates **B**. use std::cmp::Ordering; use std::collections::{HashMap, HashSet, hash_map::Iter}; use std::hash::Hash; use crate::visit::{DfsPostOrder...
/// Iterate over the given node's strict dominators. /// /// If the given node is not reachable from the root, then `None` is /// returned. pub fn strict_dominators(&self, node: N) -> Option<DominatorsIter<N>> { if self.dominators.contains_key(&node) { Some(DominatorsIter { ...
if node == self.root { None } else { self.dominators.get(&node).cloned() } }
identifier_body
dominators.rs
hash::Hash; use crate::visit::{DfsPostOrder, GraphBase, IntoNeighbors, Visitable, Walker}; /// The dominance relation for some graph and root. #[derive(Debug, Clone)] pub struct Dominators<N> where N: Copy + Eq + Hash, { root: N, dominators: HashMap<N, N>, } impl<N> Dominators<N> where N: Copy + Eq +...
fn test_iter_dominators() { let doms: Dominators<u32> = Dominators { root: 0, dominators: [(2, 1), (1, 0), (0, 0)].iter().cloned().collect(),
random_line_split
dominators.rs
to be the *immediate dominator* of a node **B** iff it //! strictly dominates **B** and there does not exist any node **C** where **A** //! dominates **C** and **C** dominates **B**. use std::cmp::Ordering; use std::collections::{HashMap, HashSet, hash_map::Iter}; use std::hash::Hash; use crate::visit::{DfsPostOrder...
} /// Iterate over all of the given node's dominators (including the given /// node itself). /// /// If the given node is not reachable from the root, then `None` is /// returned. pub fn dominators(&self, node: N) -> Option<DominatorsIter<N>> { if self.dominators.contains_key(&node) ...
None }
conditional_block
dominators.rs
be the *immediate dominator* of a node **B** iff it //! strictly dominates **B** and there does not exist any node **C** where **A** //! dominates **C** and **C** dominates **B**. use std::cmp::Ordering; use std::collections::{HashMap, HashSet, hash_map::Iter}; use std::hash::Hash; use crate::visit::{DfsPostOrder, G...
( post_order: &[N], node_to_post_order_idx: &HashMap<N, usize>, mut predecessor_sets: HashMap<N, HashSet<N>>, ) -> Vec<Vec<usize>> where N: Copy + Eq + Hash, { post_order .iter() .map(|node| { predecessor_sets .remove(node) .map(|predecesso...
decessor_sets_to_idx_vecs<N>
identifier_name
glance_client.py
# -*- encoding: utf-8 -*- # Copyright (c) 2016 Intel Corp # # Authors: Prudhvi Rao Shedimbi <prudhvi.rao.shedimbi@intel.com> # # 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.apa...
def list_opts(): return [(glance_client, GLANCE_CLIENT_OPTS)]
conf.register_group(glance_client) conf.register_opts(GLANCE_CLIENT_OPTS, group=glance_client)
identifier_body
glance_client.py
# -*- encoding: utf-8 -*- # Copyright (c) 2016 Intel Corp # # Authors: Prudhvi Rao Shedimbi <prudhvi.rao.shedimbi@intel.com> # # 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.apa...
def register_opts(conf): conf.register_group(glance_client) conf.register_opts(GLANCE_CLIENT_OPTS, group=glance_client) def list_opts(): return [(glance_client, GLANCE_CLIENT_OPTS)]
help='Region in Identity service catalog to use for ' 'communication with the OpenStack service.')]
random_line_split
glance_client.py
# -*- encoding: utf-8 -*- # Copyright (c) 2016 Intel Corp # # Authors: Prudhvi Rao Shedimbi <prudhvi.rao.shedimbi@intel.com> # # 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.apa...
(): return [(glance_client, GLANCE_CLIENT_OPTS)]
list_opts
identifier_name
getMapHandler.ts
import Router from '@koa/router'; import { SQL } from 'sql-template-strings'; import { pool } from '../../database'; import { acceptValidator } from '../../requestValidators'; import { authenticator } from '../../authenticator'; export function attachGetMapHandler(router: Router) { router.get( '/:id', accept...
const { user } = ctx.state; if ( !item.public && (!user || (!user.isAdmin && user.id !== item.userId)) ) { ctx.throw(403); } const writers = item.writers?.split(',').map((s: any) => Number(s)) ?? []; ctx.body = { meta: { id: item.id, ...
{ ctx.throw(404, 'no such map'); }
conditional_block
getMapHandler.ts
import Router from '@koa/router'; import { SQL } from 'sql-template-strings'; import { pool } from '../../database'; import { acceptValidator } from '../../requestValidators'; import { authenticator } from '../../authenticator'; export function attachGetMapHandler(router: Router)
!item.public && (!user || (!user.isAdmin && user.id !== item.userId)) ) { ctx.throw(403); } const writers = item.writers?.split(',').map((s: any) => Number(s)) ?? []; ctx.body = { meta: { id: item.id, createdAt: item.createdAt.toISOString(), ...
{ router.get( '/:id', acceptValidator('application/json'), authenticator(false), async (ctx) => { const [item] = await pool.query(SQL` SELECT id, name, public, data, createdAt, modifiedAt, map.userId, GROUP_CONCAT(mapWriteAccess.userId) AS writers FROM map LEFT JOIN mapWriteAcc...
identifier_body
getMapHandler.ts
import Router from '@koa/router'; import { SQL } from 'sql-template-strings'; import { pool } from '../../database'; import { acceptValidator } from '../../requestValidators'; import { authenticator } from '../../authenticator'; export function
(router: Router) { router.get( '/:id', acceptValidator('application/json'), authenticator(false), async (ctx) => { const [item] = await pool.query(SQL` SELECT id, name, public, data, createdAt, modifiedAt, map.userId, GROUP_CONCAT(mapWriteAccess.userId) AS writers FROM map LEFT...
attachGetMapHandler
identifier_name
getMapHandler.ts
import Router from '@koa/router'; import { SQL } from 'sql-template-strings'; import { pool } from '../../database'; import { acceptValidator } from '../../requestValidators'; import { authenticator } from '../../authenticator'; export function attachGetMapHandler(router: Router) { router.get( '/:id',
acceptValidator('application/json'), authenticator(false), async (ctx) => { const [item] = await pool.query(SQL` SELECT id, name, public, data, createdAt, modifiedAt, map.userId, GROUP_CONCAT(mapWriteAccess.userId) AS writers FROM map LEFT JOIN mapWriteAccess ON (mapWriteAccess.mapId...
random_line_split
__init__.py
prefer_tcp", "stimeout": "5000000", **options, } stream = Stream(hass, stream_source, options=options) hass.data[DOMAIN][ATTR_STREAMS].append(stream) return stream CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Optional(CONF...
"""Stop worker thread.""" if self._thread is not None: self._thread_quit.set() self._thread.join() self._thread = None _LOGGER.info("Stopped stream: %s", redact_credentials(str(self.source)))
identifier_body
__init__.py
CONF_LL_HLS, CONF_PART_DURATION, CONF_SEGMENT_DURATION, DOMAIN, HLS_PROVIDER, MAX_SEGMENTS, OUTPUT_IDLE_TIMEOUT, RECORDER_PROVIDER, SEGMENT_DURATION_ADJUSTER, STREAM_RESTART_INCREMENT, STREAM_RESTART_RESET_TIME, TARGET_SEGMENT_DURATION_NON_LL_HLS, ) from .core import PROV...
CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Optional(CONF_LL_HLS, default=False): cv.boolean, vol.Optional(CONF_SEGMENT_DURATION, default=6): vol.All( cv.positive_float, vol.Range(min=2, max=10) ), ...
return stream
random_line_split
__init__.py
_ADJUSTER, STREAM_RESTART_INCREMENT, STREAM_RESTART_RESET_TIME, TARGET_SEGMENT_DURATION_NON_LL_HLS, ) from .core import PROVIDERS, IdleTimer, StreamOutput, StreamSettings from .hls import HlsStreamOutput, async_setup_hls _LOGGER = logging.getLogger(__name__) STREAM_SOURCE_REDACT_PATTERN = [ (re.compil...
if self._fast_restart_once: # The stream source is updated, restart without any delay. self._fast_restart_once = False self._thread_quit.clear() continue break
conditional_block
__init__.py
CONF_LL_HLS, CONF_PART_DURATION, CONF_SEGMENT_DURATION, DOMAIN, HLS_PROVIDER, MAX_SEGMENTS, OUTPUT_IDLE_TIMEOUT, RECORDER_PROVIDER, SEGMENT_DURATION_ADJUSTER, STREAM_RESTART_INCREMENT, STREAM_RESTART_RESET_TIME, TARGET_SEGMENT_DURATION_NON_LL_HLS, ) from .core import PROVIDE...
(self) -> bool: """Return False if the stream is started and known to be unavailable.""" return self._available def start(self) -> None: """Start a stream.""" if self._thread is None or not self._thread.is_alive(): if self._thread is not None: # The threa...
available
identifier_name
csv_input.py
import numpy as np from assorted.GraphInput import GraphInput from model.component.component_model import ComponentModel class CsvInput(ComponentModel):
def compile_theano(self): self.graph_input.compile_theano() self.push_by_index(0, self.graph_input.variable)
name = "CsvInput" default_out_sockets = [{'position': [0, -20], 'name': 'Output'}] default_attributes = {'path': '<argument>', 'n_columns': '3', 'separator': ','} graph_input = None def __init__(self, manifest=None, identifier=None): Compo...
identifier_body
csv_input.py
import numpy as np from assorted.GraphInput import GraphInput from model.component.component_model import ComponentModel class CsvInput(ComponentModel): name = "CsvInput" default_out_sockets = [{'position': [0, -20], 'name': 'Output'}] default_attributes = {'path': '<argument>', ...
(self): return [self.graph_input] def compile_theano(self): self.graph_input.compile_theano() self.push_by_index(0, self.graph_input.variable)
theano_inputs
identifier_name
csv_input.py
import numpy as np from assorted.GraphInput import GraphInput from model.component.component_model import ComponentModel class CsvInput(ComponentModel): name = "CsvInput" default_out_sockets = [{'position': [0, -20], 'name': 'Output'}]
def __init__(self, manifest=None, identifier=None): ComponentModel.__init__(self, manifest=manifest, identifier=identifier) self.graph_input = GraphInput(self.get_name()+"_input", [3]) def parse_column_string(self, string): return np.fromstring(string, sep=' ', dtype=np.int32) def...
default_attributes = {'path': '<argument>', 'n_columns': '3', 'separator': ','} graph_input = None
random_line_split
boolean.rs
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation // Copyright (C) 2020 Stacks Open Internet Foundation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version...
Ok(Value::Bool(false)) } pub fn special_and( args: &[SymbolicExpression], env: &mut Environment, context: &LocalContext, ) -> Result<Value> { check_arguments_at_least(1, args)?; runtime_cost(ClarityCostFunction::And, env, args.len())?; for arg in args.iter() { let evaluated = eval...
if result { return Ok(Value::Bool(true)); } }
random_line_split
boolean.rs
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation // Copyright (C) 2020 Stacks Open Internet Foundation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version...
( args: &[SymbolicExpression], env: &mut Environment, context: &LocalContext, ) -> Result<Value> { check_arguments_at_least(1, args)?; runtime_cost(ClarityCostFunction::Or, env, args.len())?; for arg in args.iter() { let evaluated = eval(&arg, env, context)?; let result = type_...
special_or
identifier_name
boolean.rs
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation // Copyright (C) 2020 Stacks Open Internet Foundation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version...
{ let value = type_force_bool(&input)?; Ok(Value::Bool(!value)) }
identifier_body
ECR.ts
import { Service } from '../service'; import { IResource, TransformListFunctionType } from '../types'; import { ECR as stub } from './../spec/spec'; /** * @hidden */ const service: any = Service(stub); /** * @hidden */ const RepositoryList: TransformListFunctionType = function( AWSClient: AWS.ECR
const { repositories } = await AWSClient.describeRepositories().promise(); const lifecycles = await Promise.all( repositories.map(r => AWSClient.getLifecyclePolicy({ repositoryName: r.repositoryName, }).promise() ) ); const policytext = await Promise.all( repo...
): Promise<IResource[]> { return new Promise(async (resolve, reject) => {
random_line_split
testing.py
import optparse import os import shutil import sys import unittest from itertools import izip from . import util from . import stats #============================================================================= # common utility functions for testing def clean_dir(path): if os.path.exists(path): shutil...
def set_pausing(enabled=True): global _do_pause _do_pause = enabled #============================================================================= # common unittest functions def list_tests(stack=0): # get environment var = __import__("__main__").__dict__ for name, obj in var.iteritems(): ...
"""Pause until the user presses enter""" if _do_pause: sys.stderr.write(text) raw_input()
identifier_body
testing.py
import optparse import os import shutil import sys import unittest from itertools import izip from . import util from . import stats #============================================================================= # common utility functions for testing def clean_dir(path): if os.path.exists(path): shutil...
os.makedirs(path) def fequal(f1, f2, rel=.0001, eabs=1e-12): """assert whether two floats are approximately equal""" if f1 == f2: return if f2 == 0: err = f1 elif f1 == 0: err = f2 else: err = abs(f1 - f2) / abs(f2) x = (err < rel) if abs(f1 - f2) < ...
shutil.rmtree(path)
conditional_block
testing.py
import optparse import os import shutil import sys import unittest from itertools import izip from . import util from . import stats #============================================================================= # common utility functions for testing def clean_dir(path): if os.path.exists(path): shutil...
(f1, f2, rel=.0001, eabs=1e-12): """assert whether two floats are approximately equal""" if f1 == f2: return if f2 == 0: err = f1 elif f1 == 0: err = f2 else: err = abs(f1 - f2) / abs(f2) x = (err < rel) if abs(f1 - f2) < eabs: return assert x,...
fequal
identifier_name
testing.py
import optparse import os import shutil import sys import unittest from itertools import izip from . import util from . import stats #============================================================================= # common utility functions for testing def clean_dir(path): if os.path.exists(path): shutil....
_do_pause = enabled #============================================================================= # common unittest functions def list_tests(stack=0): # get environment var = __import__("__main__").__dict__ for name, obj in var.iteritems(): if isinstance(obj, type) and issubclass(obj, uni...
def set_pausing(enabled=True): global _do_pause
random_line_split
remote_event.d.ts
/** * Copyright 2017 Google Inc. * * 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 i...
{ /** * The snapshot version this event brings us up to, or MIN if not set. */ readonly snapshotVersion: SnapshotVersion; /** * A map from target to changes to the target. See TargetChange. */ readonly targetChanges: { [targetId: number]: TargetChange; }; /** * ...
RemoteEvent
identifier_name
remote_event.d.ts
/** * Copyright 2017 Google Inc. * * 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 i...
/** The target must be marked as no longer "current". */ MarkNotCurrent = 1, /** The target must be marked as "current". */ MarkCurrent = 2, } /** * A part of a RemoteEvent specifying set of changes to a specific target. These * changes track what documents are currently included in the target as well...
None = 0,
random_line_split
index.ts
/* * This file is part of 6502.ts, an emulator for 6502 based systems built * in Typescript * * Copyright (c) 2014 -- 2020 Christian Speckner and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Sof...
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ export { default as StateMachineInterface } from './StateMachineInterface';
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
random_line_split
connectivity_issue.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
self.type = None self.context = None
self.origin = None self.severity = None
random_line_split
connectivity_issue.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
_validation = { 'origin': {'readonly': True}, 'severity': {'readonly': True}, 'type': {'readonly': True}, 'context': {'readonly': True}, } _attribute_map = { 'origin': {'key': 'origin', 'type': 'str'}, 'severity': {'key': 'severity', 'type': 'str'}, '...
"""Information about an issue encountered in the process of checking for connectivity. Variables are only populated by the server, and will be ignored when sending a request. :ivar origin: The origin of the issue. Possible values include: 'Local', 'Inbound', 'Outbound' :vartype origin: str or...
identifier_body
connectivity_issue.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(Model): """Information about an issue encountered in the process of checking for connectivity. Variables are only populated by the server, and will be ignored when sending a request. :ivar origin: The origin of the issue. Possible values include: 'Local', 'Inbound', 'Outbound' :vartype o...
ConnectivityIssue
identifier_name
registry.ts
type filesById = { [id:number]: string[] }; export abstract class Registry { constructor(protected repoPath:string) { } public initialize() :Promise<void> { return Promise.resolve(); } public teardown() :Promise<void> { return Promise.resolve(); } public abstract addFromPath(filePath:string) : Promise<void...
(imageIds:number[]) : Promise<filesById> { return Promise.all(imageIds.map(id => this.findImage(id).then(files => ({id, files})))) .then(items => items.reduce<filesById>((acc, cur) => { if (cur.files.length > 0) { acc[cur.id] = cur.files; } return acc; }, {})); } }
findImages
identifier_name
registry.ts
type filesById = { [id:number]: string[] }; export abstract class Registry { constructor(protected repoPath:string) { } public initialize() :Promise<void> { return Promise.resolve(); } public teardown() :Promise<void> { return Promise.resolve(); } public abstract addFromPath(filePath:string) : Promise<void...
return acc; }, {})); } }
{ acc[cur.id] = cur.files; }
conditional_block
registry.ts
type filesById = { [id:number]: string[] }; export abstract class Registry { constructor(protected repoPath:string) { } public initialize() :Promise<void> { return Promise.resolve(); } public teardown() :Promise<void> { return Promise.resolve(); } public abstract addFromPath(filePath:string) : Promise<void...
}
{ return Promise.all(imageIds.map(id => this.findImage(id).then(files => ({id, files})))) .then(items => items.reduce<filesById>((acc, cur) => { if (cur.files.length > 0) { acc[cur.id] = cur.files; } return acc; }, {})); }
identifier_body
registry.ts
type filesById = { [id:number]: string[] }; export abstract class Registry {
public initialize() :Promise<void> { return Promise.resolve(); } public teardown() :Promise<void> { return Promise.resolve(); } public abstract addFromPath(filePath:string) : Promise<void> public addFromPaths(filePaths:string[]) : Promise<void> { return Promise.all(filePaths.map(fPath => this.addFromPath(...
constructor(protected repoPath:string) { }
random_line_split
touch.rs
use crate::sys; pub type Finger = sys::SDL_Finger; pub type TouchDevice = sys::SDL_TouchID; #[doc(alias = "SDL_GetNumTouchDevices")] pub fn num_touch_devices() -> i32 { unsafe { sys::SDL_GetNumTouchDevices() } } #[doc(alias = "SDL_GetTouchDevice")] pub fn touch_device(index: i32) -> TouchDevice { unsafe { sy...
pub fn touch_finger(touch: TouchDevice, index: i32) -> Option<Finger> { let raw = unsafe { sys::SDL_GetTouchFinger(touch, index) }; if raw.is_null() { None } else { unsafe { Some(*raw) } } }
#[doc(alias = "SDL_GetTouchFinger")]
random_line_split
touch.rs
use crate::sys; pub type Finger = sys::SDL_Finger; pub type TouchDevice = sys::SDL_TouchID; #[doc(alias = "SDL_GetNumTouchDevices")] pub fn num_touch_devices() -> i32 { unsafe { sys::SDL_GetNumTouchDevices() } } #[doc(alias = "SDL_GetTouchDevice")] pub fn touch_device(index: i32) -> TouchDevice { unsafe { sy...
}
{ unsafe { Some(*raw) } }
conditional_block
touch.rs
use crate::sys; pub type Finger = sys::SDL_Finger; pub type TouchDevice = sys::SDL_TouchID; #[doc(alias = "SDL_GetNumTouchDevices")] pub fn num_touch_devices() -> i32 { unsafe { sys::SDL_GetNumTouchDevices() } } #[doc(alias = "SDL_GetTouchDevice")] pub fn touch_device(index: i32) -> TouchDevice { unsafe { sy...
(touch: TouchDevice, index: i32) -> Option<Finger> { let raw = unsafe { sys::SDL_GetTouchFinger(touch, index) }; if raw.is_null() { None } else { unsafe { Some(*raw) } } }
touch_finger
identifier_name
touch.rs
use crate::sys; pub type Finger = sys::SDL_Finger; pub type TouchDevice = sys::SDL_TouchID; #[doc(alias = "SDL_GetNumTouchDevices")] pub fn num_touch_devices() -> i32
#[doc(alias = "SDL_GetTouchDevice")] pub fn touch_device(index: i32) -> TouchDevice { unsafe { sys::SDL_GetTouchDevice(index) } } #[doc(alias = "SDL_GetNumTouchFingers")] pub fn num_touch_fingers(touch: TouchDevice) -> i32 { unsafe { sys::SDL_GetNumTouchFingers(touch) } } #[doc(alias = "SDL_GetTouchFinger")...
{ unsafe { sys::SDL_GetNumTouchDevices() } }
identifier_body
ObjMail.py
#!/usr/bin/env python # Copyright (C) 2012 Andrea Valle # # This file is part of swgit. # # swgit is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
return from_opt def get_mail_cmd( self ): if self.isValid_ == False: return "" cmd_send_mail = self.CMD_SEND_MAIL_TEMPL % \ ( self.get_all_body( "BODY_HERE" ), ",".join(self.to_), "SUBJECT_HERE", self.get_cc...
from_opt = " -- -f \"%s\" " % ( self.from_ )
conditional_block
ObjMail.py
#!/usr/bin/env python # Copyright (C) 2012 Andrea Valle # # This file is part of swgit. # # swgit is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
def sanitize_message( self, mess ): for clean in [ "'", '"' ]: mess = mess.replace( clean, ' ' ) return mess def get_all_body( self, body ): allbody = self.sanitize_message( self.bodyH_ ) if self.bodyH_ != "": allbody += "\n" allbody += body if self.bodyF_ != "": allbod...
retstr = "\n" if self.isValid_ == False: retstr += "INVALID " retstr += "Mail configuration for %s\n" % self.section_ retstr += super(ObjMailBase, self ).dump() return retstr
identifier_body
ObjMail.py
#!/usr/bin/env python # Copyright (C) 2012 Andrea Valle # # This file is part of swgit. # # swgit is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
else: if debug == True: return "localhost:\n%s" % ( cmd_send_mail ), 0 else: return myCommand_fast( cmd_send_mail ) ################ # STABILIZE MAIL # ################ class ObjMailStabilize( ObjMailBase ): def __init__( self ): super(ObjMailStabilize, self ).__init__( SWFILE_MA...
random_line_split
ObjMail.py
#!/usr/bin/env python # Copyright (C) 2012 Andrea Valle # # This file is part of swgit. # # swgit is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
( ObjMailBase ): def __init__( self ): super(ObjMailStabilize, self ).__init__( SWFILE_MAILCFG, SWCFG_STABILIZE_SECT ) self.load_cfg() ############# # PUSH MAIL # ############# class ObjMailPush( ObjMailBase ): def __init__( self ): super(ObjMailPush, self ).__init__( SWFILE_MAILCFG, SWCFG_MAIL_PUSH_SE...
ObjMailStabilize
identifier_name
mongo_cache.py
# -*- encoding:utf8 -*- """ 使用mongodb作为缓存器 测试本地缓存 """ import sys reload(sys)
from pymongo import MongoClient from datetime import datetime, timedelta from bson.binary import Binary import zlib import time class MongoCache: def __init__(self, client=None, expires=timedelta(days=30)): self.client = client or MongoClient(connect=False) # 使用cache作为缓存的collection self.db...
sys.setdefaultencoding('utf8') import json
random_line_split
mongo_cache.py
# -*- encoding:utf8 -*- """ 使用mongodb作为缓存器 测试本地缓存 """ import sys reload(sys) sys.setdefaultencoding('utf8') import json from pymongo import MongoClient from datetime import datetime, timedelta from bson.binary import Binary import zlib import time class MongoCache: def __init__(self, client=None, expires=timedelt...
result['html'] = Binary(zlib.compress(result['html'])) self.db.webpage.replace_one({'_id': url}, result, upsert=True) result['html'] = zlib.decompress(result['html']) def clear(self): self.db.webpage.drop() def test(timesleep=60): cache = MongoCache(expires=timedelta()) ...
def __setitem__(self, url, result):
conditional_block
mongo_cache.py
# -*- encoding:utf8 -*- """ 使用mongodb作为缓存器 测试本地缓存 """ import sys reload(sys) sys.setdefaultencoding('utf8') import json from pymongo import MongoClient from datetime import datetime, timedelta from bson.binary import Binary import zlib import time class MongoCache: def __init__(self, client=None, expires=timedelt...
except KeyError: return False else: return True def __getitem__(self, url): result = self.db.webpage.find_one({'_id': url}) if result: result['html'] = zlib.decompress(result['html']) return result else: raise KeyError(ur...
[url]
identifier_name