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
book_tracker.py
# -*- coding: utf-8 -*- ''' Column names: Name, Author, Genre, StartDate, EndDate, Pages, Progress , Finished ''' from __future__ import division import sqlite3 as sql ######################################################## # DATA VIEWING # ######################################################## def ...
def show_finished(): cursor.execute('select Name from books where Finished = 1') print('Finished books:') for i in cursor.fetchall(): print(i) cursor.execute('select Name from books where Finished = 0') print('Unfinished books: ') for i in cursor.fetchall(): print(i) def show_progress(): books_dict = {}...
genres = [] cursor.execute('select Genre from books') # Use the set to avoid repeats for i in cursor.fetchall(): genres.append(i) genres = set(genres) print(genres)
identifier_body
book_tracker.py
# -*- coding: utf-8 -*- ''' Column names: Name, Author, Genre, StartDate, EndDate, Pages, Progress , Finished ''' from __future__ import division import sqlite3 as sql ######################################################## # DATA VIEWING # ######################################################## def ...
(): books_dict = {} titles = [] progress = [] pages = [] totals = [] cursor.execute('select Name from books where Finished = 0') # get the values out of the tuples! titles = cursor.fetchall() # Change to a list of unicodes titles = [i[0] for i in titles] # Change to a list of strings titles = [i.encode(...
show_progress
identifier_name
reference.py
from collections import namedtuple from uuid import uuid4 from GEMEditor.model.classes.annotation import Annotation class Reference: """ ReferenceItem contains the information a pubmed or similar literature reference Authors are saved as author instances """ def __init__(self, id=None, pmid="", pmc="", d...
def remove_link(self, item, reciprocal=True): """ Remove reference link from item Parameters ---------- item: GEMEditor.model.classes.base.ReferenceLink reciprocal: bool """ self._linked_items.discard(item) if reciprocal: item.remove_ref...
item.add_reference(self, reciprocal=False)
conditional_block
reference.py
from collections import namedtuple from uuid import uuid4 from GEMEditor.model.classes.annotation import Annotation class Reference: """ ReferenceItem contains the information a pubmed or similar literature reference Authors are saved as author instances """ def __init__(self, id=None, pmid="", pmc="", d...
(self): """ Get the authors part of the usual citation of scientific literature i.e.: Lastname F et al., YYYY if there are more than 2 authors Lastname1 F1 and Lastname2 F2, YYYY if there are 2 authors Lastname F, YYYY if there is only one author Input tuple wit...
reference_string
identifier_name
reference.py
from collections import namedtuple from uuid import uuid4 from GEMEditor.model.classes.annotation import Annotation class Reference: """ ReferenceItem contains the information a pubmed or similar literature reference Authors are saved as author instances """ def __init__(self, id=None, pmid="", pmc="", d...
@property def linked_items(self): return self._linked_items.copy() @property def annotation(self): result = set() if self.pmid: result.add(Annotation("pubmed", self.pmid)) if self.pmc: result.add(Annotation("pmc", self.pmc)) if self.doi:...
super(Reference, self).__init__() self._linked_items = set() self.id = id or str(uuid4()) self.pmid = pmid self.pmc = pmc self.doi = doi self.url = url if authors is None: self.authors = [] else: self.authors = authors self....
identifier_body
reference.py
from collections import namedtuple from uuid import uuid4 from GEMEditor.model.classes.annotation import Annotation class Reference: """ ReferenceItem contains the information a pubmed or similar literature reference Authors are saved as author instances """ def __init__(self, id=None, pmid="", pmc="", d...
item.add_reference(self, reciprocal=False) def remove_link(self, item, reciprocal=True): """ Remove reference link from item Parameters ---------- item: GEMEditor.model.classes.base.ReferenceLink reciprocal: bool """ self._linked_items.discard(it...
reciprocal: bool """ self._linked_items.add(item) if reciprocal:
random_line_split
diagnostic.rs
); fn bump_err_count(@mut self); fn err_count(@mut self) -> uint; fn has_errors(@mut self) -> bool; fn abort_if_errors(@mut self); fn warn(@mut self, msg: &str); fn note(@mut self, msg: &str); // used to indicate a bug in the compiler: fn bug(@mut self, msg: &str) -> !; fn unimpl(@mu...
pub fn ice_msg(msg: &str) -> ~str { format!("internal compiler error: {}\nThis message reflects a bug in the Rust compiler. \ \nWe would appreciate a bug report: {}", msg, BUG_REPORT_URL) } pub fn mk_span_handler(handler: @mut handler, cm: @codemap::CodeMap) -> @mut span_handler { ...
} }
random_line_split
diagnostic.rs
); fn bump_err_count(@mut self); fn err_count(@mut self) -> uint; fn has_errors(@mut self) -> bool; fn abort_if_errors(@mut self); fn warn(@mut self, msg: &str); fn note(@mut self, msg: &str); // used to indicate a bug in the compiler: fn bug(@mut self, msg: &str) -> !; fn unimpl(@mu...
{ err_count: uint, emit: @Emitter, } struct CodemapT { handler: @mut handler, cm: @codemap::CodeMap, } impl span_handler for CodemapT { fn span_fatal(@mut self, sp: Span, msg: &str) -> ! { self.handler.emit(Some((self.cm, sp)), msg, fatal); fail!(); } fn span_err(@mut self...
HandlerT
identifier_name
diagnostic.rs
); fn bump_err_count(@mut self); fn err_count(@mut self) -> uint; fn has_errors(@mut self) -> bool; fn abort_if_errors(@mut self); fn warn(@mut self, msg: &str); fn note(@mut self, msg: &str); // used to indicate a bug in the compiler: fn bug(@mut self, msg: &str) -> !; fn unimpl(@mu...
#[deriving(Eq)] pub enum level { fatal, error, warning, note, } fn diagnosticstr(lvl: level) -> ~str { match lvl { fatal => ~"error", error => ~"error", warning => ~"warning", note => ~"note" } } fn diagnosticcolor(lvl: level) -> term::color::Color { match...
{ let emit: @Emitter = match emitter { Some(e) => e, None => @DefaultEmitter as @Emitter }; @mut HandlerT { err_count: 0, emit: emit, } as @mut handler }
identifier_body
subscriber.js
AUTOBAHN_DEBUG = true; var autobahn = require('autobahn'); var program = require('commander'); program .option('-p, --port <port>', 'Server IP port', parseInt,9000) .option('-i, --ip <ip>', 'Server IP address','127.0.0.1') .parse(process.argv); var connection = new autobahn.Connection({ url: 'ws://' +...
// Subscribe to a topic session.subscribe('com.myapp.topic1', onEvent).then( function(subscription) { console.log("subscription successfull", subscription); currentSubscription = subscription; }, function(error) { console.log("subscription failed", e...
{ console.log('Event received args', publishArgs, 'kwargs ',kwargs); }
identifier_body
subscriber.js
AUTOBAHN_DEBUG = true; var autobahn = require('autobahn'); var program = require('commander'); program .option('-p, --port <port>', 'Server IP port', parseInt,9000) .option('-i, --ip <ip>', 'Server IP address','127.0.0.1') .parse(process.argv); var connection = new autobahn.Connection({ url: 'ws://' +...
(publishArgs, kwargs) { console.log('Event received args', publishArgs, 'kwargs ',kwargs); } // Subscribe to a topic session.subscribe('com.myapp.topic1', onEvent).then( function(subscription) { console.log("subscription successfull", subscription); currentSubscripti...
onEvent
identifier_name
subscriber.js
AUTOBAHN_DEBUG = true; var autobahn = require('autobahn'); var program = require('commander'); program .option('-p, --port <port>', 'Server IP port', parseInt,9000) .option('-i, --ip <ip>', 'Server IP address','127.0.0.1') .parse(process.argv); var connection = new autobahn.Connection({ url: 'ws://' +...
connection.close(); } ); }, 300000 ); }; connection.open();
random_line_split
i18n-dictionary.d.ts
/** * Structure of the i18n dictionary */ export interface I18nDictionary { /** * Section for translation Tool Names: both block and inline tools * Example: * "toolNames": { * "Text": "Параграф", * "Heading": "Заголовок", * "List": "Список", * ... * }, */ toolNames?: D...
*/ export type DictValue = {[key: string]: Dictionary | string} | string;
* - result translate string
random_line_split
order.test.ts
/* eslint-disable promise/always-return */ import { runQuery } from "schema/v1/test/utils" import { mockxchange } from "test/fixtures/exchange/mockxchange" import { sampleOrder } from "test/fixtures/results/sample_order" import exchangeOrderJSON from "test/fixtures/exchange/buy_order.json" import gql from "lib/gql" im...
` return runQuery(query, context).then(data => { expect(data!.order).toEqual( sampleOrder({ fulfillments: true, includeCreditCard: true, }) ) }) }) })
{ order(id: "52dd3c2e4b8480091700027f") { ${OrderSellerFields} } }
random_line_split
main.js
// allow override variables here require.context('../../assets/stylesheets/', false, /variables.*\.scss$/); // import default stylesheet with variables require('font-awesome/css/font-awesome.css'); require('../styles/application.scss'); function
(callback) { if (document.readyState !== 'loading') { callback(); } else { document.addEventListener('DOMContentLoaded', callback); } } function main() { const Mastodon = require('mastodon/containers/mastodon').default; const React = require('react'); const ReactDOM = require('react-dom'); window...
onDomContentLoaded
identifier_name
main.js
// allow override variables here require.context('../../assets/stylesheets/', false, /variables.*\.scss$/); // import default stylesheet with variables require('font-awesome/css/font-awesome.css'); require('../styles/application.scss'); function onDomContentLoaded(callback) { if (document.readyState !== 'loading')
else { document.addEventListener('DOMContentLoaded', callback); } } function main() { const Mastodon = require('mastodon/containers/mastodon').default; const React = require('react'); const ReactDOM = require('react-dom'); window.Perf = require('react-addons-perf'); require.context('../images/', true...
{ callback(); }
conditional_block
main.js
// allow override variables here require.context('../../assets/stylesheets/', false, /variables.*\.scss$/); // import default stylesheet with variables require('font-awesome/css/font-awesome.css'); require('../styles/application.scss'); function onDomContentLoaded(callback)
function main() { const Mastodon = require('mastodon/containers/mastodon').default; const React = require('react'); const ReactDOM = require('react-dom'); window.Perf = require('react-addons-perf'); require.context('../images/', true); // import customization styles require.context('../../assets/style...
{ if (document.readyState !== 'loading') { callback(); } else { document.addEventListener('DOMContentLoaded', callback); } }
identifier_body
main.js
// allow override variables here require.context('../../assets/stylesheets/', false, /variables.*\.scss$/); // import default stylesheet with variables require('font-awesome/css/font-awesome.css');
function onDomContentLoaded(callback) { if (document.readyState !== 'loading') { callback(); } else { document.addEventListener('DOMContentLoaded', callback); } } function main() { const Mastodon = require('mastodon/containers/mastodon').default; const React = require('react'); const ReactDOM = re...
require('../styles/application.scss');
random_line_split
Conakry.py
'''tzinfo timezone information for Africa/Conakry.''' from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i
class Conakry(DstTzInfo): '''Africa/Conakry timezone definition. See datetime.tzinfo for details''' zone = 'Africa/Conakry' _utc_transition_times = [ d(1,1,1,0,0,0), d(1912,1,1,0,54,52), d(1934,2,26,0,0,0), d(1960,1,1,1,0,0), ] _transition_info = [ i(-3300,0,'LMT'), i(0,0,'GMT'), i(-3600,0,'W...
random_line_split
Conakry.py
'''tzinfo timezone information for Africa/Conakry.''' from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i class
(DstTzInfo): '''Africa/Conakry timezone definition. See datetime.tzinfo for details''' zone = 'Africa/Conakry' _utc_transition_times = [ d(1,1,1,0,0,0), d(1912,1,1,0,54,52), d(1934,2,26,0,0,0), d(1960,1,1,1,0,0), ] _transition_info = [ i(-3300,0,'LMT'), i(0,0,'GMT'), i(-3600,0,'WAT'), i(0,0,'...
Conakry
identifier_name
Conakry.py
'''tzinfo timezone information for Africa/Conakry.''' from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i class Conakry(DstTzInfo):
Conakry = Conakry()
'''Africa/Conakry timezone definition. See datetime.tzinfo for details''' zone = 'Africa/Conakry' _utc_transition_times = [ d(1,1,1,0,0,0), d(1912,1,1,0,54,52), d(1934,2,26,0,0,0), d(1960,1,1,1,0,0), ] _transition_info = [ i(-3300,0,'LMT'), i(0,0,'GMT'), i(-3600,0,'WAT'), i(0,0,'GMT'), ]
identifier_body
setup.py
from setuptools import setup, find_packages from setuptools.command.test import test class TestCommand(test): def run(self):
setup( name='aino-utkik', version='0.9.1', description='Small, clean code with a lazy view dispatcher and class based views for Django.', long_description=open('README.rst').read(), author='Mikko Hellsing', author_email='mikko@aino.se', license='BSD', url='https://github.com/aino/aino...
from tests.runtests import runtests runtests()
identifier_body
setup.py
from setuptools import setup, find_packages from setuptools.command.test import test class
(test): def run(self): from tests.runtests import runtests runtests() setup( name='aino-utkik', version='0.9.1', description='Small, clean code with a lazy view dispatcher and class based views for Django.', long_description=open('README.rst').read(), author='Mikko Hellsing', ...
TestCommand
identifier_name
setup.py
from setuptools import setup, find_packages from setuptools.command.test import test class TestCommand(test): def run(self): from tests.runtests import runtests runtests() setup( name='aino-utkik', version='0.9.1', description='Small, clean code with a lazy view dispatcher and class ...
'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Framework :: Dj...
random_line_split
feedback.py
from pyramid.view import view_config from externals.lib.misc import strip_non_base_types from externals.lib.log import log_event from . import web, action_ok, action_error from ..model import DBSession from ..model.model_feedback import Feedback import logging log = logging.getLogger(__name__) @view_config(route_n...
log_event(request, **request.params) return action_ok(message='Feedback received, thank you!')
""" Feedback """ if request.method == 'GET': if request.session.get('admin'): log.info('admin viewed feedback') return action_ok(data={'feedback': [feedback.to_dict() for feedback in DBSession.query(Feedback)]}) return action_ok() if not request.params.get('detai...
identifier_body
feedback.py
from pyramid.view import view_config from externals.lib.misc import strip_non_base_types from externals.lib.log import log_event from . import web, action_ok, action_error from ..model import DBSession from ..model.model_feedback import Feedback import logging log = logging.getLogger(__name__) @view_config(route_n...
(request): """ Feedback """ if request.method == 'GET': if request.session.get('admin'): log.info('admin viewed feedback') return action_ok(data={'feedback': [feedback.to_dict() for feedback in DBSession.query(Feedback)]}) return action_ok() if not request.pa...
feedback_view
identifier_name
feedback.py
from pyramid.view import view_config from externals.lib.misc import strip_non_base_types from externals.lib.log import log_event from . import web, action_ok, action_error from ..model import DBSession from ..model.model_feedback import Feedback import logging log = logging.getLogger(__name__) @view_config(route_n...
if not request.params.get('details'): raise action_error('Please provide feedback details', code=400) feedback = Feedback() for field, value in request.params.items(): try: setattr(feedback, field,value) except: pass feedback.environ = strip_non_base_types(request.environ) ...
if request.session.get('admin'): log.info('admin viewed feedback') return action_ok(data={'feedback': [feedback.to_dict() for feedback in DBSession.query(Feedback)]}) return action_ok()
conditional_block
feedback.py
from pyramid.view import view_config from externals.lib.misc import strip_non_base_types from externals.lib.log import log_event from . import web, action_ok, action_error from ..model import DBSession from ..model.model_feedback import Feedback import logging log = logging.getLogger(__name__) @view_config(route_n...
feedback = Feedback() for field, value in request.params.items(): try: setattr(feedback, field,value) except: pass feedback.environ = strip_non_base_types(request.environ) DBSession.add(feedback) log.info('feedback - {0}'.format(request.params.get('details'))) log_event(request,...
random_line_split
authentication.js
const request = require('request-promise') const config = require('../tool/config.js') const api = require('../tool/api.js') const error = require('../tool/error.js') const Const = require('../tool/const.js') const exp = { URL : '/authenticate', ACTION : (req, res) => { try { const params =...
res.json({ success : true, token : data.token, user : data.user }) }) .catch((err) => { if (err.statusCode == 401) error.fn401(res, ...
.then((data) => {
random_line_split
edition-keywords-2015-2015.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() {}
main
identifier_name
edition-keywords-2015-2015.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
mod one_async { produces_async! {} // OK } mod two_async { produces_async_raw! {} // OK } fn main() {}
{ let mut async = 1; // OK let mut r#async = 1; // OK r#async = consumes_async!(async); // OK // r#async = consumes_async!(r#async); // ERROR, not a match // r#async = consumes_async_raw!(async); // ERROR, not a match r#async = consumes_async_raw!(r#async); // OK if passes_ident!(async) ==...
identifier_body
edition-keywords-2015-2015.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// OK one_async::async(); // OK one_async::r#async(); // OK two_async::async(); // OK two_async::r#async(); // OK } mod one_async { produces_async! {} // OK } mod two_async { produces_async_raw! {} // OK } fn main() {}
{}
conditional_block
edition-keywords-2015-2015.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
#![allow(unused_mut)] #![allow(unused_assignments)] #![allow(unused_variables)] // edition:2015 // aux-build:edition-kw-macro-2015.rs #[macro_use] extern crate edition_kw_macro_2015; pub fn check_async() { let mut async = 1; // OK let mut r#async = 1; // OK r#async = consumes_async!(async); // OK //...
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
kwd.py
import helpers from config import render, db class Keyword(object): def
(self): keyword_count = db.query('SELECT KEYWORD,\ COUNT(DISTINCT IPKEY) AS PACKAGES,\ COUNT(DISTINCT UUID) AS HOSTS\ FROM GLOBAL_KEYWORDS NATURAL JOIN KEYWORDS\ NATURAL JOIN INSTALLED_PACKAGES GROUP BY KEYWORD') keyword_data = dict() ...
GET
identifier_name
kwd.py
import helpers from config import render, db class Keyword(object): def GET(self): keyword_count = db.query('SELECT KEYWORD,\ COUNT(DISTINCT IPKEY) AS PACKAGES,\
COUNT(DISTINCT UUID) AS HOSTS\ FROM GLOBAL_KEYWORDS NATURAL JOIN KEYWORDS\ NATURAL JOIN INSTALLED_PACKAGES GROUP BY KEYWORD') keyword_data = dict() for t in keyword_count: keyword_data[t['KEYWORD']] = {'HOSTS':t['HOSTS'], 'PACKAGES':t['PACKAGES...
random_line_split
kwd.py
import helpers from config import render, db class Keyword(object):
def GET(self): keyword_count = db.query('SELECT KEYWORD,\ COUNT(DISTINCT IPKEY) AS PACKAGES,\ COUNT(DISTINCT UUID) AS HOSTS\ FROM GLOBAL_KEYWORDS NATURAL JOIN KEYWORDS\ NATURAL JOIN INSTALLED_PACKAGES GROUP BY KEYWORD') keyword_data = dict(...
identifier_body
kwd.py
import helpers from config import render, db class Keyword(object): def GET(self): keyword_count = db.query('SELECT KEYWORD,\ COUNT(DISTINCT IPKEY) AS PACKAGES,\ COUNT(DISTINCT UUID) AS HOSTS\ FROM GLOBAL_KEYWORDS NATURAL JOIN KEYWORDS\ NATUR...
x_ticklabels = keyword_data.keys() y_values = [ keyword_data[k]['PACKAGES'] for k in x_ticklabels ] keyword_plot = helpers.barchart(title = 'Installed packages per keyword', x_label = 'Keyword', y_label = 'Number of Packages', x_ticklabels = x_ticklabels, ...
conditional_block
update.ts
[0] === 'update-help') { prog.printHelp(); } let browserFile: BrowserFile; /** * Parses the options and downloads binaries if they do not exist. * @param options */ function update(options: Options): Promise<void> { let promises: q.IPromise<void>[] = []; let standalone = options[Opt.STANDALONE].getBoolean();...
{ logger.info('appium: installing appium'); let folder = path.resolve(outputDir, binary.filename()); try { rimraf.sync(folder); } catch (err) { } fs.mkdirSync(folder); fs.writeFileSync( path.resolve(folder, 'package.json'), JSON.stringify({scripts: {appium: 'appium'}})); spawn('npm', ['insta...
identifier_body
update.ts
DN]) .addOption(Opts[Opt.STANDALONE]) .addOption(Opts[Opt.CHROME]) .addOption(Opts[Opt.GECKO]) .addOption(Opts[Opt.ANDROID]) .addOption(Opts[Opt.ANDROID_API_LEVELS]) .addOption(Opts[Opt.ANDROID_ARCHITECTURES]) .addO...
promises.push(q.nfcall(fs.readFile, path.resolve(sdk_path, 'available_avds.json')) .then( (oldAVDs: string) => { oldAVDList = oldAVDs; }, () => { oldAVDList = '...
let binary = binaries[AndroidSDK.id]; let sdk_path = path.resolve(outputDir, binary.executableFilename()); let oldAVDList: string; updateBrowserFile(binary, outputDir);
random_line_split
update.ts
DN]) .addOption(Opts[Opt.STANDALONE]) .addOption(Opts[Opt.CHROME]) .addOption(Opts[Opt.GECKO]) .addOption(Opts[Opt.ANDROID]) .addOption(Opts[Opt.ANDROID_API_LEVELS]) .addOption(Opts[Opt.ANDROID_ARCHITECTURES]) .addO...
if (ie64) { let binary: IEDriver = binaries[IEDriver.id]; binary.osarch = Config.osArch(); // Win32 or x64 promises.push(updateBinary(binary, outputDir, proxy, ignoreSSL).then(() => { return Promise.resolve(updateBrowserFile(binary, outputDir)); })); } if (ie32) { let binary: IEDriver ...
{ let binary: GeckoDriver = binaries[GeckoDriver.id]; promises.push(updateBinary(binary, outputDir, proxy, ignoreSSL).then(() => { return Promise.resolve(updateBrowserFile(binary, outputDir)); })); }
conditional_block
update.ts
PIUM]) .addOption(Opts[Opt.VERSIONS_ANDROID]) .addOption(Opts[Opt.VERSIONS_GECKO]); if (Config.osType() === 'Windows_NT') { prog.addOption(Opts[Opt.VERSIONS_IE]); } export let program = prog; // stand alone runner let argv = minimist(process.argv.slice(2), prog.getMinimistOptions()); if (argv._[0] === 'upda...
installAppium
identifier_name
udpros.py
of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES...
self.init_server() #TODO: parse/validate headers sub = rospy.registration.get_topic_manager().get_subscriber_impl(topic_name) # Create Transport # TODO: create just a single 'connection' instance to represent # all UDP connections. 'connection' can tak...
""" Connect to topic resolved_name on Publisher pub_uri using UDPROS. @param resolved_name str: resolved topic name @type resolved_name: str @param pub_uri: XML-RPC URI of publisher @type pub_uri: str @param protocol_params: protocol parameters to use for connecting ...
identifier_body
udpros.py
names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARR...
def __init__(self, protocol, name, header): """ ctor @param name: topic name @type name: str: @param protocol: protocol implementation @param protocol: UDPROSTransportProtocol @param header: handshake header if transport handshake header was ...
transport_type = 'UDPROS'
random_line_split
udpros.py
of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES...
def supports(self, protocol): """ @param protocol: name of protocol @type protocol: str @return: True if protocol is supported @rtype: bool """ return protocol == UDPROS def get_supported(self): """ Get supported protocols ""...
transport.close() return 0, "ERROR: Race condition failure: duplicate topic subscriber [%s] was created"%(topic_name), 0
conditional_block
udpros.py
): """ rospy protocol handler for UDPROS. Stores the datagram server if necessary. """ def __init__(self, port=0): """ ctor """ self.port = port self.buff_size = get_max_datagram_size() def init_server(self): """ Initialize and st...
receive_loop
identifier_name
syntax_iterators.py
from typing import Union, Iterator, Tuple from ...tokens import Doc, Span from ...symbols import NOUN, PROPN, PRON from ...errors import Errors def noun_chunks(doclike: Union[Doc, Span]) -> Iterator[Tuple[int, int, int]]: """ Detect base noun phrases from a dependency parse. Works on both Doc and Span. ""...
# Prevent nested chunks from being produced if word.i >= prev_end: continue if word.dep in np_deps: prev_end = word.left_edge.i yield word.left_edge.i, extend_right(word), np_label elif word.dep == conj: cc_token = word.left_edge ...
continue
conditional_block
syntax_iterators.py
from typing import Union, Iterator, Tuple from ...tokens import Doc, Span from ...symbols import NOUN, PROPN, PRON from ...errors import Errors def noun_chunks(doclike: Union[Doc, Span]) -> Iterator[Tuple[int, int, int]]: """ Detect base noun phrases from a dependency parse. Works on both Doc and Span. ""...
SYNTAX_ITERATORS = {"noun_chunks": noun_chunks}
# Shave off cc tokens from the NP yield cc_token.right_edge.i + 1, extend_right(word), np_label
random_line_split
syntax_iterators.py
from typing import Union, Iterator, Tuple from ...tokens import Doc, Span from ...symbols import NOUN, PROPN, PRON from ...errors import Errors def noun_chunks(doclike: Union[Doc, Span]) -> Iterator[Tuple[int, int, int]]:
flat = doc.vocab.strings.add("flat") np_label = doc.vocab.strings.add("NP") def extend_right(w): # Playing a trick for flat rindex = w.i + 1 for rdep in doc[w.i].rights: # Extend the span to right if there is a flat if rdep.dep == flat and rdep.pos in (NOUN, PROPN): ...
""" Detect base noun phrases from a dependency parse. Works on both Doc and Span. """ # Please see documentation for Turkish NP structure labels = [ "nsubj", "iobj", "obj", "obl", "appos", "orphan", "dislocated", "ROOT", ] doc = doc...
identifier_body
syntax_iterators.py
from typing import Union, Iterator, Tuple from ...tokens import Doc, Span from ...symbols import NOUN, PROPN, PRON from ...errors import Errors def
(doclike: Union[Doc, Span]) -> Iterator[Tuple[int, int, int]]: """ Detect base noun phrases from a dependency parse. Works on both Doc and Span. """ # Please see documentation for Turkish NP structure labels = [ "nsubj", "iobj", "obj", "obl", "appos", ...
noun_chunks
identifier_name
login.js
"use strict"; angular.module('frsApp.login', ['firebase.utils', 'firebase.auth', 'ngRoute', 'frsApp.countries']) .controller('LoginCtrl', ['$scope', 'Auth', '$location', 'fbutil', 'APPNAME', 'CountryService', function($scope, Auth, $location, fbutil, APPNAME, countries) { $scope.email = null; $sc...
else if ($scope.createMode && $scope.pass !== $scope.confirm) { $scope.err = 'Passwords do not match'; } return !$scope.err; } function errMessage(err) { return angular.isObject(err) && err.code ? err.code : err + ''; } function firs...
{ $scope.err = 'Please enter a password'; }
conditional_block
login.js
"use strict"; angular.module('frsApp.login', ['firebase.utils', 'firebase.auth', 'ngRoute', 'frsApp.countries']) .controller('LoginCtrl', ['$scope', 'Auth', '$location', 'fbutil', 'APPNAME', 'CountryService', function($scope, Auth, $location, fbutil, APPNAME, countries) { $scope.email = null; $sc...
(email) { return ucfirst(email.substr(0, email.indexOf('@')) || ''); } function ucfirst(str) { // inspired by: http://kevin.vanzonneveld.net str += ''; var f = str.charAt(0).toUpperCase(); return f + str.substr(1); } }]) .config(['$r...
firstPartOfEmail
identifier_name
login.js
"use strict"; angular.module('frsApp.login', ['firebase.utils', 'firebase.auth', 'ngRoute', 'frsApp.countries']) .controller('LoginCtrl', ['$scope', 'Auth', '$location', 'fbutil', 'APPNAME', 'CountryService', function($scope, Auth, $location, fbutil, APPNAME, countries) { $scope.email = null; $sc...
$scope.createAccount = function() { $scope.err = null; var email = $scope.email; var pass = $scope.pass; // create user credentials in Firebase auth system Auth.$createUser({ email: email, password: pass }) ....
random_line_split
login.js
"use strict"; angular.module('frsApp.login', ['firebase.utils', 'firebase.auth', 'ngRoute', 'frsApp.countries']) .controller('LoginCtrl', ['$scope', 'Auth', '$location', 'fbutil', 'APPNAME', 'CountryService', function($scope, Auth, $location, fbutil, APPNAME, countries) { $scope.email = null; $sc...
function firstPartOfEmail(email) { return ucfirst(email.substr(0, email.indexOf('@')) || ''); } function ucfirst(str) { // inspired by: http://kevin.vanzonneveld.net str += ''; var f = str.charAt(0).toUpperCase(); return f + str.substr(1); ...
{ return angular.isObject(err) && err.code ? err.code : err + ''; }
identifier_body
test_002_board_class.py
import code import unittest import os import pcbnew import pdb import tempfile from pcbnew import * class TestBoardClass(unittest.TestCase): def setUp(self): self.pcb = LoadBoard("data/complex_hierarchy.kicad_pcb") self.TITLE="Test Board" self.COMMENT1="For load/save test" self.F...
(self): pcb = BOARD() pcb.GetTitleBlock().SetTitle(self.TITLE) pcb.GetTitleBlock().SetComment1(self.COMMENT1) result = SaveBoard(self.FILENAME,pcb) self.assertTrue(result) pcb2 = LoadBoard(self.FILENAME) self.assertNotEqual(pcb2,None) tb = pcb2.G...
test_pcb_save_and_load
identifier_name
test_002_board_class.py
import code import unittest import os import pcbnew import pdb import tempfile from pcbnew import * class TestBoardClass(unittest.TestCase): def setUp(self): self.pcb = LoadBoard("data/complex_hierarchy.kicad_pcb") self.TITLE="Test Board" self.COMMENT1="For load/save test" self.F...
def test_pcb_bounding_box(self): pcb = BOARD() track = TRACK(pcb) pcb.Add(track) #track.SetStartEnd(wxPointMM(10.0, 10.0), # wxPointMM(20.0, 30.0)) track.SetStart(wxPointMM(10.0, 10.0)) track.SetEnd(wxPointMM(20.0, 30.0)) ...
pcb = BOARD() self.assertEqual(pcb.GetNumSegmTrack(),0) track0 = TRACK(pcb) pcb.Add(track0) self.assertEqual(pcb.GetNumSegmTrack(),1) track1 = TRACK(pcb) pcb.Add(track1) self.assertEqual(pcb.GetNumSegmTrack(),2)
identifier_body
test_002_board_class.py
import code import unittest import os import pcbnew import pdb import tempfile from pcbnew import * class TestBoardClass(unittest.TestCase): def setUp(self): self.pcb = LoadBoard("data/complex_hierarchy.kicad_pcb") self.TITLE="Test Board" self.COMMENT1="For load/save test" self.F...
unittest.main()
conditional_block
test_002_board_class.py
import code import unittest import os import pcbnew import pdb import tempfile from pcbnew import * class TestBoardClass(unittest.TestCase): def setUp(self): self.pcb = LoadBoard("data/complex_hierarchy.kicad_pcb") self.TITLE="Test Board" self.COMMENT1="For load/save test" self.F...
pad.SetPosition(wxPointMM(0,0)) # easy case p1 = pcb.GetPad(wxPointMM(0,0)) # top side p2 = pcb.GetPad(wxPointMM(0.9,0.0)) # bottom side p3 = pcb.GetPad(wxPointMM(0,1.4)) # TODO: get pad == p1 evaluated as true instead # of relyin...
module.Add(pad) pad.SetShape(PAD_OVAL) pad.SetSize(wxSizeMM(2.0, 3.0))
random_line_split
codemirror.component.ts
*/ updateValue(value) { this.value = value; this.onTouched(); this.change.emit(value); } /** * Implements ControlValueAccessor */ writeValue(value) { this._value = value || ''; if (this.instance) { this.instance.setValue(this._value); } } onChange(_) { } onTouc...
(/\s{1,}/g, ' ') .replace(/ AND /ig, '~::~' + tab + tab + 'AND ') .replace(/ BETWEEN /ig, '~::~' + tab + 'BETWEEN ') .replace(/ CASE /ig, '~::~' + 'CASE ') .replace(/ ELSE /ig, '~::~' + 'ELSE ') .replace(/ END /ig, '~::~' + 'END
tr.replace
identifier_name
codemirror.component.ts
*/ updateValue(value) { this.value = value; this.onTouched(); this.change.emit(value); } /** * Implements ControlValueAccessor */ writeValue(value) { this._value = value || ''; if (this.instance) { this.instance.setValue(this._value); } } onChange(_) { } onTouc...
private split_sql(str, tab) { return str.replace(/\s{1,}/g, ' ') .replace(/ AND /ig, '~::~' + tab + tab + 'AND ') .replace(/ BETWEEN /ig, '~::~' + tab + 'BETWEEN ') .replace(/ CASE /ig, '~::~' + 'CASE ') .replace(/ ELSE /ig, '~::~' + 'ELSE ') .replace(/ END /ig, '~::~' + '
private isSubquery(str, parenthesisLevel) { return parenthesisLevel - (str.replace(/\(/g, '').length - str.replace(/\)/g, '').length) }
random_line_split
codemirror.component.ts
*/ updateValue(value) { this.value = value; this.onTouched(); this.change.emit(value); } /** * Implements ControlValueAccessor */ writeValue(value) { this._value = value || ''; if (this.instance) { this.instance.setValue(this._value); } } onChange(_) { } onTouc...
if (qend === -1) { // 뒤로 조회 let cnt = 0; for (let j = crow; j >= 0; j = j - 1) { if (lines[j].text.indexOf(';') > -1 && cnt === 0) { // ; 있으면 qend = j; } if (lines[j].text.indexOf(';') > -1 && cnt === 1) { ...
ce.doc.setSelection({ch: 0, line: qstart + 1}, {ch: 0, line: qend + 1}); } break; } // 없다면.
conditional_block
codemirror.component.ts
string = this.instance.doc.getRange({line: 0, ch: 0}, {line: range.from.line, ch: range.from.ch}) const afterText: string = this.instance.doc.getRange({line: range.to.line, ch: range.to.ch}, { line: lines.length, ch: 0 }) text = beforeText + text + afterText; this.writeValue(text); this...
0; const tab = step; // +this.step, let parenthesisLevel = 0; let str = ''; let ix = 0; const shift = step ? that.createShiftArr(step) : undefined; for (ix = 0; ix < len; ix++) { if (ix % 2) { ar = ar.concat(arByQuote[ix]); } else { ar = ar.concat(that.split_sql(arB...
identifier_body
analysis_DropTest.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.cm fig = plt.figure() ax = {} ax["DropOut"] = fig.add_subplot(121) ax["NoDropOut"] = fig.add_subplot(122) dList = {} dList["DropOut"] = ["DropOut1","DropOut2","DropOut3"] dList["NoDropOut"] = ["NoDropOut1","NoDropOut2"] d...
plt.show()
myPlot(ax[k],dList[k])
conditional_block
analysis_DropTest.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.cm fig = plt.figure() ax = {} ax["DropOut"] = fig.add_subplot(121) ax["NoDropOut"] = fig.add_subplot(122) dList = {} dList["DropOut"] = ["DropOut1","DropOut2","DropOut3"] dList["NoDropOut"] = ["NoDropOut1","NoDropOut2"] d...
for k in dList: myPlot(ax[k],dList[k]) plt.show()
cList = ["black","blue","red","green","cyan"] for i,dfile in enumerate(dName): print dfile d = pd.read_csv("Output_DropTest/%s/output.dat"%dfile) dTrain = d[d["mode"]=="Train"] dTest = d[d["mode"]=="Test" ] ax.plot(dTrain.epoch, dTrain.accuracy*100., lineStyle="-" , color=cL...
identifier_body
analysis_DropTest.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.cm fig = plt.figure() ax = {} ax["DropOut"] = fig.add_subplot(121)
def myPlot(ax,dName): cList = ["black","blue","red","green","cyan"] for i,dfile in enumerate(dName): print dfile d = pd.read_csv("Output_DropTest/%s/output.dat"%dfile) dTrain = d[d["mode"]=="Train"] dTest = d[d["mode"]=="Test" ] ax.plot(dTrain.epoch, dTrain.accuracy*100...
ax["NoDropOut"] = fig.add_subplot(122) dList = {} dList["DropOut"] = ["DropOut1","DropOut2","DropOut3"] dList["NoDropOut"] = ["NoDropOut1","NoDropOut2"]
random_line_split
analysis_DropTest.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.cm fig = plt.figure() ax = {} ax["DropOut"] = fig.add_subplot(121) ax["NoDropOut"] = fig.add_subplot(122) dList = {} dList["DropOut"] = ["DropOut1","DropOut2","DropOut3"] dList["NoDropOut"] = ["NoDropOut1","NoDropOut2"] d...
(ax,dName): cList = ["black","blue","red","green","cyan"] for i,dfile in enumerate(dName): print dfile d = pd.read_csv("Output_DropTest/%s/output.dat"%dfile) dTrain = d[d["mode"]=="Train"] dTest = d[d["mode"]=="Test" ] ax.plot(dTrain.epoch, dTrain.accuracy*100., lineStyl...
myPlot
identifier_name
about_iteration.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) fib = 0 for num in it: fib += num self.assertEqual(__ , fib) def test_iter...
self.assertEqual(__, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(__, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test...
random_line_split
about_iteration.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) fib = 0 for num in it: fib += num self.assertEqual(__ , fib) def test_iter...
# ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce(...
def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' se...
identifier_body
about_iteration.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) fib = 0 for num in it:
self.assertEqual(__ , fib) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual(__, next(stages)) next(stages) self.assertEqual(__, next(stages)) next(stages) except StopItera...
fib += num
conditional_block
about_iteration.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) fib = 0 for num in it: fib += num self.assertEqual(__ , fib) def test_iter...
(self): # Ranges are an iteratable sequence result = map(self.add_ten, range(1,4)) self.assertEqual(__, list(result)) try: # Files act like a collection of lines file = open("example_file.txt") def make_upcase(line): return line.s...
test_all_iteration_methods_work_on_any_sequence_not_just_lists
identifier_name
font_metrics.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/. */ //! Access to font metrics from the style system. #![deny(missing_docs)] use Atom; use app_units::Au; use euclid...
{ /// The x-height of the font. pub x_height: Au, /// The zero advance. pub zero_advance_measure: Size2D<Au>, } /// The result for querying font metrics for a given font family. #[derive(Debug, PartialEq, Clone)] pub enum FontMetricsQueryResult { /// The font is available, but we may or may not ha...
FontMetrics
identifier_name
font_metrics.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/. */ //! Access to font metrics from the style system. #![deny(missing_docs)] use Atom; use app_units::Au; use euclid...
/// A trait used to represent something capable of providing us font metrics. pub trait FontMetricsProvider: Send + Sync + fmt::Debug { /// Obtain the metrics for given font family. /// /// TODO: We could make this take the full list, I guess, and save a few /// virtual calls in the case we are repeated...
}
random_line_split
TestPitchRollCoupling.py
from LogAnalyzer import Test,TestResult import DataflashLog from VehicleType import VehicleType import collections class TestPitchRollCoupling(Test):
if not "CTUN" in logdata.channels: self.result.status = TestResult.StatusType.UNKNOWN self.result.statusMessage = "No CTUN log data" return if "BarAlt" in logdata.channels['CTUN']: self.ctun_baralt_att = 'BarAlt' else: self.ctun_baral...
'''test for divergence between input and output pitch/roll, i.e. mechanical failure or bad PID tuning''' # TODO: currently we're only checking for roll/pitch outside of max lean angle, will come back later to analyze roll/pitch in versus out values def __init__(self): Test.__init__(self) self.n...
identifier_body
TestPitchRollCoupling.py
from LogAnalyzer import Test,TestResult import DataflashLog from VehicleType import VehicleType import collections class TestPitchRollCoupling(Test): '''test for divergence between input and output pitch/roll, i.e. mechanical failure or bad PID tuning''' # TODO: currently we're only checking for roll/pitch o...
(self): Test.__init__(self) self.name = "Pitch/Roll" self.enable = True # TEMP def run(self, logdata, verbose): self.result = TestResult() self.result.status = TestResult.StatusType.GOOD if logdata.vehicleType != VehicleType.Copter: self.result.status ...
__init__
identifier_name
TestPitchRollCoupling.py
from LogAnalyzer import Test,TestResult import DataflashLog from VehicleType import VehicleType import collections class TestPitchRollCoupling(Test): '''test for divergence between input and output pitch/roll, i.e. mechanical failure or bad PID tuning''' # TODO: currently we're only checking for roll/pitch o...
# ignore data from these modes: ignoreModes = ["ACRO", "SPORT", "FLIP", "AUTOTUNE","", "THROW",] autoSegments = [] # list of (startLine,endLine) pairs manualSegments = [] # list of (startLine,endLine) pairs orderedModes = collections.OrderedDict(sorted(logdata.modeChanges.ite...
# use CTUN RollIn/DesRoll + PitchIn/DesPitch manualModes = ["STABILIZE", "DRIFT", "ALTHOLD", "ALT_HOLD", "POSHOLD"]
random_line_split
TestPitchRollCoupling.py
from LogAnalyzer import Test,TestResult import DataflashLog from VehicleType import VehicleType import collections class TestPitchRollCoupling(Test): '''test for divergence between input and output pitch/roll, i.e. mechanical failure or bad PID tuning''' # TODO: currently we're only checking for roll/pitch o...
elif mode in ignoreModes: if isAuto: autoSegments.append((prevLine,line-1)) else: manualSegments.append((prevLine,line-1)) prevLine = 0 else: raise Exception("Unknown mode in TestPitchRollCou...
if isAuto: autoSegments.append((prevLine,line-1)) prevLine = line isAuto = False
conditional_block
workqueue.rs
: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>), /// Arbitrary data. pub data: WorkData, } /// Messages from the supervisor to the worker. enum
<QueueData: 'static, WorkData: 'static + Send> { /// Tells the worker to start work. Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData), /// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`. Stop, /// Tells the worker to measure the heap siz...
WorkerMsg
identifier_name
workqueue.rs
: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>), /// Arbitrary data. pub data: WorkData, } /// Messages from the supervisor to the worker. enum WorkerMsg<QueueData: 'static, WorkData: 'static + Send> { /// Tells the worker to start work. Start(Worker<WorkUnit<QueueData, WorkData>>, ...
} } sleep_microseconds(back_off_sleep); back_off_sleep += BACKOFF_INCREMENT_IN_US; i = 0 } else { ...
Ok(WorkerMsg::Exit) => return, Ok(_) => panic!("unexpected message"), _ => {}
random_line_split
session.ts
/** * 用户相关session操作模块
import Router from 'koa-router'; import { proxyImageObj } from '../../utils/common'; import { getDateAfterSeconds } from '../../utils/date'; /** * 设置session * * @param {Router.IRouterContext} ctx 上下文 * @param {Record<string, any>} userResp 请求结果 * @returns */ export function setUserSession( ctx: Router.IRouterC...
* @author VenDream * @since 2018-8-20 */
random_line_split
session.ts
/** * 用户相关session操作模块 * @author VenDream * @since 2018-8-20 */ import Router from 'koa-router'; import { proxyImageObj } from '../../utils/common'; import { getDateAfterSeconds } from '../../utils/date'; /** * 设置session * * @param {Router.IRouterContext} ctx 上下文 * @param {Record<string, any>} userResp 请求结果 *...
on; // 清除session delete session.user; delete session.accessToken; delete session.refreshToken; return true; }
sion as AppSessi
identifier_name
session.ts
/** * 用户相关session操作模块 * @author VenDream * @since 2018-8-20 */ import Router from 'koa-router'; import { proxyImageObj } from '../../utils/common'; import { getDateAfterSeconds } from '../../utils/date'; /** * 设置session * * @param {Router.IRouterContext} ctx 上下文 * @param {Record<string, any>} userResp 请求结果 *...
* 清除session * * @param {Router.IRouterContext} ctx 上下 文 */ export function clearUserSession(ctx: Router.IRouterContext) { const session = ctx.session as AppSession; // 清除session delete session.user; delete session.accessToken; delete session.refreshToken; return true; }
UserModel; if (user) { const session = ctx.session as AppSession; // 头像图片反向代理 proxyImageObj(user.profileImageUrls); // 设置用户相关session session.user = user; session.accessToken = userResp.accessToken; session.refreshToken = { value: userResp.refreshToken, expiredAt: getDateAfterS...
identifier_body
session.ts
/** * 用户相关session操作模块 * @author VenDream * @since 2018-8-20 */ import Router from 'koa-router'; import { proxyImageObj } from '../../utils/common'; import { getDateAfterSeconds } from '../../utils/date'; /** * 设置session * * @param {Router.IRouterContext} ctx 上下文 * @param {Record<string, any>} userResp 请求结果 *...
* @param {Router.IRou terContext} ctx 上下文 */ export function clearUserSession(ctx: Router.IRouterContext) { const session = ctx.session as AppSession; // 清除session delete session.user; delete session.accessToken; delete session.refreshToken; return true; }
as AppSession; // 头像图片反向代理 proxyImageObj(user.profileImageUrls); // 设置用户相关session session.user = user; session.accessToken = userResp.accessToken; session.refreshToken = { value: userResp.refreshToken, expiredAt: getDateAfterSeconds(userResp.expiresIn), }; return true; } ...
conditional_block
Diamond.py
import numpy as np from bokeh.models import ColumnDataSource, Plot, LinearAxis, Grid from bokeh.models.markers import Diamond from bokeh.io import curdoc, show N = 9 x = np.linspace(-2, 2, N) y = x**2 sizes = np.linspace(10, 20, N) source = ColumnDataSource(dict(x=x, y=y, sizes=sizes)) plot = Plot( title=None, ...
plot.add_glyph(source, glyph) xaxis = LinearAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) curdoc().add_root(plot) show(plot)
h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None) glyph = Diamond(x="x", y="y", size="sizes", line_color="#1c9099", line_width=2, fill_color=None)
random_line_split
bracket.py
# Copyright 2011 Nicholas Bray # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
def concat(self, other): # Join the lists self.root.prev.next = other.root.next other.root.next.prev = self.root.prev # Connect the end of the new list too the root. self.root.prev = other.root.prev other.root.prev.next = self.root self.__size += other.__size # Reset the other root. other.root.n...
yield current current = current.prev
conditional_block
bracket.py
# Copyright 2011 Nicholas Bray # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
self.root.prev = other.root.prev other.root.prev.next = self.root self.__size += other.__size # Reset the other root. other.root.next = other.root other.root.prev = other.root other.__size = 0
# Join the lists self.root.prev.next = other.root.next other.root.next.prev = self.root.prev # Connect the end of the new list too the root.
random_line_split
bracket.py
# Copyright 2011 Nicholas Bray # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
(self, other): assert other.isOrphaned() other.prev = self other.next = self.next self.next.prev = other self.next = other def isOrphaned(self): return self.prev == None and self.next == None def __repr__(self): return "Bracket(%r)" % self.data class BracketList(object): def __init__(self): sel...
insertAfter
identifier_name
bracket.py
# Copyright 2011 Nicholas Bray # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
def delete(self): assert not self.isOrphaned() self.prev.next = self.next self.next.prev = self.prev self.prev = None self.next = None def insertAfter(self, other): assert other.isOrphaned() other.prev = self other.next = self.next self.next.prev = other self.next = other def isOrphaned...
self.data = data self.prev = None self.next = None
identifier_body
server.js
process.env.NODE_ENV = process.env.NODE_ENV || 'development' let express = require('express'); let path = require('path'); let favicon = require('serve-favicon'); let logger = require('morgan'); let cookieParser = require('cookie-parser'); let bodyParser = require('body-parser'); let compression = require('compression...
// production error handler // no stacktraces leaked to user server.use((err, req, res, next) => { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = server;
{ server.use((err, req, res, next) => { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); }
conditional_block
server.js
process.env.NODE_ENV = process.env.NODE_ENV || 'development' let express = require('express'); let path = require('path'); let favicon = require('serve-favicon'); let logger = require('morgan'); let cookieParser = require('cookie-parser'); let bodyParser = require('body-parser'); let compression = require('compression...
server.use(logger('dev')); server.use(bodyParser.json()); server.use(bodyParser.urlencoded({ extended: false })); server.use(cookieParser()); server.use(express.static(path.join(__dirname, 'public'))); server.use(compression()) // express-sessions setup server.use(session({ secret: 'blueberry pie', resave: false, ...
// uncomment after placing your favicon in /public //server.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
random_line_split
ShowRoute.js
import React from 'react'; import Helmet from 'react-helmet'; import { Route } from '../../core/router'; import { Model as Waste } from '../../entities/Waste'; import { Deferred } from '../../util/utils'; import NavLink from '../../components/NavLink'; import Progress from 'react-progress-2'; import { PageHeader, Row, ...
extends Route { breadcrumb({ params }) { const dfd = new Deferred; const waste = new Waste({ fid: params.wfid }); waste.forSubjectParam(params.fid); waste.fetch({ success: m => dfd.resolve(m.get('title')) }); return dfd.promise; } fetch({ params }) { this.companyFid = params.fid; th...
WasteShowRoute
identifier_name
ShowRoute.js
import React from 'react'; import Helmet from 'react-helmet'; import { Route } from '../../core/router'; import { Model as Waste } from '../../entities/Waste'; import { Deferred } from '../../util/utils'; import NavLink from '../../components/NavLink'; import Progress from 'react-progress-2'; import { PageHeader, Row, ...
}
random_line_split
ShowRoute.js
import React from 'react'; import Helmet from 'react-helmet'; import { Route } from '../../core/router'; import { Model as Waste } from '../../entities/Waste'; import { Deferred } from '../../util/utils'; import NavLink from '../../components/NavLink'; import Progress from 'react-progress-2'; import { PageHeader, Row, ...
render() { const waste = this.waste.toJSON(); return ( <div> <Helmet title={waste.title} /> <PageHeader>{waste.title}</PageHeader> <Row> <Col md={12}> <ul className="nav menu-nav-pills"> <li> <NavLink to={`/...
{ this.companyFid = params.fid; this.waste = new Waste({ fid: params.wfid }); this.waste.forSubjectParam(params.fid).expandParam('subtype'); return this.waste.fetch(); }
identifier_body
poll.rs
use std::fmt; use error::MioResult; use io::IoHandle; use os; use os::token::Token; use os::event; pub struct Poll { selector: os::Selector, events: os::Events } impl Poll { pub fn new() -> MioResult<Poll> { Ok(Poll { selector: try!(os::Selector::new()), events: os::Events:...
} pub struct EventsIterator<'a> { events: &'a os::Events, index: usize } impl<'a> Iterator for EventsIterator<'a> { type Item = event::IoEvent; fn next(&mut self) -> Option<event::IoEvent> { if self.index == self.events.len() { None } else { self.index += 1; ...
{ write!(fmt, "Poll") }
identifier_body
poll.rs
use std::fmt; use error::MioResult; use io::IoHandle; use os; use os::token::Token; use os::event; pub struct Poll { selector: os::Selector, events: os::Events } impl Poll { pub fn
() -> MioResult<Poll> { Ok(Poll { selector: try!(os::Selector::new()), events: os::Events::new() }) } pub fn register<H: IoHandle>(&mut self, io: &H, token: Token, interest: event::Interest, opts: event::PollOpt) -> MioResult<()> { debug!("registering with polle...
new
identifier_name
poll.rs
use std::fmt; use error::MioResult;
use os::event; pub struct Poll { selector: os::Selector, events: os::Events } impl Poll { pub fn new() -> MioResult<Poll> { Ok(Poll { selector: try!(os::Selector::new()), events: os::Events::new() }) } pub fn register<H: IoHandle>(&mut self, io: &H, token: ...
use io::IoHandle; use os; use os::token::Token;
random_line_split
poll.rs
use std::fmt; use error::MioResult; use io::IoHandle; use os; use os::token::Token; use os::event; pub struct Poll { selector: os::Selector, events: os::Events } impl Poll { pub fn new() -> MioResult<Poll> { Ok(Poll { selector: try!(os::Selector::new()), events: os::Events:...
else { self.index += 1; Some(self.events.get(self.index - 1)) } } }
{ None }
conditional_block
plot.py
import locale import sys from matplotlib import pylab as plt from scipy.interpolate import interp1d import numpy def parse_pRDF(f): pRDFs={} count=0 for line in open(f).readlines(): words=line.split() if words[0]=="dstep":
elif words[0]=="nstep": nstep=locale.atof(words[1]) continue else: atom_type = words[0] pRDF=[] for word in words[1:]: pRDF.append(locale.atof(word)) pRDFs[atom_type]=pRDF return (pRDFs,dstep) f=sys.argv[1] (pRDFs, dstep)=parse_pRDF(f) colors={"C":"k", "HC":"r", "N":"b", "HN":"g", "O":"m",...
dstep=locale.atof(words[1]) continue
conditional_block
plot.py
import locale import sys from matplotlib import pylab as plt from scipy.interpolate import interp1d import numpy def parse_pRDF(f): pRDFs={}
count=0 for line in open(f).readlines(): words=line.split() if words[0]=="dstep": dstep=locale.atof(words[1]) continue elif words[0]=="nstep": nstep=locale.atof(words[1]) continue else: atom_type = words[0] pRDF=[] for word in words[1:]: pRDF.append(locale.atof(word)) pRDFs[atom_ty...
random_line_split
plot.py
import locale import sys from matplotlib import pylab as plt from scipy.interpolate import interp1d import numpy def parse_pRDF(f):
f=sys.argv[1] (pRDFs, dstep)=parse_pRDF(f) colors={"C":"k", "HC":"r", "N":"b", "HN":"g", "O":"m", "HO":"y", "S":"c"} X = numpy.linspace(0, 10+dstep, int(10/dstep)+1) scale=3 Xf = numpy.linspace(0, 10+dstep, (int(10/dstep)+1)*scale) for atom_type, pRDF in pRDFs.iteritems(): Y=numpy.array(pRDF) #f = interp1d(X,Y,kin...
pRDFs={} count=0 for line in open(f).readlines(): words=line.split() if words[0]=="dstep": dstep=locale.atof(words[1]) continue elif words[0]=="nstep": nstep=locale.atof(words[1]) continue else: atom_type = words[0] pRDF=[] for word in words[1:]: pRDF.append(locale.atof(word)) pRDF...
identifier_body
plot.py
import locale import sys from matplotlib import pylab as plt from scipy.interpolate import interp1d import numpy def
(f): pRDFs={} count=0 for line in open(f).readlines(): words=line.split() if words[0]=="dstep": dstep=locale.atof(words[1]) continue elif words[0]=="nstep": nstep=locale.atof(words[1]) continue else: atom_type = words[0] pRDF=[] for word in words[1:]: pRDF.append(locale.atof(word)) ...
parse_pRDF
identifier_name
mod.rs
//! Contains all of the currently completed standard bots/searchers/AIs. //! //! These are mostly for example purposes, to see how one can create a chess AI. extern crate rand; pub mod minimax; pub mod parallel_minimax; pub mod alphabeta; pub mod jamboree; pub mod iterative_parallel_mvv_lva; use core::piece_move::*;...
(board: Board, _depth: u16) -> BitMove { let moves = board.generate_moves(); moves[rand::random::<usize>() % moves.len()] } } impl Searcher for AlphaBetaSearcher { fn name() -> &'static str { "AlphaBeta Searcher" } fn best_move(board: Board, depth: u16) -> BitMove { let...
best_move
identifier_name