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
Panel.js
import React, { Component } from 'react' import PropTypes from 'prop-types' import { assign } from 'lodash' import autoBind from '../utils/autoBind' const styles = { 'ClosedPanelWrapper': { height: '40px' }, 'PanelWrapper': { position: 'relative' }, 'Over': { border: '1px dashed white', ove...
handleTitleClick() { const { index, isOpen, openPanel } = this.props openPanel(isOpen ? -1 : index) } handleDragStart(e) { // e.target.style.opacity = '0.4'; // this / e.target is the source node. e.dataTransfer.setData('index', e.target.dataset.index) } handleDragOver(e) { if (e.prev...
{ super() this.state = { dragIndex: null, overIndex: null, isOver: false } autoBind(this, [ 'handleTitleClick', 'handleDragStart', 'handleDragOver', 'handleDragEnter', 'handleDragLeave', 'handleDrop', 'handleDragEnd' ]) }
identifier_body
MultiPathfinderTest.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2013 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU ...
def onInstanceActionCancelled(self, instance, action): pass def onInstanceActionFrame(self, instance, action, frame): pass class MultiPathfinderTest(test.Test): def create(self, engine, application): self._application = application self._engine = engine self._running = False self._loader = fife.M...
def onInstanceActionFinished(self, instance, action): instance.move('walk', self._test.createRandomTarget(), 4.0)
random_line_split
MultiPathfinderTest.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2013 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU ...
self._camera = self._map.getCamera("camera1") self._actorlayer = self._map.getLayer("item_layer") self._groundlayer = self._map.getLayer("ground_layer") self._player = self._actorlayer.getInstance("player") self._frigate1 = self._actorlayer.getInstance("frigate1") self._frigate1.actOnce("stand", self._fri...
self._map = self._loader.load(self._mapfilename) self._mapLoaded = True
conditional_block
MultiPathfinderTest.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2013 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU ...
(self): """ This gets called every frame that the test is running. We have nothing to do here for this test. """ pass def loadMap(self, filename): """ Simple function to load and display a map file. We could of course have passed in the map filename but I'll leave that up to you. @param filenam...
pump
identifier_name
MultiPathfinderTest.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2013 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU ...
class MultiPathfinderTest(test.Test): def create(self, engine, application): self._application = application self._engine = engine self._running = False self._loader = fife.MapLoader(self._engine.getModel(), self._engine.getVFS(), self._engine.getImageManager(), self._engine....
def __init__(self, test): self._engine = test._engine self._test = test fife.InstanceActionListener.__init__(self) def onInstanceActionFinished(self, instance, action): instance.move('walk', self._test.createRandomTarget(), 4.0) def onInstanceActionCancelled(self, instance, action): pass def onInst...
identifier_body
menu_createRoom.js
import React, { Component } from 'react'; import axios from 'axios'; import { Router, Link } from 'react-router'; import { Button } from 'react-bootstrap'; export default class trueMenu extends Component { constructor(props) { super(); this.state = { displayCreateBoard: false, displayJoin: false...
onChange={(e) => this.handleName(e)} className={!this.state.isValid ? 'animated shake search-style' : 'search-style'} /> <p> <button className="btn btn-primary button-spacing" onClick={this.handleJoination}>Enter Room </button> </p> <...
{ const logoStyle = { 'marginTop': '14%' } const imageSize = { width: '400px' } return ( <div className="center-roomselect" id="createroom"> <form style={logoStyle} className="animated fadeInUp" onSubmit={this.handleJoination}> <img style={imageSize} src="./media/codeout.p...
identifier_body
menu_createRoom.js
import React, { Component } from 'react'; import axios from 'axios'; import { Router, Link } from 'react-router'; import { Button } from 'react-bootstrap'; export default class trueMenu extends Component { constructor(props) { super(); this.state = { displayCreateBoard: false, displayJoin: false...
} handleJoination(e) { e.preventDefault(); if(this.state.name === ''){ this.setState({placeholder: "Please enter a room name", isValid: false}) return; } else if (this.state.name.indexOf(' ') !== -1){ this.setState({placeholder: "Room names can not contain spaces", name: '', isValid: ...
this.handleJoination = this.handleJoination.bind(this);
random_line_split
menu_createRoom.js
import React, { Component } from 'react'; import axios from 'axios'; import { Router, Link } from 'react-router'; import { Button } from 'react-bootstrap'; export default class trueMenu extends Component { constructor(props) { super(); this.state = { displayCreateBoard: false, displayJoin: false...
() { const logoStyle = { 'marginTop': '14%' } const imageSize = { width: '400px' } return ( <div className="center-roomselect" id="createroom"> <form style={logoStyle} className="animated fadeInUp" onSubmit={this.handleJoination}> <img style={imageSize} src="./media/codeou...
render
identifier_name
menu_createRoom.js
import React, { Component } from 'react'; import axios from 'axios'; import { Router, Link } from 'react-router'; import { Button } from 'react-bootstrap'; export default class trueMenu extends Component { constructor(props) { super(); this.state = { displayCreateBoard: false, displayJoin: false...
else if (this.state.name.indexOf(' ') !== -1){ this.setState({placeholder: "Room names can not contain spaces", name: '', isValid: false}) return; }else if (/[^a-zA-Z0-9\-\/]/.test(this.state.name)) { this.setState({placeholder: "Special characters are not allowed", name: '', isValid: false}) ...
{ this.setState({placeholder: "Please enter a room name", isValid: false}) return; }
conditional_block
clear_pgviews.py
import logging from django.core.management.base import BaseCommand from django.apps import apps from django.db import connection from django_pgviews.view import clear_view, View, MaterializedView log = logging.getLogger('django_pgviews.sync_pgviews') class Command(BaseCommand): help = """Clear Postgres views....
python_name = '{}.{}'.format(view_cls._meta.app_label, view_cls.__name__) status = clear_view( connection, view_cls._meta.db_table, materialized=isinstance(view_cls(), MaterializedView)) if status == 'DROPPED': msg = 'dropped' ...
continue
conditional_block
clear_pgviews.py
import logging from django.core.management.base import BaseCommand from django.apps import apps from django.db import connection from django_pgviews.view import clear_view, View, MaterializedView log = logging.getLogger('django_pgviews.sync_pgviews') class Command(BaseCommand): help = """Clear Postgres views....
""" """ for view_cls in apps.get_models(): if not (isinstance(view_cls, type) and issubclass(view_cls, View) and hasattr(view_cls, 'sql')): continue python_name = '{}.{}'.format(view_cls._meta.app_label, view_cls.__name__) ...
identifier_body
clear_pgviews.py
import logging from django.core.management.base import BaseCommand from django.apps import apps from django.db import connection from django_pgviews.view import clear_view, View, MaterializedView log = logging.getLogger('django_pgviews.sync_pgviews') class
(BaseCommand): help = """Clear Postgres views. Use this before running a migration""" def handle(self, **options): """ """ for view_cls in apps.get_models(): if not (isinstance(view_cls, type) and issubclass(view_cls, View) and hasattr...
Command
identifier_name
clear_pgviews.py
import logging from django.core.management.base import BaseCommand from django.apps import apps from django.db import connection from django_pgviews.view import clear_view, View, MaterializedView log = logging.getLogger('django_pgviews.sync_pgviews') class Command(BaseCommand): help = """Clear Postgres views....
msg = 'dropped' else: msg = 'not dropped' log.info("%(python_name)s (%(view_name)s): %(msg)s" % { 'python_name': python_name, 'view_name': view_cls._meta.db_table, 'msg': msg})
random_line_split
config.py
GITHUB_SIGNATURE_HEADER = 'X-Hub-Signature' GITHUB_SECRET = 'redacted' GITHUB_COMMIT_API = 'https://api.github.com/repos/adsabs/{repo}/git/commits/{hash}' GITHUB_TAG_FIND_API = 'https://api.github.com/repos/adsabs/{repo}/git/refs/tags/{tag}' GITHUB_TAG_GET_API = 'https://api.github.com/repos/adsabs/{repo}/git/tags/{has...
'[%(asctime)s]:\t%(message)s', 'datefmt': '%m/%d/%Y %H:%M:%S', } }, 'handlers': { 'console': { 'formatter': 'default', 'level': 'DEBUG', 'class': 'logging.StreamHandler' }, }, 'loggers': { '': { ...
'formatters': { 'default': { 'format': '%(levelname)s\t%(process)d '
random_line_split
ShowPipelineTemplateJsonModal.tsx
import React from 'react'; import { IPromise } from 'angular'; import classNames from 'classnames'; import { Modal } from 'react-bootstrap'; import { Spinner } from 'core/widgets/spinners/Spinner'; import { IModalComponentProps, JsonEditor } from 'core/presentation'; import { IPipelineTemplateV2 } from 'core/domain';...
private onChange = (e: React.ChangeEvent<HTMLInputElement>, property: string) => { if (!this.props.editable) { return; } this.setState({ template: { ...this.state.template, metadata: { ...this.state.template.metadata, [property]: e.target.value, },...
{ super(props); this.state = { template: props.template, saveError: null, saving: false }; }
identifier_body
ShowPipelineTemplateJsonModal.tsx
import React from 'react'; import { IPromise } from 'angular'; import classNames from 'classnames'; import { Modal } from 'react-bootstrap'; import { Spinner } from 'core/widgets/spinners/Spinner'; import { IModalComponentProps, JsonEditor } from 'core/presentation'; import { IPipelineTemplateV2 } from 'core/domain';...
<Modal.Body className="flex-fill"> <div className="text-center"> <Spinner size="medium" message="Saving ..." /> </div> </Modal.Body> </> ); } return ( <> <ModalClose dismiss={dismissModal} /> <Modal.Header> ...
</Modal.Header>
random_line_split
ShowPipelineTemplateJsonModal.tsx
import React from 'react'; import { IPromise } from 'angular'; import classNames from 'classnames'; import { Modal } from 'react-bootstrap'; import { Spinner } from 'core/widgets/spinners/Spinner'; import { IModalComponentProps, JsonEditor } from 'core/presentation'; import { IPipelineTemplateV2 } from 'core/domain';...
return ( <> <ModalClose dismiss={dismissModal} /> <Modal.Header> <Modal.Title>{modalHeading}</Modal.Title> </Modal.Header> <Modal.Body className="flex-fill"> <p>{descriptionText}</p> <form className="form-horizontal"> <div className="f...
{ return ( <> <ModalClose dismiss={dismissModal} /> <Modal.Header> <Modal.Title>{modalHeading}</Modal.Title> </Modal.Header> <Modal.Body className="flex-fill"> <div className="text-center"> <Spinner size="medium" message="Savin...
conditional_block
ShowPipelineTemplateJsonModal.tsx
import React from 'react'; import { IPromise } from 'angular'; import classNames from 'classnames'; import { Modal } from 'react-bootstrap'; import { Spinner } from 'core/widgets/spinners/Spinner'; import { IModalComponentProps, JsonEditor } from 'core/presentation'; import { IPipelineTemplateV2 } from 'core/domain';...
(props: IShowPipelineTemplateJsonModalProps) { super(props); this.state = { template: props.template, saveError: null, saving: false }; } private onChange = (e: React.ChangeEvent<HTMLInputElement>, property: string) => { if (!this.props.editable) { return; } this.setState({ template...
constructor
identifier_name
report.py
import json, uuid from six import PY3 from wptserve.utils import isomorphic_decode
response.headers.set(b'Access-Control-Allow-Headers', b'Content-Type') response.headers.set(b'Cache-Control', b'no-cache, no-store, must-revalidate'); if request.method == u'OPTIONS': # CORS preflight return b'' key = 0 if b'endpoint' in request.GET: # Use Python version checking he...
def main(request, response): response.headers.set(b'Access-Control-Allow-Origin', b'*') response.headers.set(b'Access-Control-Allow-Methods', b'OPTIONS, GET, POST')
random_line_split
report.py
import json, uuid from six import PY3 from wptserve.utils import isomorphic_decode def main(request, response):
if request.method == u'POST': reports = request.server.stash.take(key) or [] for report in json.loads(request.body): reports.append(report) request.server.stash.put(key, reports) return b"done" if request.method == u'GET': response.headers.set(b'Content-Type'...
response.headers.set(b'Access-Control-Allow-Origin', b'*') response.headers.set(b'Access-Control-Allow-Methods', b'OPTIONS, GET, POST') response.headers.set(b'Access-Control-Allow-Headers', b'Content-Type') response.headers.set(b'Cache-Control', b'no-cache, no-store, must-revalidate'); if request.method...
identifier_body
report.py
import json, uuid from six import PY3 from wptserve.utils import isomorphic_decode def main(request, response): response.headers.set(b'Access-Control-Allow-Origin', b'*') response.headers.set(b'Access-Control-Allow-Methods', b'OPTIONS, GET, POST') response.headers.set(b'Access-Control-Allow-Headers', b'C...
if request.method == u'GET': response.headers.set(b'Content-Type', b'application/json') return json.dumps(request.server.stash.take(key) or []) response.status = 400 return b'invalid method'
reports = request.server.stash.take(key) or [] for report in json.loads(request.body): reports.append(report) request.server.stash.put(key, reports) return b"done"
conditional_block
report.py
import json, uuid from six import PY3 from wptserve.utils import isomorphic_decode def
(request, response): response.headers.set(b'Access-Control-Allow-Origin', b'*') response.headers.set(b'Access-Control-Allow-Methods', b'OPTIONS, GET, POST') response.headers.set(b'Access-Control-Allow-Headers', b'Content-Type') response.headers.set(b'Cache-Control', b'no-cache, no-store, must-revalidate...
main
identifier_name
agent_manager.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 New Dream Network, LLC (DreamHost) # # 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/li...
(self, context, pool_id=None, host=None): """Handle RPC cast from plugin to modify a pool if known to agent.""" if self.cache.get_by_pool_id(pool_id): self.refresh_device(pool_id) def destroy_pool(self, context, pool_id=None, host=None): """Handle RPC cast from plugin to destroy...
modify_pool
identifier_name
agent_manager.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 New Dream Network, LLC (DreamHost) # # 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/li...
# history # 1.0 Initial version # 1.1 Support agent_updated call RPC_API_VERSION = '1.1' def __init__(self, conf): self.conf = conf try: vif_driver = importutils.import_object(conf.interface_driver, conf) except ImportError: # the driver is optio...
return self.pool_lookup.keys() class LbaasAgentManager(periodic_task.PeriodicTasks):
random_line_split
agent_manager.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 New Dream Network, LLC (DreamHost) # # 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/li...
self.agent_state = { 'binary': 'neutron-loadbalancer-agent', 'host': conf.host, 'topic': plugin_driver.TOPIC_LOADBALANCER_AGENT, 'configurations': {'device_driver': conf.device_driver, 'interface_driver': conf.interface_driver}, ...
self.conf = conf try: vif_driver = importutils.import_object(conf.interface_driver, conf) except ImportError: # the driver is optional msg = _('Error importing interface driver: %s') raise SystemExit(msg % conf.interface_driver) vif_driver = No...
identifier_body
agent_manager.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 New Dream Network, LLC (DreamHost) # # 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/li...
def get_by_pool_id(self, pool_id): return self.pool_lookup.get(pool_id) def get_by_port_id(self, port_id): return self.port_lookup.get(port_id) def get_pool_ids(self): return self.pool_lookup.keys() class LbaasAgentManager(periodic_task.PeriodicTasks): # history # 1....
self.devices.remove(d)
conditional_block
type-alias-enum-variants-pass.rs
// run-pass // Check that it is possible to resolve, in the value namespace, // to an `enum` variant through a type alias. This includes `Self`. // Type qualified syntax `<Type>::Variant` also works when syntactically valid. #[derive(Debug, PartialEq, Eq)] enum Foo { Bar(i32), Baz { i: i32 }, Qux, } type...
() -> Self { let x = Self::Bar(3); assert_eq!(x, <Self>::Bar(3)); check_pat!(x, Self::Bar(3)); x } fn baz() -> Self { let x = Self::Baz { i: 42 }; check_pat!(x, Self::Baz { i: 42 }); x } fn qux() -> Self { let x = Self::Qux; asser...
bar
identifier_name
type-alias-enum-variants-pass.rs
// run-pass // Check that it is possible to resolve, in the value namespace, // to an `enum` variant through a type alias. This includes `Self`. // Type qualified syntax `<Type>::Variant` also works when syntactically valid. #[derive(Debug, PartialEq, Eq)] enum Foo { Bar(i32), Baz { i: i32 }, Qux, } type...
}
random_line_split
type-alias-enum-variants-pass.rs
// run-pass // Check that it is possible to resolve, in the value namespace, // to an `enum` variant through a type alias. This includes `Self`. // Type qualified syntax `<Type>::Variant` also works when syntactically valid. #[derive(Debug, PartialEq, Eq)] enum Foo { Bar(i32), Baz { i: i32 }, Qux, } type...
} fn main() { let bar = Foo::Bar(1); assert_eq!(bar, FooAlias::Bar(1)); assert_eq!(bar, <FooAlias>::Bar(1)); check_pat!(bar, FooAlias::Bar(1)); let baz = FooAlias::Baz { i: 2 }; assert_eq!(baz, Foo::Baz { i: 2 }); check_pat!(baz, FooAlias::Baz { i: 2 }); let qux = Foo::Qux; asser...
{ let x = Self::Qux; assert_eq!(x, <Self>::Qux); check_pat!(x, Self::Qux); check_pat!(x, <Self>::Qux); x }
identifier_body
index.js
'use strict' // dependencies var path = require('path'), request = require('request'), // container connections ccs = []; // function to get all containers function
(host, func) { request({ json: true, method: 'GET', uri: host + '/containers/json' }, function (err, resp, body) { var containers = []; if (err) { return func(err, containers); } if (resp.statusCode != 200) { return func(new ...
GetAllContainers
identifier_name
index.js
'use strict' // dependencies var path = require('path'), request = require('request'), // container connections ccs = []; // function to get all containers function GetAllContainers(host, func) { request({ json: true, method: 'GET', uri: host + '/containers/json' ...
; exports.GetAllContainers = GetAllContainers; exports.GetStats = GetStats;
{ ccs.map(function(e){ e.destroy(); ccs.pop(); }) ccs.push(request({ json: true, method: 'GET', uri: host + '/containers/' + containerID + '/stats' }) .on('data', function(data){ statsCB(JSON.parse(data)) })) }
identifier_body
index.js
'use strict' // dependencies var path = require('path'), request = require('request'), // container connections ccs = []; // function to get all containers function GetAllContainers(host, func) { request({ json: true, method: 'GET', uri: host + '/containers/json' ...
if (resp.statusCode != 200) { return func(new Error("Status from server was: " + resp.statusCode), containers); } if (body.length <= 0) { return func(new Error("You have no containers currently.", containers)) } body.forEach(function(el) { ...
{ return func(err, containers); }
conditional_block
index.js
var path = require('path'), request = require('request'), // container connections ccs = []; // function to get all containers function GetAllContainers(host, func) { request({ json: true, method: 'GET', uri: host + '/containers/json' }, function (err, resp, body) ...
'use strict' // dependencies
random_line_split
tests.rs
extern crate existent; use existent::{When, Unless}; macro_rules! basic_tests( ($($name:ident - $exp:expr),+) => ( mod test_unless { use existent::Unless; $( #[test] fn $name() { assert_eq!(Some($exp), $exp.unless(false)); ...
let mut bar = 1; assert_eq!(Some(42), (|| expensive_computation(bar)).do_unless(false)); assert_eq!(None, (|| expensive_computation(bar)).do_unless(true)); bar = 2; assert_eq!(Some(84), (|| expensive_computation(bar)).do_when(true)); assert_eq!(None, (|| expensive_computation(bar)).do_when(fa...
{ 42 * bar }
identifier_body
tests.rs
extern crate existent; use existent::{When, Unless}; macro_rules! basic_tests( ($($name:ident - $exp:expr),+) => ( mod test_unless { use existent::Unless; $( #[test] fn $name() { assert_eq!(Some($exp), $exp.unless(false)); ...
() { fn unless<'a>(s: &'a str) -> Option<&'a str> { s.unless(false) } fn when<'a>(s: &'a str) -> Option<&'a str> { s.when(true) } let x = "Abandoning".to_string(); let ys = { let y = &x[..]; unless(y) }; assert_eq!(Some(&*x), ys); let ys = { ...
lifetimes_work
identifier_name
tests.rs
extern crate existent; use existent::{When, Unless}; macro_rules! basic_tests( ($($name:ident - $exp:expr),+) => ( mod test_unless { use existent::Unless; $( #[test] fn $name() { assert_eq!(Some($exp), $exp.unless(false)); ...
assert_eq!(None, Unless::unless(Foo(6), true)); assert_eq!(Some(Foo(7)), Unless::unless(Foo(7), false)); assert_eq!(None, Foo(8).when(true)); assert_eq!(None, Foo(3).when(false)); assert_eq!(Some(Foo(52)), Foo(2).unless(true)); assert_eq!(Some(Foo(52)), Foo(1).unless(false)); } #[test] fn lazy...
random_line_split
coinFeature.js
/** * @author Kate Compton */ define(["common", "threeUtils", "graph", "ui"], function(common, threeUtils, Graph, UI) { var useMultiMaterial = false; defaultMaterial = new THREE.MeshNormalMaterial(); var darkMaterial = new THREE.MeshBasicMaterial({ color : 0xffffcc }); var wireframeMateria...
this.remod(); }, modEdgeVertex : function(p, context) { var bump = 1 + .05 * Math.sin(context.pctRing * 3); var i = context.segment; var node = context.path.nodes[i]; p.x = node.x * bump; p.y = node.y * bump; var s =...
{ this.mesh.add(this.featureShapes[i].getMesh()); }
conditional_block
coinFeature.js
/** * @author Kate Compton */ define(["common", "threeUtils", "graph", "ui"], function(common, threeUtils, Graph, UI) { var useMultiMaterial = false; defaultMaterial = new THREE.MeshNormalMaterial(); var darkMaterial = new THREE.MeshBasicMaterial({ color : 0xffffcc }); var wireframeMateria...
getMesh : function() { if (useMultiMaterial) this.mesh = THREE.SceneUtils.createMultiMaterialObject(this.modgeo.createGeometry(), multiMaterial); else this.mesh = new THREE.Mesh(this.modgeo.createGeometry(), defaultMaterial); return this.mesh;...
this.heightOffset = 50 - .004 * Math.pow(area, .8); console.log("OFFSET: " + area + " " + this.heightOffset); },
random_line_split
resize.directive.ts
import { Directive, ElementRef, EventEmitter, Inject, Input, NgZone, OnDestroy, OnInit, Output } from '@angular/core'; import { Subject, Subscription } from 'rxjs'; import { debounceTime } from 'rxjs/operators'; import { ResizeObserverEntry } from './resize-observer-entry'; import { RESIZE_OBSERVER } from './resize-obs...
emit = (x: ResizeObserverEntry) => this.zone.run(() => this.resize.emit(x.contentRect)); }
} subscribe = (entries: Array<ResizeObserverEntry>) => entries.forEach(x => this.subject.next(x));
random_line_split
resize.directive.ts
import { Directive, ElementRef, EventEmitter, Inject, Input, NgZone, OnDestroy, OnInit, Output } from '@angular/core'; import { Subject, Subscription } from 'rxjs'; import { debounceTime } from 'rxjs/operators'; import { ResizeObserverEntry } from './resize-observer-entry'; import { RESIZE_OBSERVER } from './resize-obs...
this.subscription.add(this.subject.pipe( debounceTime(this.time) ).subscribe(this.emit)); } ngOnDestroy(): void { if (this.observer) { this.observer.disconnect(); } this.subscription.unsubscribe(); } subscribe = (entries: Array<ResizeObs...
{ this.observer = new this.resizeObserver(this.subscribe); this.observer.observe(this.elementRef.nativeElement); }
conditional_block
resize.directive.ts
import { Directive, ElementRef, EventEmitter, Inject, Input, NgZone, OnDestroy, OnInit, Output } from '@angular/core'; import { Subject, Subscription } from 'rxjs'; import { debounceTime } from 'rxjs/operators'; import { ResizeObserverEntry } from './resize-observer-entry'; import { RESIZE_OBSERVER } from './resize-obs...
(): void { if (this.resizeObserver) { this.observer = new this.resizeObserver(this.subscribe); this.observer.observe(this.elementRef.nativeElement); } this.subscription.add(this.subject.pipe( debounceTime(this.time) ).subscribe(this.emit)); } ...
ngOnInit
identifier_name
Arrows.js
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/TeX/AMS/Regular/Arrows.js * * Copyright (c) 2009-2016 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with th...
* See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.Hub.Insert( MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['MathJax_AMS'], { 0x2190: [437,-64,500,64,422], // LEFTWARDS ARROW 0x2192: [437,-64,500,58,417], // RIGHTWARD...
random_line_split
v1_namespace_spec.py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.6.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re ...
""" Returns true if both objects are not equal """ return not self == other
identifier_body
v1_namespace_spec.py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.6.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re ...
def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
""" Returns true if both objects are equal """ return self.__dict__ == other.__dict__
random_line_split
v1_namespace_spec.py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.6.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re ...
elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, v...
result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value ))
conditional_block
v1_namespace_spec.py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.6.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re ...
(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if ...
to_dict
identifier_name
modulo.js
import _curry2 from './internal/_curry2.js'; /** * Divides the first parameter by the second and returns the remainder. Note * that this function preserves the JavaScript-style behavior for modulo. For
* * @func * @memberOf R * @since v0.1.1 * @category Math * @sig Number -> Number -> Number * @param {Number} a The value to the divide. * @param {Number} b The pseudo-modulus * @return {Number} The result of `b % a`. * @see R.mathMod * @example * * R.modulo(17, 3); //=> 2 * // JS behavior: * ...
* mathematical modulo see [`mathMod`](#mathMod).
random_line_split
gulpfile.js
var fs = require('fs'); var path = require('path'); var gulp = require('gulp'); var plugins = require('gulp-load-plugins')(); // Load all gulp plugins // automatically and attach // them to the `plugins` object var runSequence...
}); gulp.task('copy:jquery', function () { return gulp.src(['node_modules/jquery/dist/jquery.min.js']) .pipe(plugins.rename('jquery-' + pkg.devDependencies.jquery + '.min.js')) .pipe(gulp.dest(dirs.dist + '/js/vendor')); }); gulp.task('copy:license', function () { return gulp.src...
gulp.task('copy:index.html', function () { return gulp.src(dirs.src + '/index.html') .pipe(plugins.replace(/{{JQUERY_VERSION}}/g, pkg.devDependencies.jquery)) .pipe(gulp.dest(dirs.dist));
random_line_split
index.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {View} from 'react-native'; import EmbeddedBinding from './embedded_binding'; import type {AppBinding} from '@mm-redux/types/apps'; import type {Theme} from '@mm-redux/typ...
/>, ); }); return ( <View style={{flex: 1, flexDirection: 'column'}}> {content} </View> ); }; export default EmbeddedBindings;
random_line_split
ProvenanceGraphUtils.ts
/** * Created by sam on 12.02.2015. */ import {PluginRegistry} from '../app/PluginRegistry'; import {ObjectNode, IObjectRef, ObjectRefUtils} from './ObjectNode'; import {StateNode, } from './StateNode'; import {ActionNode, IActionCompressor} from './ActionNode'; import {SlideNode} from './SlideNode'; import {GraphEdg...
(): ICmdFunctionFactory { const facts = PluginRegistry.getInstance().listPlugins('actionFactory'); const singles = PluginRegistry.getInstance().listPlugins('actionFunction'); function resolveFun(id: string) { if (id === 'noop') { return ResolveNow.resolveImmediately(ProvenanceGraphUtils.noop)...
createLazyCmdFunctionFactory
identifier_name
ProvenanceGraphUtils.ts
/** * Created by sam on 12.02.2015. */ import {PluginRegistry} from '../app/PluginRegistry'; import {ObjectNode, IObjectRef, ObjectRefUtils} from './ObjectNode'; import {StateNode, } from './StateNode'; import {ActionNode, IActionCompressor} from './ActionNode'; import {SlideNode} from './SlideNode'; import {GraphEdg...
* @param b * @returns {any} */ static findCommon<T>(a: T[], b: T[]) { let c = 0; while (c < a.length && c < b.length && a[c] === b[c]) { //go to next till a difference c++; } if (c === 0) { //not even the root common return null; } return { i: c - 1, j: c - 1 ...
} /** * find common element in the list of two elements returning the indices of the first same item * @param a
random_line_split
ProvenanceGraphUtils.ts
/** * Created by sam on 12.02.2015. */ import {PluginRegistry} from '../app/PluginRegistry'; import {ObjectNode, IObjectRef, ObjectRefUtils} from './ObjectNode'; import {StateNode, } from './StateNode'; import {ActionNode, IActionCompressor} from './ActionNode'; import {SlideNode} from './SlideNode'; import {GraphEdg...
return Promise.reject('no factory found for ' + id); } const lazyFunction = (id: string) => { let _resolved: PromiseLike<any> = null; return function (this: any, inputs: IObjectRef<any>[], parameters: any) { const that = this, args = Array.from(arguments); if (_resolved == nu...
{ return factory.load().then((f) => f.factory(id)); }
conditional_block
almost_prime.rs
// http://rosettacode.org/wiki/Almost_prime fn is_kprime(mut n: usize, k: usize) -> bool { let mut p = 2; let mut f = 0; while f < k && p * p <= n { while 0 == n % p { n /= p; f += 1; } p += 1; } f + (n > 1) as usize == k } fn get_kprimes(k: usize,...
#[test] fn k_equals_4() { assert!(get_kprimes(4, 10) == [16, 24, 36, 40, 54, 56, 60, 81, 84, 88]); } #[test] fn k_equals_5() { assert!(get_kprimes(5, 10) == [32, 48, 72, 80, 108, 112, 120, 162, 168, 176]); } }
{ assert!(get_kprimes(3, 10) == [8, 12, 18, 20, 27, 28, 30, 42, 44, 45]); }
identifier_body
almost_prime.rs
// http://rosettacode.org/wiki/Almost_prime fn
(mut n: usize, k: usize) -> bool { let mut p = 2; let mut f = 0; while f < k && p * p <= n { while 0 == n % p { n /= p; f += 1; } p += 1; } f + (n > 1) as usize == k } fn get_kprimes(k: usize, amount: usize) -> Vec<usize> { (2..) .filter...
is_kprime
identifier_name
almost_prime.rs
// http://rosettacode.org/wiki/Almost_prime fn is_kprime(mut n: usize, k: usize) -> bool { let mut p = 2; let mut f = 0; while f < k && p * p <= n { while 0 == n % p { n /= p; f += 1; } p += 1; } f + (n > 1) as usize == k } fn get_kprimes(k: usize,...
}
random_line_split
wrapper.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use core::nonzero::NonZero; use dom::bindings::reflector::DomObject; use dom::bindings::root::{DomRoot, MutNullabl...
() -> TypedWebGLExtensionWrapper<T> { TypedWebGLExtensionWrapper { extension: MutNullableDom::new(None) } } } impl<T> WebGLExtensionWrapper for TypedWebGLExtensionWrapper<T> where T: WebGLExtension + JSTraceable + HeapSizeOf + 'static { #[allow(unsafe_c...
new
identifier_name
wrapper.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use core::nonzero::NonZero; use dom::bindings::reflector::DomObject; use dom::bindings::root::{DomRoot, MutNullabl...
fn as_any<'a>(&'a self) -> &'a Any { self } } impl<T> TypedWebGLExtensionWrapper<T> where T: WebGLExtension + JSTraceable + HeapSizeOf + 'static { pub fn dom_object(&self) -> Option<DomRoot<T::Extension>> { self.extension.get() } }
{ T::name() }
identifier_body
wrapper.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use core::nonzero::NonZero; use dom::bindings::reflector::DomObject; use dom::bindings::root::{DomRoot, MutNullabl...
#[must_root] #[derive(HeapSizeOf, JSTraceable)] pub struct TypedWebGLExtensionWrapper<T: WebGLExtension> { extension: MutNullableDom<T::Extension> } /// Typed WebGL Extension implementation. /// Exposes the exact MutNullableDom<DOMObject> type defined by the extension. impl<T: WebGLExtension> TypedWebGLExtensionWr...
fn as_any(&self) -> &Any; }
random_line_split
wrapper.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use core::nonzero::NonZero; use dom::bindings::reflector::DomObject; use dom::bindings::root::{DomRoot, MutNullabl...
unsafe { NonZero::new_unchecked(extension.reflector().get_jsobject().get()) } } fn is_supported(&self, ext: &WebGLExtensions) -> bool { self.is_enabled() || T::is_supported(ext) } fn is_enabled(&self) -> bool { self.extension.get().is_some() } fn e...
{ self.enable(ext); }
conditional_block
keyboard.js
/**
* @copyright Javier Valencia Romero * @license {@link https://github.com/jvalen/prototypePacman/blob/master/license.txt|MIT License} */ /** * Keyboard class constructor * * @class Controls.Keyboard * @constructor */ var Controls = Controls || {}; Controls.Keyboard = function() { this.KEYS = { ...
* @author Javier Valencia Romero <javiervalenciaromero@gmail.com>
random_line_split
0002_add_subscription.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-03-19 19:08 from __future__ import unicode_literals import channels.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("channels", "0001_add_tokens"), ] operations = [ migrations.CreateModel( name="Subscription", fields=[ ( "id", ...
Migration
identifier_name
0002_add_subscription.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-03-19 19:08 from __future__ import unicode_literals import channels.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
("post_id", channels.models.Base36IntegerField()), ("comment_id", channels.models.Base36IntegerField(null=True)), ( "user", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, ...
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("channels", "0001_add_tokens"), ] operations = [ migrations.CreateModel( name="Subscription", fields=[ ( "id", models.AutoField( ...
identifier_body
0002_add_subscription.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-03-19 19:08 from __future__ import unicode_literals import channels.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migr...
operations = [ migrations.CreateModel( name="Subscription", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, ...
random_line_split
debug_element_view_listener.ts
import { CONST_EXPR, isPresent, NumberWrapper, StringWrapper, RegExpWrapper } from 'angular2/src/facade/lang'; import {MapWrapper, Map, ListWrapper, List} from 'angular2/src/facade/collection'; import {Injectable, bind, Binding} from 'angular2/di'; import {AppViewListener} from 'angular2/src/core/compiler/vie...
} export var ELEMENT_PROBE_CONFIG = [ DebugElementViewListener, bind(AppViewListener).toAlias(DebugElementViewListener), ];
random_line_split
debug_element_view_listener.ts
import { CONST_EXPR, isPresent, NumberWrapper, StringWrapper, RegExpWrapper } from 'angular2/src/facade/lang'; import {MapWrapper, Map, ListWrapper, List} from 'angular2/src/facade/collection'; import {Injectable, bind, Binding} from 'angular2/di'; import {AppViewListener} from 'angular2/src/core/compiler/vie...
(element): List<number> { var elId = DOM.getData(element, NG_ID_PROPERTY); if (isPresent(elId)) { return ListWrapper.map(StringWrapper.split(elId, NG_ID_SEPARATOR_RE), (partStr) => NumberWrapper.parseInt(partStr, 10)); } else { return null; } } export function inspectDomEleme...
_getElementId
identifier_name
debug_element_view_listener.ts
import { CONST_EXPR, isPresent, NumberWrapper, StringWrapper, RegExpWrapper } from 'angular2/src/facade/lang'; import {MapWrapper, Map, ListWrapper, List} from 'angular2/src/facade/collection'; import {Injectable, bind, Binding} from 'angular2/di'; import {AppViewListener} from 'angular2/src/core/compiler/vie...
export function inspectDomElement(element): DebugElement { var elId = _getElementId(element); if (isPresent(elId)) { var view = MapWrapper.get(_allViewsById, elId[0]); if (isPresent(view)) { return new DebugElement(view, elId[1]); } } return null; } @Injectable() export class DebugElementVi...
{ var elId = DOM.getData(element, NG_ID_PROPERTY); if (isPresent(elId)) { return ListWrapper.map(StringWrapper.split(elId, NG_ID_SEPARATOR_RE), (partStr) => NumberWrapper.parseInt(partStr, 10)); } else { return null; } }
identifier_body
debug_element_view_listener.ts
import { CONST_EXPR, isPresent, NumberWrapper, StringWrapper, RegExpWrapper } from 'angular2/src/facade/lang'; import {MapWrapper, Map, ListWrapper, List} from 'angular2/src/facade/collection'; import {Injectable, bind, Binding} from 'angular2/di'; import {AppViewListener} from 'angular2/src/core/compiler/vie...
return null; } @Injectable() export class DebugElementViewListener implements AppViewListener { constructor() { DOM.setGlobalVar(INSPECT_GLOBAL_NAME, inspectDomElement); } viewCreated(view: AppView) { var viewId = _nextId++; MapWrapper.set(_allViewsById, viewId, view); MapWrapper.set(_allIdsByView,...
{ var view = MapWrapper.get(_allViewsById, elId[0]); if (isPresent(view)) { return new DebugElement(view, elId[1]); } }
conditional_block
conftest.py
"""Fixtures for pywemo.""" import asyncio from unittest.mock import create_autospec, patch import pytest import pywemo from homeassistant.components.wemo import CONF_DISCOVERY, CONF_STATIC from homeassistant.components.wemo.const import DOMAIN from homeassistant.setup import async_setup_component MOCK_HOST = "127.0....
registry.on.side_effect = on_func with patch("pywemo.SubscriptionRegistry", return_value=registry): yield registry @pytest.fixture(name="pywemo_device") def pywemo_device_fixture(pywemo_registry, pywemo_model): """Fixture for WeMoDevice instances.""" device = create_autospec(getattr(pywemo,...
registry.callbacks[device.name] = callback registry.semaphore.release()
identifier_body
conftest.py
"""Fixtures for pywemo.""" import asyncio from unittest.mock import create_autospec, patch import pytest import pywemo from homeassistant.components.wemo import CONF_DISCOVERY, CONF_STATIC from homeassistant.components.wemo.const import DOMAIN from homeassistant.setup import async_setup_component MOCK_HOST = "127.0....
(device, type_filter, callback): registry.callbacks[device.name] = callback registry.semaphore.release() registry.on.side_effect = on_func with patch("pywemo.SubscriptionRegistry", return_value=registry): yield registry @pytest.fixture(name="pywemo_device") def pywemo_device_fixture(...
on_func
identifier_name
conftest.py
"""Fixtures for pywemo.""" import asyncio from unittest.mock import create_autospec, patch import pytest import pywemo from homeassistant.components.wemo import CONF_DISCOVERY, CONF_STATIC from homeassistant.components.wemo.const import DOMAIN from homeassistant.setup import async_setup_component MOCK_HOST = "127.0....
def pywemo_model_fixture(): """Fixture containing a pywemo class name used by pywemo_device_fixture.""" return "Insight" @pytest.fixture(name="pywemo_registry") def pywemo_registry_fixture(): """Fixture for SubscriptionRegistry instances.""" registry = create_autospec(pywemo.SubscriptionRegistry, inst...
@pytest.fixture(name="pywemo_model")
random_line_split
update.py
#!/usr/bin/env python ''' Module that update the software and its databases ''' import os import shutil from sys import exit import os.path import tarfile import requests from bs4 import BeautifulSoup from ...base import * from ...sentry import sentry from ...clint import progress class Updater(object): def __i...
shutil.move(inst_module, inst_module_norm) print(color.info.info(color.info.success("Installation completed"))) return 1 except Exception as e: print(color.info.info(color.info.fail("Installation failed"))) print(color.info.error(e)) retur...
shutil.rmtree(inst_module_norm)
conditional_block
update.py
#!/usr/bin/env python ''' Module that update the software and its databases ''' import os import shutil from sys import exit import os.path import tarfile import requests from bs4 import BeautifulSoup from ...base import * from ...sentry import sentry from ...clint import progress class Updater(object): def __i...
label=local_filename, expected_size=(total_length/1024)): if chunk: f.write(chunk) f.flush() return local_filename def extract(self, filename): try: tar = tarfile.open(filename) repo = tar.getnames()[0...
''' Download module from [url] to [path] ''' # get name of file to downaload local_filename = url.split('/')[-1] try: stream = requests.get(url, stream=True) total_length = int(stream.headers['Content-Length']) except requests.exceptions.RequestExc...
identifier_body
update.py
#!/usr/bin/env python '''
import shutil from sys import exit import os.path import tarfile import requests from bs4 import BeautifulSoup from ...base import * from ...sentry import sentry from ...clint import progress class Updater(object): def __init__(self, path, ver, url): self.inst_path = path self.repo_url = url ...
Module that update the software and its databases ''' import os
random_line_split
update.py
#!/usr/bin/env python ''' Module that update the software and its databases ''' import os import shutil from sys import exit import os.path import tarfile import requests from bs4 import BeautifulSoup from ...base import * from ...sentry import sentry from ...clint import progress class Updater(object): def __i...
(self): ''' Upgrade BigBrother completely ''' print(color.info.info("Fetching version from Github...")) # Retrieving github releases try: response = requests.get(self.repo_url) except requests.exceptions.RequestException as e: print(color.i...
update_all
identifier_name
TypeScript.ts
import { Binder } from './binder' import { Dialog } from './dialog' import { Channel } from './channel' import { UserMessage } from './types' type Matcher = { match: (message: UserMessage) => boolean } type DialogHandler<T extends Bot> = Matcher & { handler: (dialog: Dialog<T>, bot: T) => any } type PerformerHandl...
}
} }
random_line_split
TypeScript.ts
import { Binder } from './binder' import { Dialog } from './dialog' import { Channel } from './channel' import { UserMessage } from './types' type Matcher = { match: (message: UserMessage) => boolean } type DialogHandler<T extends Bot> = Matcher & { handler: (dialog: Dialog<T>, bot: T) => any } type PerformerHandl...
dialog(channel: string, users: string[]) { return new Dialog(this, channel, users) } abortDialog(channel: string, user: string) { this._channelFor(channel).abort(user) } protected onMessage(message: UserMessage): any { const performer = this._performerHandlers.find(c => c.match(message)) i...
{ const channel = this._channels.get(channelId) || new Channel() this._channels.set(channelId, channel) return channel }
identifier_body
TypeScript.ts
import { Binder } from './binder' import { Dialog } from './dialog' import { Channel } from './channel' import { UserMessage } from './types' type Matcher = { match: (message: UserMessage) => boolean } type DialogHandler<T extends Bot> = Matcher & { handler: (dialog: Dialog<T>, bot: T) => any } type PerformerHandl...
(channelId: string) { const channel = this._channels.get(channelId) || new Channel() this._channels.set(channelId, channel) return channel } dialog(channel: string, users: string[]) { return new Dialog(this, channel, users) } abortDialog(channel: string, user: string) { this._channelFor(ch...
_channelFor
identifier_name
us_state.py
import random from sunlight import openstates, response_cache from . import DataProvider from ...campaign.constants import (TARGET_CHAMBER_BOTH, TARGET_CHAMBER_UPPER, TARGET_CHAMBER_LOWER, ORDER_IN_ORDER, ORDER_SHUFFLE, ORDER_UPPER_FIRST, ORDER_LOWER_FIRST)
def __init__(self, cache, api_cache=None): self.cache = cache if api_cache: response_cache.enable(api_cache) def load_data(self): "Not needed, data provided over Sunlight OpenStates API, and cached on response" pass def cache_set(self, key, val): if hasa...
class USStateData(DataProvider): KEY_OPENSTATES = 'us_state:openstates:{id}'
random_line_split
us_state.py
import random from sunlight import openstates, response_cache from . import DataProvider from ...campaign.constants import (TARGET_CHAMBER_BOTH, TARGET_CHAMBER_UPPER, TARGET_CHAMBER_LOWER, ORDER_IN_ORDER, ORDER_SHUFFLE, ORDER_UPPER_FIRST, ORDER_LOWER_FIRST) class USStateData(DataProvider): KEY_OPENSTATE...
(self): "Not needed, data provided over Sunlight OpenStates API, and cached on response" pass def cache_set(self, key, val): if hasattr(self.cache, 'set'): self.cache.set(key, val) elif hasattr(self.cache, 'update'): self.cache.update({key: val}) else...
load_data
identifier_name
us_state.py
import random from sunlight import openstates, response_cache from . import DataProvider from ...campaign.constants import (TARGET_CHAMBER_BOTH, TARGET_CHAMBER_UPPER, TARGET_CHAMBER_LOWER, ORDER_IN_ORDER, ORDER_SHUFFLE, ORDER_UPPER_FIRST, ORDER_LOWER_FIRST) class USStateData(DataProvider): KEY_OPENSTATE...
def get_legid(self, legid): cache_key = self.KEY_OPENSTATES.format(id=legid) return self.get_key(cache_key) def get_uid(self, key): return self.cache.get(key) def locate_targets(self, latlon, chambers=TARGET_CHAMBER_BOTH, order=ORDER_IN_ORDER, state=None): """ Find all st...
if hasattr(self.cache, 'set'): self.cache.set(key, val) elif hasattr(self.cache, 'update'): self.cache.update({key: val}) else: raise AttributeError('cache does not appear to be dict-like')
identifier_body
us_state.py
import random from sunlight import openstates, response_cache from . import DataProvider from ...campaign.constants import (TARGET_CHAMBER_BOTH, TARGET_CHAMBER_UPPER, TARGET_CHAMBER_LOWER, ORDER_IN_ORDER, ORDER_SHUFFLE, ORDER_UPPER_FIRST, ORDER_LOWER_FIRST) class USStateData(DataProvider): KEY_OPENSTATE...
else: # default to name targets.extend(senators) targets.extend(house_reps) targets.sort() if order == ORDER_SHUFFLE: random.shuffle(targets) return targets
targets.extend(house_reps) targets.extend(senators)
conditional_block
effects.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values related to effects. use std::fmt::{self, Write}; use style_traits::values::{CssW...
Ok(()) } }
{ dest.write_str(" inset")?; }
conditional_block
effects.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values related to effects. use std::fmt::{self, Write}; use style_traits::values::{CssW...
BlurShapeLength: ToCss, ShapeLength: ToCss, { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { { let mut writer = SequenceWriter::new(&mut *dest, " "); writer.item(&self.base)?; writer.item(&self.spread)?; } ...
impl<Color, SizeLength, BlurShapeLength, ShapeLength> ToCss for BoxShadow<Color, SizeLength, BlurShapeLength, ShapeLength> where Color: ToCss, SizeLength: ToCss,
random_line_split
effects.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values related to effects. use std::fmt::{self, Write}; use style_traits::values::{CssW...
<Color, SizeLength, ShapeLength> { /// Color. pub color: Color, /// Horizontal radius. pub horizontal: SizeLength, /// Vertical radius. pub vertical: SizeLength, /// Blur radius. pub blur: ShapeLength, } impl<Color, SizeLength, BlurShapeLength, ShapeLength> ToCss for BoxShadow<Color...
SimpleShadow
identifier_name
mod.rs
use std::fmt; use std::sync::Arc; use std::net::{TcpStream, ToSocketAddrs}; use std::io::prelude::*; use std::process::{exit, Command}; use std::path::PathBuf; use my_daemonize; #[macro_use] mod toml; mod cmd; mod proxy_config; mod running_config; use self::cmd::{parse_cmds, check_and_set_from_args, check_and_set_se...
fn get_all_ips() -> Option<String> { let cmd = if cfg!(windows) { "ipconfig" } else { "ifconfig" }; let output = try_opt!(Command::new(cmd).output().ok()); String::from_utf8(output.stdout).ok() } fn check_ip(ip: &str) -> bool { if let Some(ips) = get_all_ips() { ips.f...
{ let addr = try_opt!((host, 80).to_socket_addrs().ok().and_then(|mut addrs| addrs.next())); let mut conn = try_opt!(TcpStream::connect(addr).ok()); let r = format!("GET {} HTTP/1.1\r\nHost: {}\r\n\r\n", path, host); try_opt!(conn.write_all(r.as_bytes()).ok()); let mut s = String::new(); try_opt...
identifier_body
mod.rs
use std::fmt; use std::sync::Arc; use std::net::{TcpStream, ToSocketAddrs}; use std::io::prelude::*; use std::process::{exit, Command}; use std::path::PathBuf; use my_daemonize; #[macro_use] mod toml; mod cmd; mod proxy_config; mod running_config; use self::cmd::{parse_cmds, check_and_set_from_args, check_and_set_se...
fn get_external_ip() -> ConfigResult<String> { const HOST_PATHS: &'static [(&'static str, &'static str)] = &[("ident.me", "/"), ("icanhazip.com", "/")]; let mut external_ip = None; for host_path in HOST_PATHS { let ip = echo_ip(host...
random_line_split
mod.rs
use std::fmt; use std::sync::Arc; use std::net::{TcpStream, ToSocketAddrs}; use std::io::prelude::*; use std::process::{exit, Command}; use std::path::PathBuf; use my_daemonize; #[macro_use] mod toml; mod cmd; mod proxy_config; mod running_config; use self::cmd::{parse_cmds, check_and_set_from_args, check_and_set_se...
else { // TODO: share ssserver server (check 0.0.0.0 & 127.0.0.1) if args.is_present("share_server") { exit(0); } } // setup from input and save it if no default config if let Some(input) = args.value_of("input") { let mut proxy_conf = ProxyConfig::default(); ...
{ if let Some(server_conf) = args.value_of("add_server") { let mut tmp = Arc::make_mut(&mut conf.proxy_conf); tmp.base64_decode(server_conf)?; append_to_default_config(tmp); exit(0); } // TODO: share sslocal server according mode if args.is...
conditional_block
mod.rs
use std::fmt; use std::sync::Arc; use std::net::{TcpStream, ToSocketAddrs}; use std::io::prelude::*; use std::process::{exit, Command}; use std::path::PathBuf; use my_daemonize; #[macro_use] mod toml; mod cmd; mod proxy_config; mod running_config; use self::cmd::{parse_cmds, check_and_set_from_args, check_and_set_se...
(ip: &str) -> bool { if let Some(ips) = get_all_ips() { ips.find(ip).is_some() } else { false } }
check_ip
identifier_name
en-NU.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; fun...
(n: number): number { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } export default [ 'en-NU', [['a', 'p'], ['am', 'pm'], u], [['am', 'pm'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Th...
plural
identifier_name
en-NU.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; fun...
plural ];
'$', 'New Zealand Dollar', {'JPY': ['JP¥', '¥'], 'NZD': ['$'], 'USD': ['US$', '$']}, 'ltr',
random_line_split
en-NU.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; fun...
export default [ 'en-NU', [['a', 'p'], ['am', 'pm'], u], [['am', 'pm'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] ], ...
{ let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; }
identifier_body
dig.rs
extern crate argparse; extern crate domain; extern crate tokio_core; use std::error; use std::result; use std::str::FromStr; use domain::bits::message::{MessageBuf, RecordSection}; use domain::bits::name::{DNameBuf, DNameSlice}; use domain::iana::{Class, Rtype}; use domain::resolv::{ResolvConf, Resolver}; //--------...
(&self) -> Result<Rtype> { if self.qtype.is_empty() { Ok(if self.name.is_empty() { Rtype::Ns } else { Rtype::A }) } else { Ok(try!(Rtype::from_str(&self.qtype))) } } fn qclass(&self) -> Result<Class> { Ok(Class::In) } fn conf(&self) -...
qtype
identifier_name
dig.rs
extern crate argparse; extern crate domain; extern crate tokio_core; use std::error; use std::result; use std::str::FromStr; use domain::bits::message::{MessageBuf, RecordSection}; use domain::bits::name::{DNameBuf, DNameSlice}; use domain::iana::{Class, Rtype}; use domain::resolv::{ResolvConf, Resolver}; //--------...
println!(";; ANSWER SECTION"); print_records(&mut answer); println!(""); } let mut authority = answer.next_section().unwrap().unwrap(); if response.counts().nscount() > 0 { println!(";; AUTHORITY SECTION"); print_records(&mut authority); println!(""); } ...
random_line_split
dig.rs
extern crate argparse; extern crate domain; extern crate tokio_core; use std::error; use std::result; use std::str::FromStr; use domain::bits::message::{MessageBuf, RecordSection}; use domain::bits::name::{DNameBuf, DNameSlice}; use domain::iana::{Class, Rtype}; use domain::resolv::{ResolvConf, Resolver}; //--------...
else { Ok(try!(Rtype::from_str(&self.qtype))) } } fn qclass(&self) -> Result<Class> { Ok(Class::In) } fn conf(&self) -> &ResolvConf { &self.conf } } //------------ Error and Result --------------------------------------------- type Error = Box<error::Error>;...
{ Ok(if self.name.is_empty() { Rtype::Ns } else { Rtype::A }) }
conditional_block
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use std::cell::RefCell; use std::path::Path; use ::revlogindex::RevlogIndex; use cpython::*; use cpython_...
py_class!(class revlogindex |py| { data index: RefCell<RevlogIndex>; def __new__(_cls, changelogipath: String, nodemappath: String) -> PyResult<Self> { let changelogipath = Path::new(&changelogipath); let nodemappath = Path::new(&nodemappath); let index = RevlogIndex::new(&changelogip...
{ let name = [package, "revlogindex"].join("."); let m = PyModule::new(py, &name)?; m.add_class::<revlogindex>(py)?; Ok(m) }
identifier_body
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use std::cell::RefCell; use std::path::Path; use ::revlogindex::RevlogIndex; use cpython::*; use cpython_...
(py: Python, package: &str) -> PyResult<PyModule> { let name = [package, "revlogindex"].join("."); let m = PyModule::new(py, &name)?; m.add_class::<revlogindex>(py)?; Ok(m) } py_class!(class revlogindex |py| { data index: RefCell<RevlogIndex>; def __new__(_cls, changelogipath: String, nodemapp...
init_module
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use std::cell::RefCell; use std::path::Path; use ::revlogindex::RevlogIndex; use cpython::*; use cpython_...
/// Calculate `heads(ancestors(revs))`. def headsancestors(&self, revs: Vec<u32>) -> PyResult<Vec<u32>> { let revlog = self.index(py).borrow(); Ok(revlog.headsancestors(revs).map_pyerr(py)?) } /// Given public and draft head revision numbers, calculate the "phase sets". /// Return (...
}
random_line_split
test_qcut.py
. labels, bins = qcut(arr, 4, retbins=True) ex_bins = quantile(arr, [0, 0.25, 0.5, 0.75, 1.0]) result = labels.categories.left.values assert np.allclose(result, ex_bins[:-1], atol=1e-2) result = labels.categories.right.values assert np.allclose(result, ex_bins[1:], atol=1e-2) ex_levels = ...
(labels): # GH 13318 values = range(10) msg = "Bin labels must be one fewer than the number of bin edges" with pytest.raises(ValueError, match=msg): qcut(values, 4, labels=labels) @pytest.mark.parametrize( "labels, expected", [ (["a", "b", "c"], Categorical(["a", "b", "c"], ord...
test_qcut_wrong_length_labels
identifier_name
test_qcut.py
. labels, bins = qcut(arr, 4, retbins=True) ex_bins = quantile(arr, [0, 0.25, 0.5, 0.75, 1.0]) result = labels.categories.left.values assert np.allclose(result, ex_bins[:-1], atol=1e-2) result = labels.categories.right.values assert np.allclose(result, ex_bins[1:], atol=1e-2) ex_levels = ...
@pytest.mark.parametrize( "labels, expected", [ (["a", "b", "c"], Categorical(["a", "b", "c"], ordered=True)), (list(range(3)), Categorical([0, 1, 2], ordered=True)), ], ) def test_qcut_list_like_labels(labels, expected): # GH 13318 values = range(3) result = qcut(values, 3, l...
values = range(10) msg = "Bin labels must be one fewer than the number of bin edges" with pytest.raises(ValueError, match=msg): qcut(values, 4, labels=labels)
identifier_body
test_qcut.py
labels, bins = qcut(arr, 4, retbins=True) ex_bins = quantile(arr, [0, 0.25, 0.5, 0.75, 1.0]) result = labels.categories.left.values assert np.allclose(result, ex_bins[:-1], atol=1e-2) result = labels.categories.right.values assert np.allclose(result, ex_bins[1:], atol=1e-2) ex_levels = cu...
else: expected = Series([0] * length, dtype=np.intp) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "ser", [ Series(DatetimeIndex(["20180101", NaT, "20180103"])), Series(TimedeltaIndex(["0 days", NaT, "2 days"])), ], ids=lambda x: str(x.dtype), ) d...
intervals = IntervalIndex([Interval(start, end)] * length, closed="right") expected = Series(intervals).astype(CDT(ordered=True))
conditional_block