file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
client.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import uuid import socket import time __appname__ = "pymessage" __author__ = "Marco Sirabella, Owen Davies" __copyright__ = "" __credits__ = "Marco Sirabella, Owen Davies" __license__ = "new BSD 3-Clause" __version__ = "0.0.3" __maintainers__ = "Ma...
print('received message: {}'.format(fullmsg)) sock.close() connect()
msg = sock.recv(16).decode() # low byte count for whatever reason #print('mes rec: {}'.format(msg)) fullmsg += msg
conditional_block
updater.py
# Copyright (c) 2010-2011 OpenStack, LLC. # # 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 ...
Perform the object update to the container :param node: node dictionary from the container ring :param part: partition that holds the container :param op: operation performed (ex: 'POST' or 'DELETE') :param obj: object name being updated :param headers: headers to send w...
update['successes'] = successes write_pickle(update, update_path, os.path.join(device, 'tmp')) def object_update(self, node, part, op, obj, headers): """
random_line_split
updater.py
# Copyright (c) 2010-2011 OpenStack, LLC. # # 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 ...
else: self.failures += 1 self.logger.debug(_('Update failed for %(obj)s %(path)s'), {'obj': obj, 'path': update_path}) update['successes'] = successes write_pickle(update, update_path, os.path.join(device, 'tmp')) def object_update(self, node...
self.successes += 1 self.logger.debug(_('Update sent for %(obj)s %(path)s'), {'obj': obj, 'path': update_path}) os.unlink(update_path)
conditional_block
updater.py
# Copyright (c) 2010-2011 OpenStack, LLC. # # 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 ...
(self, update_path, device): """ Process the object information to be updated and update. :param update_path: path to pickled object update file :param device: path to device """ try: update = pickle.load(open(update_path, 'rb')) except Exception: ...
process_object_update
identifier_name
updater.py
# Copyright (c) 2010-2011 OpenStack, LLC. # # 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 ...
def run_forever(self, *args, **kwargs): """Run the updater continuously.""" time.sleep(random() * self.interval) while True: self.logger.info(_('Begin object update sweep')) begin = time.time() pids = [] # read from container ring to ensure i...
"""Get the container ring. Load it, if it hasn't been yet.""" if not self.container_ring: self.logger.debug( _('Loading container ring from %s'), self.container_ring_path) self.container_ring = Ring(self.container_ring_path) return self.container_ring
identifier_body
regress-382509.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the Lic...
if (options().match(/werror/)) { options('werror'); } global.foo = eval; global.a = 'global'; expect = 'global indirect'; actual = global.foo('a+" indirect"'); reportCompare(expect, actual, summary + ': global indirect'); object.foo = eval; object.a = 'local'; expect = 'EvalError: funct...
{ options('strict'); }
conditional_block
regress-382509.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the Lic...
() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); if (options().match(/strict/)) { options('strict'); } if (options().match(/werror/)) { options('werror'); } global.foo = eval; global.a = 'global'; expect = 'global indirect'; actual = global.foo('a+" indire...
test
identifier_name
regress-382509.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the Lic...
reportCompare(expect, actual, summary + ': strict, rename warning'); options('strict'); options('werror'); expect = 'No Error'; try { var foo = eval; foo('1+1'); actual = 'No Error'; } catch(ex) { actual = ex + ''; } reportCompare(expect, actual, summary + ': not strict, no renam...
{ actual = ex + ''; }
random_line_split
regress-382509.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the Lic...
{ enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); if (options().match(/strict/)) { options('strict'); } if (options().match(/werror/)) { options('werror'); } global.foo = eval; global.a = 'global'; expect = 'global indirect'; actual = global.foo('a+" indirect"...
identifier_body
glue.rs
// Copyright 2012-2013 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-MI...
<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, size: ValueRef, align: ValueRef, debug_loc: DebugLoc) ->...
trans_exchange_free_dyn
identifier_name
glue.rs
// Copyright 2012-2013 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-MI...
} _ => bcx.sess().bug(&format!("Unexpected unsized type, found {}", t)) } } fn make_drop_glue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, v0: ValueRef, g: DropGlueKind<'tcx>) -> Block<'blk, 'tcx> { let t = g.ty(); let skip_dtor = match g { DropGlueKind::Ty(_) => false,...
let unit_size = llsize_of_alloc(bcx.ccx(), llunit_ty); (Mul(bcx, info, C_uint(bcx.ccx(), unit_size), DebugLoc::None), C_uint(bcx.ccx(), unit_align))
random_line_split
glue.rs
// Copyright 2012-2013 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-MI...
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum DropGlueKind<'tcx> { /// The normal path; runs the dtor, and then recurs on the contents Ty(Ty<'tcx>), /// Skips the dtor, if any, for ty; drops the contents directly. /// Note that the dtor is only skipped at the most *shallow* /// level...
{ get_drop_glue_core(ccx, DropGlueKind::Ty(t)) }
identifier_body
plugins.js
import core from 'core-js'; import * as LogManager from 'aurelia-logging'; import {Metadata} from 'aurelia-metadata'; var logger = LogManager.getLogger('aurelia'); function
(aurelia, loader, info){ logger.debug(`Loading plugin ${info.moduleId}.`); aurelia.currentPluginId = info.moduleId; return loader.loadModule(info.moduleId).then(m => { if('configure' in m){ return Promise.resolve(m.configure(aurelia, info.config || {})).then(() => { aurelia.currentPluginId = nu...
loadPlugin
identifier_name
plugins.js
import core from 'core-js'; import * as LogManager from 'aurelia-logging'; import {Metadata} from 'aurelia-metadata'; var logger = LogManager.getLogger('aurelia'); function loadPlugin(aurelia, loader, info){ logger.debug(`Loading plugin ${info.moduleId}.`); aurelia.currentPluginId = info.moduleId; return loade...
}); } /** * Manages loading and configuring plugins. * * @class Plugins * @constructor * @param {Aurelia} aurelia An instance of Aurelia. */ export class Plugins { constructor(aurelia){ this.aurelia = aurelia; this.info = []; this.processed = false; } /** * Configures a plugin before Aur...
{ aurelia.currentPluginId = null; logger.debug(`Loaded plugin ${info.moduleId}.`); }
conditional_block
plugins.js
import core from 'core-js'; import * as LogManager from 'aurelia-logging'; import {Metadata} from 'aurelia-metadata'; var logger = LogManager.getLogger('aurelia'); function loadPlugin(aurelia, loader, info){ logger.debug(`Loading plugin ${info.moduleId}.`); aurelia.currentPluginId = info.moduleId; return loade...
* @param {config} config The configuration for the specified module. * @return {Plugins} Returns the current Plugins instance. */ plugin(moduleId, config){ var plugin = {moduleId:moduleId, config:config || {}}; if(this.processed){ loadPlugin(this.aurelia, this.aurelia.loader, plugin); }else{...
/** * Configures a plugin before Aurelia starts. * * @method plugin * @param {moduleId} moduleId The ID of the module to configure.
random_line_split
plugins.js
import core from 'core-js'; import * as LogManager from 'aurelia-logging'; import {Metadata} from 'aurelia-metadata'; var logger = LogManager.getLogger('aurelia'); function loadPlugin(aurelia, loader, info){ logger.debug(`Loading plugin ${info.moduleId}.`); aurelia.currentPluginId = info.moduleId; return loade...
_process(){ var aurelia = this.aurelia, loader = aurelia.loader, info = this.info, current; if(this.processed){ return; } var next = () => { if(current = info.shift()){ return loadPlugin(aurelia, loader, current).then(next); } this.processed...
{ var plugin = {moduleId:moduleId, config:config || {}}; if(this.processed){ loadPlugin(this.aurelia, this.aurelia.loader, plugin); }else{ this.info.push(plugin); } return this; }
identifier_body
canvas.js
var DOM = require('../dom'); var utils = require('../utils'); module.exports = (function() { var canvas = DOM.newEl('canvas'); var ctx = null; return function(sceneGraph) { if (ctx == null) { ctx = canvas.getContext('2d'); } var dpr = utils.canvasRatio(); var r...
var textGroup = root.children.holderTextGroup; ctx.font = textGroup.properties.font.weight + ' ' + (dpr * textGroup.properties.font.size) + textGroup.properties.font.units + ' ' + textGroup.properties.font.family + ', monospace'; ctx.fillStyle = textGroup.properties.fill; for (var lin...
{ //todo: abstract this into a method ctx.strokeStyle = bg.properties.outline.fill; ctx.lineWidth = bg.properties.outline.width; ctx.moveTo(outlineOffsetWidth, outlineOffsetWidth); // TL, TR, BR, BL ctx.lineTo(bgWidth - outlineOffsetWidth, outlineO...
conditional_block
canvas.js
var DOM = require('../dom'); var utils = require('../utils'); module.exports = (function() { var canvas = DOM.newEl('canvas'); var ctx = null; return function(sceneGraph) { if (ctx == null) { ctx = canvas.getContext('2d'); } var dpr = utils.canvasRatio(); var r...
ctx.textBaseline = 'middle'; var bg = root.children.holderBg; var bgWidth = dpr * bg.width; var bgHeight = dpr * bg.height; //todo: parametrize outline width (e.g. in scene object) var outlineWidth = 2; var outlineOffsetWidth = outlineWidth / 2; ctx.fill...
random_line_split
IntervalObservable.d.ts
import { Subscriber } from '../Subscriber'; import { IScheduler } from '../Scheduler'; import { Observable } from '../Observable'; /** * We need this JSDoc comment for affecting ESDoc. * @extends {Ignored} * @hide true */ export declare class IntervalObservable extends Observable<number> { private period; p...
* @static true * @name interval * @owner Observable */ static create(period?: number, scheduler?: IScheduler): Observable<number>; static dispatch(state: any): void; constructor(period?: number, scheduler?: IScheduler); protected _subscribe(subscriber: Subscriber<number>): void; }
* @param {Scheduler} [scheduler=async] The IScheduler to use for scheduling * the emission of values, and providing a notion of "time". * @return {Observable} An Observable that emits a sequential number each time * interval.
random_line_split
IntervalObservable.d.ts
import { Subscriber } from '../Subscriber'; import { IScheduler } from '../Scheduler'; import { Observable } from '../Observable'; /** * We need this JSDoc comment for affecting ESDoc. * @extends {Ignored} * @hide true */ export declare class
extends Observable<number> { private period; private scheduler; /** * Creates an Observable that emits sequential numbers every specified * interval of time, on a specified IScheduler. * * <span class="informal">Emits incremental numbers periodically in time. * </span> * ...
IntervalObservable
identifier_name
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
_direct: &[(Address, U256)], _indirect: &[(Address, U256)], ) -> Result<(), Self::Error> { Ok(()) } }
&self, _live: &mut Self::LiveBlock,
random_line_split
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
( &self, _live: &mut Self::LiveBlock, _direct: &[(Address, U256)], _indirect: &[(Address, U256)], ) -> Result<(), Self::Error> { Ok(()) } }
note_rewards
identifier_name
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
}
{ Ok(()) }
identifier_body
test_order.py
# coding: utf-8 """ DeliveryHub DeliveryHub API OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtai...
def tearDown(self): pass def testOrder(self): """ Test Order """ model = swagger_client.models.order.Order() if __name__ == '__main__': unittest.main()
def setUp(self): pass
random_line_split
test_order.py
# coding: utf-8 """ DeliveryHub DeliveryHub API OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtai...
unittest.main()
conditional_block
test_order.py
# coding: utf-8 """ DeliveryHub DeliveryHub API OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtai...
def testOrder(self): """ Test Order """ model = swagger_client.models.order.Order() if __name__ == '__main__': unittest.main()
pass
identifier_body
test_order.py
# coding: utf-8 """ DeliveryHub DeliveryHub API OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtai...
(self): """ Test Order """ model = swagger_client.models.order.Order() if __name__ == '__main__': unittest.main()
testOrder
identifier_name
gcp_spanner_database_facts.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
(): module = GcpModule(argument_spec=dict(instance=dict(required=True))) if not module.params['scopes']: module.params['scopes'] = ['https://www.googleapis.com/auth/spanner.admin'] items = fetch_list(module, collection(module)) if items.get('databases'): items = items.get('databases') ...
main
identifier_name
gcp_spanner_database_facts.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
def fetch_list(module, link): auth = GcpSession(module, 'spanner') response = auth.get(link) return return_if_object(module, response) def return_if_object(module, response): # If not found, return nothing. if response.status_code == 404: return None # If no content, return nothing...
res = {'project': module.params['project'], 'instance': replace_resource_dict(module.params['instance'], 'name')} return "https://spanner.googleapis.com/v1/projects/{project}/instances/{instance}/databases".format(**res)
identifier_body
gcp_spanner_database_facts.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
description: - Gather facts for GCP Database short_description: Gather facts for GCP Database version_added: 2.8 author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: instance: description: - The instance to create the database on. - ...
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_spanner_database_facts
random_line_split
gcp_spanner_database_facts.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
# If no content, return nothing. if response.status_code == 204: return None try: module.raise_for_status(response) result = response.json() except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst: module.fail_json(msg="Invalid JSON response with error: %s"...
return None
conditional_block
config_installer.py
import os from conans.tools import unzip import shutil from conans.util.files import rmdir, mkdir from conans.client.remote_registry import RemoteRegistry from conans import tools from conans.errors import ConanException def
(registry_path, remote_file, output): registry = RemoteRegistry(registry_path, output) new_registry = RemoteRegistry(remote_file, output) registry.define_remotes(new_registry.remotes) def _handle_profiles(source_folder, target_folder, output): mkdir(target_folder) for root, _, files in os.walk(sou...
_handle_remotes
identifier_name
config_installer.py
import os from conans.tools import unzip import shutil from conans.util.files import rmdir, mkdir from conans.client.remote_registry import RemoteRegistry from conans import tools from conans.errors import ConanException def _handle_remotes(registry_path, remote_file, output): registry = RemoteRegistry(registry_p...
tmp_folder = os.path.join(client_cache.conan_folder, "tmp_config_install") # necessary for Mac OSX, where the temp folders in /var/ are symlinks to /private/var/ tmp_folder = os.path.realpath(tmp_folder) mkdir(tmp_folder) try: if item is None: try: item = client_cache...
identifier_body
config_installer.py
import os from conans.tools import unzip import shutil from conans.util.files import rmdir, mkdir from conans.client.remote_registry import RemoteRegistry from conans import tools from conans.errors import ConanException def _handle_remotes(registry_path, remote_file, output): registry = RemoteRegistry(registry_p...
elif item.startswith("http"): _process_download(item, client_cache, output, tmp_folder) else: raise ConanException("I don't know how to process %s" % item) finally: if item: client_cache.conan_config.set_item("general.config_install", item) rmdir(...
_process_zip_file(item, client_cache, output, tmp_folder)
conditional_block
config_installer.py
import os from conans.tools import unzip import shutil from conans.util.files import rmdir, mkdir from conans.client.remote_registry import RemoteRegistry from conans import tools from conans.errors import ConanException def _handle_remotes(registry_path, remote_file, output): registry = RemoteRegistry(registry_p...
settings_path = client_cache.settings_path shutil.copy(os.path.join(root, f), settings_path) elif f == "conan.conf": output.info("Processing conan.conf") conan_conf = client_cache.conan_config _handle_conan_conf(conan_conf, os.p...
for f in files: if f == "settings.yml": output.info("Installing settings.yml")
random_line_split
setup_test.ts
/** * @license * Copyright 2019 Google LLC. All Rights Reserved. * 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 a...
} // Otherwise ignore the test. return false; }; // Import and run all the tests from core. import '@tensorflow/tfjs-core/dist/tests';
{ return true; }
conditional_block
setup_test.ts
/** * @license * Copyright 2019 Google LLC. All Rights Reserved. * 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 a...
const INCLUDE_LIST: string[] = ['add ']; /** Tests that have these substrings in their name will be excluded. */ const EXCLUDE_LIST: string[] = [ 'complex', // Complex numbers not yet implemented. 'gradient', // Gradient is missing. 'broadcast inner dim', // Broadcast i...
/** Tests that have these substrings in their name will be included. */
random_line_split
creatureDB.py
'''A module containing a class for storing Creature objects in a SQLite database.''' import csv import sqlite3 __all__ = ['CreatureDB'] class CreatureDB(object):
def __init__(self, name='creature.db', use_nominal_cr=False): self.min_cr = 0.0 self.max_cr = float('inf') # set flags self.using_nominal_cr = use_nominal_cr # initialize database self.connection = sqlite3.connect(name) self.connection.text_factory = str ...
'''Class for storing Creature objects in a SQLite database.'''
random_line_split
creatureDB.py
'''A module containing a class for storing Creature objects in a SQLite database.''' import csv import sqlite3 __all__ = ['CreatureDB'] class CreatureDB(object): '''Class for storing Creature objects in a SQLite database.''' def __init__(self, name='creature.db', use_nominal_cr=False): self....
# insert creature into database values = self._construct_tuple_insert_values(creature) query = '''insert into creatures ( name,CR, hp,HD, ac,touch_ac,flatfooted_ac, Fort, Ref, Will, ...
return
conditional_block
creatureDB.py
'''A module containing a class for storing Creature objects in a SQLite database.''' import csv import sqlite3 __all__ = ['CreatureDB'] class CreatureDB(object): '''Class for storing Creature objects in a SQLite database.''' def __init__(self, name='creature.db', use_nominal_cr=False): self....
(self, file_name='creature.csv'): '''Exports the data in this object as a .csv file. :param file_name: the name of the output csv file ''' cursor = self.connection.cursor() data = cursor.execute('select * from creatures') # write data to output file csv_f...
export_as_csv
identifier_name
creatureDB.py
'''A module containing a class for storing Creature objects in a SQLite database.''' import csv import sqlite3 __all__ = ['CreatureDB'] class CreatureDB(object): '''Class for storing Creature objects in a SQLite database.''' def __init__(self, name='creature.db', use_nominal_cr=False): self....
def commit_and_close(self): '''Commits any uncommitted changes to the SQLite database and closes the connection ''' self.connection.commit() self.connection.close() def export_as_csv(self, file_name='creature.csv'): '''Exports the data in this object a...
'''Adds a Creature object as a row in the appropriate table of the SQLite database :param creature: a Creature object to be added to the database ''' # check that creature CR is within desired range creature_cr = float(creature.cr) if creature_cr < self.min_cr o...
identifier_body
ErrorObservable.d.ts
import { Scheduler } from '../Scheduler'; import { Observable } from '../Observable'; import { TeardownLogic } from '../Subscription'; export interface DispatchArg { error: any; subscriber: any; } /** * We need this JSDoc comment for affecting ESDoc. * @extends {Ignored} * @hide true */ export declare class...
* var result = interval.mergeMap(x => * x === 13 ? * Rx.Observable.throw('Thirteens are bad') : * Rx.Observable.of('a', 'b', 'c') * ); * result.subscribe(x => console.log(x), e => console.error(e)); * * @see {@link create} * @see {@link empty} * @see {@link ne...
* result.subscribe(x => console.log(x), e => console.error(e)); * * @example <caption>Map and flattens numbers to the sequence 'a', 'b', 'c', but throw an error for 13</caption> * var interval = Rx.Observable.interval(1000);
random_line_split
ErrorObservable.d.ts
import { Scheduler } from '../Scheduler'; import { Observable } from '../Observable'; import { TeardownLogic } from '../Subscription'; export interface DispatchArg { error: any; subscriber: any; } /** * We need this JSDoc comment for affecting ESDoc. * @extends {Ignored} * @hide true */ export declare class...
<T> extends Observable<any> { error: T; private scheduler; /** * Creates an Observable that emits no items to the Observer and immediately * emits an error notification. * * <span class="informal">Just emits 'error', and nothing else. * </span> * * <img src="./img/throw.pn...
ErrorObservable
identifier_name
response.py
""" VerseBot for Reddit By Matthieu Grieger Continued By Team VerseBot response.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ MAXIMUM_MESSAGE_LENGTH = 4000 class Response: """ Class that holds the properties and methods of a comment response. """ def __init__(self, message, parser, link=None)...
self.response += verse.contents self.response += "\n\n" if self.response == "": return None else: if self.exceeds_max_length(): self.response = self.generate_overflow_response() # self.response += self.get_comment_foote...
self.response += ("[**%s %d | %s**](%s)\n\n>" % (verse.book, verse.chapter, verse.translation_title, verse.permalink))
conditional_block
response.py
""" VerseBot for Reddit By Matthieu Grieger Continued By Team VerseBot response.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ MAXIMUM_MESSAGE_LENGTH = 4000 class Response: """ Class that holds the properties and methods of a comment response. """ def __init__(self, message, parser, link=None)...
def generate_overflow_response(self): """ Constructs and generates an overflow comment whenever the comment exceeds the character limit set by MAXIMUM_MESSAGE_LENGTH. Instead of posting the contents of the verse(s) in the comment, it links to webpages that contain the contents of t...
""" Returns true if the current response exceeds the maximum comment length, returns false otherwise. """ return len(self.response) > MAXIMUM_MESSAGE_LENGTH
identifier_body
response.py
""" VerseBot for Reddit By Matthieu Grieger Continued By Team VerseBot response.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ MAXIMUM_MESSAGE_LENGTH = 4000 class Response: """ Class that holds the properties and methods of a comment response. """ def __init__(self, message, parser, link=None)...
return len(self.response) > MAXIMUM_MESSAGE_LENGTH def generate_overflow_response(self): """ Constructs and generates an overflow comment whenever the comment exceeds the character limit set by MAXIMUM_MESSAGE_LENGTH. Instead of posting the contents of the verse(s) in the comment, i...
def exceeds_max_length(self): """ Returns true if the current response exceeds the maximum comment length, returns false otherwise. """
random_line_split
response.py
""" VerseBot for Reddit By Matthieu Grieger Continued By Team VerseBot response.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ MAXIMUM_MESSAGE_LENGTH = 4000 class Response: """ Class that holds the properties and methods of a comment response. """ def __init__(self, message, parser, link=None)...
(self, verse): """ Adds a verse to the verse list. :param verse: Verse to add to the list of verses """ self.verse_list.append(verse) def is_duplicate_verse(self, verse): """ Checks the incoming verse against the verse list to make sure it is not a duplicate. ...
add_verse
identifier_name
index.d.ts
/* * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib Authors. * * 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 ap...
* @example * var v = mean( -0.2 ); * // returns NaN * * @example * var v = mean( NaN ); * // returns NaN */ declare function mean( lambda: number ): number; // EXPORTS // export = mean;
random_line_split
index.js
require('dotenv').config({ silent: true }); var Express = require('express'); var path = require('path'); var fs = require('fs'); var merge = require('lodash/merge'); var proxy = require('proxy-middleware'); var ejs = require('ejs'); var config = require('./config'); var server = new Express(); server.set('port', c...
});
random_line_split
index.js
require('dotenv').config({ silent: true }); var Express = require('express'); var path = require('path'); var fs = require('fs'); var merge = require('lodash/merge'); var proxy = require('proxy-middleware'); var ejs = require('ejs'); var config = require('./config'); var server = new Express(); server.set('port', c...
console.log('Gandalf is started to listen at localhost:' + server.get('port')); });
{ console.log('error while starting server', err); }
conditional_block
index.js
var features = require('./features'); var Rework = require('rework'); /** * Expose `myth`. */ module.exports = exports = myth; /** * Expose `features`. */
* * @param {String} string (optional) * @param {Object} options (optional) * @property {String} source * @property {Array} browsers * @property {Boolean} compress * @property {Object} features * @return {String} */ function myth(string, options){ if ('object' == typeof string) options = string, stri...
exports.features = Object.keys(features); /** * Rework a CSS `string`, or return the Myth rework plugin.
random_line_split
index.js
var features = require('./features'); var Rework = require('rework'); /** * Expose `myth`. */ module.exports = exports = myth; /** * Expose `features`. */ exports.features = Object.keys(features); /** * Rework a CSS `string`, or return the Myth rework plugin. * * @param {String} string (optional) * @param...
(string, options){ if ('object' == typeof string) options = string, string = null; options = options || {}; if ('string' != typeof string) return plugin(options); return Rework(string, options) .use(plugin(options)) .toString(options); } /** * Generate a Myth rework plugin with `options`. * * @par...
myth
identifier_name
index.js
var features = require('./features'); var Rework = require('rework'); /** * Expose `myth`. */ module.exports = exports = myth; /** * Expose `features`. */ exports.features = Object.keys(features); /** * Rework a CSS `string`, or return the Myth rework plugin. * * @param {String} string (optional) * @param...
/** * Generate a Myth rework plugin with `options`. * * @param {Object} options * @return {Function} */ function plugin(options){ return function(stylesheet, rework){ var enabled = options.features || {}; exports.features.forEach(function(key){ if (enabled[key] === false) return; var plugi...
{ if ('object' == typeof string) options = string, string = null; options = options || {}; if ('string' != typeof string) return plugin(options); return Rework(string, options) .use(plugin(options)) .toString(options); }
identifier_body
FetchSimpleFeaturesByTags.ts
import { doRequest, Method } from 'lib/rest/RestRequests'; import FetchSimpleFeaturesByTagsTypes from './generated/FetchSimpleFeaturesByTagsTypes'; import FetchSimpleFeaturesTypes from './generated/FetchSimpleFeaturesTypes'; import Tag from 'models/Tag'; import { createSimpleFeatures, SimpleFeatureResponseData } from '...
} type ResponseData = ResponseDataElement[]; const createTag = (data: ResponseDataElement): Tag => { return { name: data.tag, features: createSimpleFeatures(data.features), }; }; const createTags = (data: ResponseData): Tag[] => { return data.map(item => createTag(item)); }; const fetchSimpleFeaturesBy...
random_line_split
terrain.js
(function(){ function render (context, points) { console.log ('render called'); var angle = 0, center = new Point3D (400,400,400); return function () { context.clearRect(0,0,800,600); if (points.length < 1000) { points.push (randomPoint...
function init() { console.log ('inited'); var viewport = document.getElementById('viewport'), context = viewport.getContext ('2d'), points = []; context.strokeStyle = '#aaa'; context.lineWidth = 1; setInterval (render (context, points...
{ return new Point3D ( randomInt (-100,900), randomInt (-100,900), randomInt (-100,900), 1, randomInt (1,10) ); }
identifier_body
terrain.js
(function(){ function render (context, points) { console.log ('render called'); var angle = 0, center = new Point3D (400,400,400); return function () { context.clearRect(0,0,800,600); if (points.length < 1000) { points.push (randomPoint...
() { return new Point3D ( randomInt (-100,900), randomInt (-100,900), randomInt (-100,900), 1, randomInt (1,10) ); } function init() { console.log ('inited'); var viewport = document.getElementById('viewport'), ...
randomPoint
identifier_name
terrain.js
(function(){ function render (context, points) { console.log ('render called'); var angle = 0, center = new Point3D (400,400,400); return function () { context.clearRect(0,0,800,600); if (points.length < 1000) { points.push (randomPoint...
); angle = angle + 1; } } function randomInt (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function randomPoint () { return new Point3D ( randomInt (-100,900), randomInt (-100,900), randomInt...
context.fill(); }
random_line_split
terrain.js
(function(){ function render (context, points) { console.log ('render called'); var angle = 0, center = new Point3D (400,400,400); return function () { context.clearRect(0,0,800,600); if (points.length < 1000) { points.push (randomPoint...
points.map ( function (pt) { return pt.subtract (center); } ).map ( function (pt) { return y_rotate(pt, angle); } )/*.map ( function (pt) { ret...
{angle = 0;}
conditional_block
mod.rs
//! Traits and datastructures representing a collection trace. //! //! A collection trace is a set of updates of the form `(key, val, time, diff)`, which determine the contents //! of a collection at given times by accumulating updates whose time field is less or equal to the target field. //! //! The `Trace` trait des...
else { panic!("unable to acquire complete cursor for trace; is it closed?"); } } /// Acquires a cursor to the restriction of the collection's contents to updates at times not greater or /// equal to an element of `upper`. /// /// This method is expected to work if called with an `upper` that (i) was an ob...
{ cursor }
conditional_block
mod.rs
//! Traits and datastructures representing a collection trace. //! //! A collection trace is a set of updates of the form `(key, val, time, diff)`, which determine the contents //! of a collection at given times by accumulating updates whose time field is less or equal to the target field. //! //! The `Trace` trait des...
pub struct AbomonatedMerger<K,V,T,R,B:Batch<K,V,T,R>> { merger: B::Merger } /// Represents a merge in progress. impl<K,V,T,R,B:Batch<K,V,T,R>+Abomonation> Merger<K, V, T, R, Abomonated<B,Vec<u8>>> for AbomonatedMerger<K,V,T,R,B> { fn new(source1: &Abomonated<B,Vec<u8>>, source2: &Abomonated<B,Vec<u8>>) -> Self { ...
random_line_split
mod.rs
//! Traits and datastructures representing a collection trace. //! //! A collection trace is a set of updates of the form `(key, val, time, diff)`, which determine the contents //! of a collection at given times by accumulating updates whose time field is less or equal to the target field. //! //! The `Trace` trait des...
(&mut self, target: &mut Antichain<Self::Time>) where Self::Time: Timestamp, { target.clear(); target.insert(Default::default()); self.map_batches(|batch| { target.clear(); for time in batch.upper().iter().cloned() { target.insert(time); } }); } /// Advances `upper` by any empty batches. ...
read_upper
identifier_name
mod.rs
//! Traits and datastructures representing a collection trace. //! //! A collection trace is a set of updates of the form `(key, val, time, diff)`, which determine the contents //! of a collection at given times by accumulating updates whose time field is less or equal to the target field. //! //! The `Trace` trait des...
/// All times in the batch are not greater or equal to any element of `upper`. fn upper(&self) -> &[T] { self.description().upper() } } /// An immutable collection of updates. pub trait Batch<K, V, T, R> : BatchReader<K, V, T, R> where Self: ::std::marker::Sized { /// A type used to assemble batches from disordere...
{ self.description().lower() }
identifier_body
dirname.rs
#![crate_name = "uu_dirname"] /* * This file is part of the uutils coreutils package. * * (c) Derek Chiang <derekchiang93@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; use std::path::Path; sta...
(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("z", "zero", "separate output with NUL rather than newline"); opts.optflag("", "help", "display this help and exit"); opts.optflag("", "version", "output version information and exit"); let matches = match opts.parse(...
uumain
identifier_name
dirname.rs
#![crate_name = "uu_dirname"] /* * This file is part of the uutils coreutils package. * * (c) Derek Chiang <derekchiang93@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; use std::path::Path; sta...
println!("{0}: missing operand", NAME); println!("Try '{0} --help' for more information.", NAME); return 1; } 0 }
} } else {
random_line_split
dirname.rs
#![crate_name = "uu_dirname"] /* * This file is part of the uutils coreutils package. * * (c) Derek Chiang <derekchiang93@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; use std::path::Path; sta...
{ let mut opts = getopts::Options::new(); opts.optflag("z", "zero", "separate output with NUL rather than newline"); opts.optflag("", "help", "display this help and exit"); opts.optflag("", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m)...
identifier_body
models.py
from django.db import models from django.core.urlresolvers import reverse from django.conf import settings import misaka from groups.models import Group # Create your models here. # POSTS MODELS.PY from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.Fo...
(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('posts:single', kwargs={'username': self.user.username, 'pk': self.pk}) class Meta: o...
__str__
identifier_name
models.py
from django.db import models from django.core.urlresolvers import reverse from django.conf import settings import misaka from groups.models import Group # Create your models here. # POSTS MODELS.PY from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.Fo...
ordering = ['-created_at'] unique_together = ['user', 'message']
identifier_body
models.py
from django.db import models from django.core.urlresolvers import reverse from django.conf import settings import misaka from groups.models import Group # Create your models here. # POSTS MODELS.PY from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model):
def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('posts:single', kwargs={'username': self.user.username, 'pk': self.pk}) class...
user = models.ForeignKey(User, related_name='posts') created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name='posts', null=True, blank=True)
random_line_split
error.rs
use common::document::ContainerDocument; use snafu::Snafu; #[derive(Debug, Snafu)] pub enum Error { #[snafu(display("Failed to parse {} document: {}", target_type, source))] Deserialization { target_type: &'static str, source: serde_json::Error, }, #[snafu(display("Document Retrieval Er...
<T: ContainerDocument>(err: serde_json::Error) -> Self { Self::Deserialization { target_type: T::static_doc_type(), source: err, } } }
from_deserialization
identifier_name
error.rs
use common::document::ContainerDocument; use snafu::Snafu; #[derive(Debug, Snafu)] pub enum Error { #[snafu(display("Failed to parse {} document: {}", target_type, source))] Deserialization { target_type: &'static str, source: serde_json::Error, }, #[snafu(display("Document Retrieval Er...
#[snafu(display("Status Error: {}", source))] Status { source: Box<dyn std::error::Error> }, #[snafu(display("Backend Configuration Error: {}", source))] BackendConfiguration { source: Box<dyn std::error::Error> }, } impl Error { pub fn from_deserialization<T: ContainerDocument>(err: serde_json::E...
#[snafu(display("Configuration Error: {}", source))] Configuration { source: config::ConfigError },
random_line_split
main.js
(function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelA...
function handleMouseup(event) { downKeys[UP] = false; downKeys[DOWN] = false; downKeys[LEFT] = false; downKeys[RIGHT] = false; } }());
{ if(event.layerY < HEIGHT / 3) { downKeys[UP] = true; } else if(event.layerY < HEIGHT * 2 / 3) { if(event.layerX < WIDTH/2) { downKeys[LEFT] = true; } else { downKeys[RIGHT] = true; } } else { downKeys[DOWN] = true; } }
identifier_body
main.js
(function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelA...
(event) { downKeys[UP] = false; downKeys[DOWN] = false; downKeys[LEFT] = false; downKeys[RIGHT] = false; } }());
handleMouseup
identifier_name
main.js
(function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelA...
val.sx, val.sy, val.sw, val.sh, val.dx, val.sy, val.dw, val.sh ); */ } } function handleKeydown(event) { var code = event.keyCode - codeOffset; //console.log('keydown: ' + code); switch(code) { case UP: case DOWN: case LEFT: case RIGHT: downKeys[code] =...
groundCanvas,
random_line_split
race.ts
import { tee } from "./tee"; import { pump } from "./pump"; import { createDuplex } from "./duplex"; import { wrapAsyncIterableIterator } from "./wrap-async-iterable-iterator"; /** * Calls all target functions in parallel, and returns the yielded values of the _fastest_ one. * * @example * * const ping = race( ...
lse { output.unshift(value); } }); }).then(() => { if (wonFn === fn) { output.return(); } }); }); }); };
output.return(); } e
conditional_block
race.ts
import { tee } from "./tee";
import { wrapAsyncIterableIterator } from "./wrap-async-iterable-iterator"; /** * Calls all target functions in parallel, and returns the yielded values of the _fastest_ one. * * @example * * const ping = race( * * ); */ export const race = (...fns: Function[]) => (...args): AsyncIterableIterator<any> => ...
import { pump } from "./pump"; import { createDuplex } from "./duplex";
random_line_split
telescope.py
'''Tutorial to demonstrate theia.''' import numpy as np from theia.running import simulation as sim from theia.optics import beam as gbeam from theia.optics import mirror as mir from theia.helpers import settings from theia.helpers.units import * # initialize globals (necessary to use theia in library form) dic = {'i...
# Run simulation. Output of this simulation is intended to be compared # to the output of the telescope.f90 optocad simulation simu.run() if __name__ == "__main__": print(simu) print(simu.BeamTreeList[0].beamList())
simu.Threshold = threshold
random_line_split
telescope.py
'''Tutorial to demonstrate theia.''' import numpy as np from theia.running import simulation as sim from theia.optics import beam as gbeam from theia.optics import mirror as mir from theia.helpers import settings from theia.helpers.units import * # initialize globals (necessary to use theia in library form) dic = {'i...
print(simu) print(simu.BeamTreeList[0].beamList())
conditional_block
module_disk_select_test.py
# # Copyright (C) 2019 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be...
def ignored_disks_property_test(self): """Test the ignored disks property.""" self._test_dbus_property( "IgnoredDisks", ["sda", "sdb"] ) def protected_disks_property_test(self): """Test the protected disks property.""" self._test_dbus_property( ...
"""Test the exclusive disks property.""" self._test_dbus_property( "ExclusiveDisks", ["sda", "sdb"] )
identifier_body
module_disk_select_test.py
# # Copyright (C) 2019 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be...
(self): """Test the GetUsableDisks method.""" with self.assertRaises(UnavailableStorageError): self.disk_selection_interface.GetUsableDisks() self.disk_selection_module.on_storage_changed(create_storage()) self.assertEqual(self.disk_selection_interface.GetUsableDisks(), [])
get_usable_disks_test
identifier_name
module_disk_select_test.py
# # Copyright (C) 2019 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version.
# ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Found...
# This program is distributed in the hope that it will be useful, but WITHOUT
random_line_split
client.py
# - coding: utf-8 - # Copyright (C) 2007 Patryk Zawadzki <patrys at pld-linux.org> # Copyright (C) 2007-2009 Toms Baugis <toms.baugis@gmail.com> # This file is part of Project Hamster. # Project Hamster is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as ...
def get_activity_by_name(self, activity, category_id = None, resurrect = True): """returns activity dict by name and optionally filtering by category. if activity is found but is marked as deleted, it will be resurrected unless told otherwise in the resurrect param """ ...
def get_category_id(self, category_name): """returns category id by name""" return self.conn.GetCategoryId(category_name)
random_line_split
client.py
# - coding: utf-8 - # Copyright (C) 2007 Patryk Zawadzki <patrys at pld-linux.org> # Copyright (C) 2007-2009 Toms Baugis <toms.baugis@gmail.com> # This file is part of Project Hamster. # Project Hamster is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as ...
new_id = self.conn.AddFact(serialized, start_timestamp, end_timestamp, temporary_activity) # TODO - the parsing should happen just once and preferably here # we should feed (serialized_act...
end_timestamp = timegm(end_timestamp.timetuple())
conditional_block
client.py
# - coding: utf-8 - # Copyright (C) 2007 Patryk Zawadzki <patrys at pld-linux.org> # Copyright (C) 2007-2009 Toms Baugis <toms.baugis@gmail.com> # This file is part of Project Hamster. # Project Hamster is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as ...
def get_facts(self, date, end_date = None, search_terms = ""): """Returns facts for the time span matching the optional filter criteria. In search terms comma (",") translates to boolean OR and space (" ") to boolean AND. Filter is applied to tags, categories, activity nam...
"""returns facts of the current date, respecting hamster midnight hamster midnight is stored in gconf, and presented in minutes """ return [from_dbus_fact(fact) for fact in self.conn.GetTodaysFacts()]
identifier_body
client.py
# - coding: utf-8 - # Copyright (C) 2007 Patryk Zawadzki <patrys at pld-linux.org> # Copyright (C) 2007-2009 Toms Baugis <toms.baugis@gmail.com> # This file is part of Project Hamster. # Project Hamster is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as ...
(self, id, name): return self.conn.UpdateCategory(id, name) def add_category(self, name): return self.conn.AddCategory(name)
update_category
identifier_name
is_integer.rs
use integer::Integer; use malachite_base::num::conversion::traits::IsInteger; impl<'a> IsInteger for &'a Integer { /// Determines whether an `Integer` is an integer. It always returns `true`. /// /// $f(x) = \textrm{true}$. /// /// # Worst-case complexity /// Constant time and additional memory...
/// extern crate malachite_base; /// extern crate malachite_nz; /// /// use malachite_base::num::basic::traits::{NegativeOne, One, Zero}; /// use malachite_base::num::conversion::traits::IsInteger; /// use malachite_nz::integer::Integer; /// /// assert_eq!(Integer::ZERO.is_integer(), tru...
/// # Examples /// ```
random_line_split
is_integer.rs
use integer::Integer; use malachite_base::num::conversion::traits::IsInteger; impl<'a> IsInteger for &'a Integer { /// Determines whether an `Integer` is an integer. It always returns `true`. /// /// $f(x) = \textrm{true}$. /// /// # Worst-case complexity /// Constant time and additional memory...
(self) -> bool { true } }
is_integer
identifier_name
is_integer.rs
use integer::Integer; use malachite_base::num::conversion::traits::IsInteger; impl<'a> IsInteger for &'a Integer { /// Determines whether an `Integer` is an integer. It always returns `true`. /// /// $f(x) = \textrm{true}$. /// /// # Worst-case complexity /// Constant time and additional memory...
}
{ true }
identifier_body
view.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | ...
} impl PuzzleView for View { fn info_text(&self, game: &Game) -> &'static str { if game.if_memory_serves.is_solved() { SOLVED_INFO_TEXT } else { INFO_BOX_TEXT } } fn undo(&mut self, _: &mut Game) {} fn redo(&mut self, _: &mut Game) {} fn reset(&mu...
{ let state = &mut game.if_memory_serves; let mut action = self.core.handle_event(event, state); if event == &Event::ClockTick && self.remove_countdown > 0 { self.remove_countdown -= 1; if self.remove_countdown == REMOVE_SOUND_AT { let symbol = self.grid.f...
identifier_body
view.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | ...
if (!action.should_stop() && self.remove_countdown == 0) || event == &Event::ClockTick { let subaction = self.grid.handle_event(event, state.grid_mut()); if let Some(&symbol) = subaction.value() { action.also_play_sound(Sound::device_rotate()); ...
{ let subaction = self.next.handle_event(event, &mut state.next_shape()); if let Some(&pt) = subaction.value() { let (col, row) = self.grid.coords_for_point(pt); if let Some(symbol) = state.try_place_shape(col, row) { action.als...
conditional_block
view.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | ...
(&mut self, _: &mut Game) {} fn redo(&mut self, _: &mut Game) {} fn reset(&mut self, game: &mut Game) { self.core.clear_undo_redo(); game.if_memory_serves.reset(); } fn solve(&mut self, game: &mut Game) { game.if_memory_serves.solve(); self.core.begin_outro_scene(); ...
undo
identifier_name
view.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | ...
if value >= 0 && (value as usize) < LETTERS.len() { let (col, row, letter) = LETTERS[value as usize]; self.grid.add_letter(col, row, letter); } } } } } // ====================================================================...
if kind == 0 { self.show_next = value != 0; } else if kind == 1 {
random_line_split
html_generator.py
def generate_concept_HTML(concept_title, concept_description): html_text_1 = ''' <div class="concept"> <div class="concept-title"> ''' + concept_title html_text_2 = ''' </div> <div class="concept-description"> ''' + concept_description html_text_3 = ''' </div> </di...
print generate_all_html(TEST_TEXT)
current_concept_number = 1 concept = get_concept_by_number(text, current_concept_number) all_html = '' while concept != '': title = get_title(concept) description = get_description(concept) concept_html = generate_concept_HTML(title, description) all_html = all_html + ...
identifier_body
html_generator.py
def generate_concept_HTML(concept_title, concept_description): html_text_1 = ''' <div class="concept"> <div class="concept-title"> ''' + concept_title html_text_2 = ''' </div> <div class="concept-description"> ''' + concept_description html_text_3 = ''' </div> </di...
TITLE: What is a variable in Python? DESCRIPTION: Variables give programmers a way to give names to values. If my_variable is a variable with a value of 2, then the following code would print out 0: print my_variable - my_variable """ def generate_all_html(text): current_concept_number = 1 concept = ge...
DESCRIPTION: Programming languages are used by programmers to tell a computer what to do. Python is one example of a programming language. TITLE: Python DESCRIPTION: When you write Python code and "Run" the code, a Python Interpreter converts the written code into a set of instructions that the computer can understan...
random_line_split
html_generator.py
def generate_concept_HTML(concept_title, concept_description): html_text_1 = ''' <div class="concept"> <div class="concept-title"> ''' + concept_title html_text_2 = ''' </div> <div class="concept-description"> ''' + concept_description html_text_3 = ''' </div> </di...
return all_html print generate_all_html(TEST_TEXT)
title = get_title(concept) description = get_description(concept) concept_html = generate_concept_HTML(title, description) all_html = all_html + concept_html current_concept_number = current_concept_number + 1 concept = get_concept_by_number(text, current_concept_number)
conditional_block
html_generator.py
def
(concept_title, concept_description): html_text_1 = ''' <div class="concept"> <div class="concept-title"> ''' + concept_title html_text_2 = ''' </div> <div class="concept-description"> ''' + concept_description html_text_3 = ''' </div> </div>''' full_htm...
generate_concept_HTML
identifier_name
connect.py
import requests import os def post_var(token, ubi_source, ubi_var, value, timestamp=None, context=None): ''' This function posts data to ubidots Input parameters: token: The Ubidots token ubi_source: The name of the user's Ubidots datasource ubi_var: The name of the user's Ubidots variable value: Value to b...
''' This function gets data from ubidots Input parameters: token: The Ubidots token ubi_source: The name of the user's Ubidots datasource ubi_var: The name of the user's Ubidots variable Return: Returns in this order the next parameters: value, timestamp, context ''' try: url = os.getenv("UBIDOTS_URL")...
identifier_body
connect.py
import requests import os def
(token, ubi_source, ubi_var, value, timestamp=None, context=None): ''' This function posts data to ubidots Input parameters: token: The Ubidots token ubi_source: The name of the user's Ubidots datasource ubi_var: The name of the user's Ubidots variable value: Value to be sent timestamp: Optional, for custom...
post_var
identifier_name
connect.py
import requests import os def post_var(token, ubi_source, ubi_var, value, timestamp=None, context=None): ''' This function posts data to ubidots Input parameters: token: The Ubidots token ubi_source: The name of the user's Ubidots datasource ubi_var: The name of the user's Ubidots variable value: Value to b...
r = requests.post(url=url, headers=headers, json= data) except Exception as e: return e def get_var(token, ubi_source, ubi_var, value, timestamp=None, context=None): ''' This function gets data from ubidots Input parameters: token: The Ubidots token ubi_source: The name of the user's Ubidots datasource ...
data[ubi_var]["context"]=context
conditional_block
connect.py
import requests import os def post_var(token, ubi_source, ubi_var, value, timestamp=None, context=None): ''' This function posts data to ubidots Input parameters: token: The Ubidots token ubi_source: The name of the user's Ubidots datasource ubi_var: The name of the user's Ubidots variable value: Value to b...
Returns in this order the next parameters: value, timestamp, context ''' try: url = os.getenv("UBIDOTS_URL") if os.getenv("UBIDOTS_URL") is not None else "http://things.ubidots.com/" url = url + "api/v1.6/devices/" + ubi_source + "/" + ubi_var + "/values?page_size=1" headers = {"X-Auth-Token": token, "...
random_line_split
migrations.js
// File describing all migrations and their upward/downward changes // for API Usage Information see https://github.com/percolatestudio/meteor-migrations import {Meteor} from 'meteor/meteor'; import {ImageResources} from '../imports/modules/constants'; /* eslint-disable lodash/prefer-lodash-method */ if(Meteor.isServ...
}); } /* eslint-enable */
{ const users = Meteor.users.find().fetch(); _(users) .thru((user) => { user.apiAuthKey = user.stressApi.apiKey; user.apiAuthType = user.stressApi.apiAuthType; delete user.stressApi; return user; }).forEach((user) => Meteor.users.update({_id: user._i...
identifier_body