prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from __future__ import unicode_literals # # Copyright 2004 Free Software Foundation, Inc. # # This file is part of GNU
Radio # # SPDX-License-Identifier: GPL-3.0-or-later # cl
ass NotDAG (Exception): """Not a directed acyclic graph""" pass class CantHappen (Exception): """Can't happen""" pass
# -*- coding: utf-8 -*- from stash.tests.stashtest import StashTestCase class CowsayTests(StashTestCase): """tests for cowsay""" def test_help(self): """test help output""" output = self.run_command("cowsay --help", exitcode=0) self.assertIn("cowsay", output) self.assertIn("--...
put) self.assertIn("\\", output) self.assertIn("|", output)
self.assertNotIn("<", output) self.assertNotIn(">", output)
1) Initializes the voltage edges (self.edges) and probability mass in each bin (self.pv), 2) Creates an initial dictionary of inputs into the population, and 3) Resets the recorder that tracks firing rate during a simulation. This metho...
by the initialize method rather than on its own. It resets the lists that track the firing rate during execution of the simulation. ''' # Set up firing rate recorder: if len(self.firing_rate_record) == 0: self.firing_rate_record.append(self.curr_firing_rate) ...
imulation.t) def initialize_total_input_dict(self): '''Initialize dictionary of presynaptic inputs at beginning of simulation This method is typically called by the initialize method rather than on its own. It creates a dictionary of synaptic inputs to the population. ...
# -*- coding: utf-8 -*- # Copyright 2018 Novo Nordisk Foundation Center for Biosustainability, # Technical University of Denmark. # # 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...
_name__) class GrowthExperiment(Experiment): """Represent a growth experiment.""" SCHEMA = "growth.json" def __init__(self, **kwargs): """ Initialize a growth experiment. Parameters ---------- kwargs """ super(GrowthExperiment, self).__init__(**k...
---- dtype_conversion : dict Column names as keys and corresponding type for loading the data. Please take a look at the `pandas documentation <https://pandas.pydata.org/pandas-docs/stable/io.html#specifying-column-data-types>`__ for detailed explanations. ...
# -*- coding: utf-8 -*- #!/usr/bin/python # Author:
Tania M. Molina # UY - 2017 # MIT License import math import numpy as np import pandas as pd from scipy import stats from scipy.stats import norm import scipy.
stats as stats import scipy.stats as st import matplotlib import matplotlib.pyplot as plt import re import scipy.stats import matplotlib.pyplot as mlab fhand = raw_input('Enter .csv file name or keyword: ') data = pd.read_csv(fhand, header=0) frame = pd.DataFrame(data)
import os import unittest import numpy as np from tfsnippet.examples.utils import MLResults from tfsnippet.utils import TemporaryDirectory def head_of_file(path, n): with open(path, 'rb') as f: return f.read(n) class MLResultTestCase(unittest.TestCase): def test_imwrite(self): with Tempor...
x4e\x47\x0d\x0a\x1a\x0a') results.save_image('test.jpg', im) file_path = os.path.join(tmpdir, 'test.jpg') self.assertTrue(os.path.isfile(file_path)) self.assertEqual(head_of_file(file_path, 3), b'\xff\xd8\xf
f')
(self.admin) self.payload = {'user': self.user.pk, 'content_id': uuid.uuid4().hex, 'channel_id': uuid.uuid4().hex, 'kind': 'video', 'start_timestamp': str(datetime.datetime.now())} def test_contentsessionlog_lis...
se.status_code, status.HTTP_201_CREATED) def test_learner_can_create_ratinglog(self): self.client.login(username=self.user.username, password=DUMMY_PASSWORD, facility=self.facility) response = self.client.post(rev
erse('contentratinglog-list'), data=self.payload, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_anonymous_user_cannot_create_ratinglog_for_learner(self): response = self.client.post(reverse('contentratinglog-list'), data=self.payload, format='json') ...
project go here. LOCAL_APPS = ( 'users', # custom users app # Your stuff: custom apps go here ) # See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS INSTALLED_APPS += ( # Needs to come last f...
join(BASE_DIR, 'templates'), ) TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) # See: http://django-crispy-forms.readthedocs.org/en/latest/install.html#tem
plate-packs CRISPY_TEMPLATE_PACK = 'bootstrap3' # END TEMPLATE CONFIGURATION # STATIC FILE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = join(os.path.dirname(BASE_DIR), 'staticfiles') # See: https://docs.djangoproject.com/en/dev/ref/settings...
# Copyright (c) 2016 Mirantis Inc. # 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 require...
express or implied. See the # License for the specific language governing permissions and limitations # under the License. from alembic import context from rally.common.db import api from rally.common.db import models # add your model's MetaData object here # for 'autogenerate' support # from myapp import mym...
the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. "...
from ctypes import c_float, cast, POINTER import numpy as np import OpenGL.GL as gl import openvr from openvr.gl_renderer import OpenVrFramebuffer as OpenVRFramebuffer from openvr.gl_renderer import matrixForOpenVrMatrix as matrixForOpenVRMatrix from openvr.tracked_devices_actor import TrackedDevicesActor import g...
lf.vr_framebuffers[0].height) for eye in (0, 1): gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.vr_framebuffers[eye].fb) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gltfu.set_material_state.current_material = None gltfu.set_technique_state.current_te...
rojection_matrices[eye], view_matrix=self.view_matrices[eye]) self.controllers.display_gl(self.view_matrices[eye], self.projection_matrices[eye]) self.vr_compositor.submit(openvr.Eye_Left, self.vr_framebuffers[0].texture) self.vr_compositor.submit(openvr.Eye_R...
ries(range(2), ... index=pd.DatetimeIndex(['2015-03-29 02:30:00', ... '2015-03-29 03:30:00'])) >>> s.tz_localize('Europe/Warsaw', nonexistent='shift_forward') 2015-03-29 03:00:00+02:00 0 2015-03-29 03:30:00+02:00 1 ...
of dtypes or None (default), optional, A black list of data types to omit from the result. Ignored for ``Series``. Here are the options: - A list-like of dtypes : Exclu
des the provided data types from the result. To exclude numeric types submit ``numpy.number``. To exclude object columns submit the data type ``numpy.object``. Strings can also be used in the style of ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To ...
'''OpenGL extension ARB.robustness_application_isolation This module customises the behaviour of the OpenGL.raw.WGL.ARB.robustness_application_isolation to provide a more Python-friendly API The official definition of this extension is available here: http://www.opengl.org/registry/specs/ARB/robustness_application_...
pes, _glgets from OpenGL.raw.WGL.ARB.robustness_application_isolation import * from OpenGL.raw.WGL.ARB.robustness_application_isolation import _EXTENSION_NAME def glInitRobustnessApplicationIsolationARB(): '''Return boolean i
ndicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME ) ### END AUTOGENERATED SECTION
""" Database ORM models managed by this Django app Please do not integrate directly with these models!!! This app currently offers one programmatic API -- api.py for direct Python integration. """ import re from django.core.exceptions import ValidationError from django.db import models from django.utils.translation i...
history.models import HistoricalRecords class Organization(TimeStampedModel):
""" An Organization is a representation of an entity which publishes/provides one or more courses delivered by the LMS. Organizations have a base set of metadata describing the organization, including id, name, and description. """ name = models.CharField(max_length=255, db_index=True) short_na...
i
mport kera
s
# Copyright 2014 Intel Corp. # # Author: Zhai Edwin <edwin.zhai@intel.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
up_pipeline', mock.MagicMock()) def test_load_plugins(self): mgr = manager.AgentManager() self.assertIsNotNone(list(mgr.pollster_manager)) class TestRunTasks(agentbase.BaseAgentManagerTest
Case): @staticmethod def create_manager(): return manager.AgentManager() def setUp(self): self.source_resources = True super(TestRunTasks, self).setUp()
r per-faction special rules. def getFactionCost(self, unit): return sum([self.factionRules[r] for r in unit.specialRules + unit.wargearSp if r in self.factionRules]) class DumpTxt: def __init__(self): self.data = [] def _addUnit(self, unit): data = ['{0} {1} {2}+'.format(prettyNam...
chics.items() for name, desc in spell.items()] self.data.append('\n'.join(data)) def get(self, faction): for units, upgrades, spe
cialRules, psychics in faction.pages: self.addUnits(units) self.addUpgrades(upgrades) self.data.append('\n'.join([k + ': ' + v for k, v in specialRules.items()])) self.addPsychics(psychics) return '\n\n'.join(self.data) class DumpTex: def __init__(self): ...
from lfmconf.lfmconf import get_lastfm_conf query_play_count_by_month = """ select * from view_play_count_by_month v where substr(v.yr_month, 1, 4) = """ query_top_with_remaining = """ with top as ( {query_top} ), total_count as ( {query_play_count} ) select t.* from t...
_tracks_with_remaining.format(query_top=query_top, query_play_count=query_count) def build_query_top_tracks_for_duration(duration): condition = build_duration_condition(duration) return query_top_tracks.format(condition=condition) + add_limit() def build_que...
query_top = build_query_top_artists_for_year() query_count = build_query_play_count_for_year() return query_top_artists_with_remaining.format(query_top=query_top, query_play_count=query_count) def build_query_top_artists_for_year(): condition = build...
from utils.strings import quote from plugins.languages import javascript from utils.loggers import log from utils import rand import base64 import re class Dot(javascript.Javascript): def init(self): self.update_actions({ 'render' : { 'render': '{{=%(code)s}}', ...
e('fs').readFileSync('%(path)s').toString('base64');""" }, 'md5' : { 'call': 'evaluate', 'md5': """global.process.mainModule.require('crypto').createHash('md5').update(global.process.mai
nModule.require('fs').readFileSync('%(path)s')).digest("hex");""" }, 'evaluate' : { 'test_os': """global.process.mainModule.require('os').platform()""", }, 'execute' : { 'call': 'evaluate', 'execute': """global.process.mainM...
'''Dirty talk like you're in Dundalk''' import random import re import string __author__ = ('iandioch') COMMAND = 'flirt' PHRASES = [ "rawr~, {s}{sep}", "{s}, big boy{sep}", "{s} xo", "{s} bb{sep}", "babe, {s}{sep}", "hey xxx {s}{sep}", "{s} xxx", "{s} xx", "{s} xo", "{s} xoxo...
rn message def main(bot, author_id, message, thread_id, thread_type, **kwargs): message = bot.fetchThreadMessages(thread_id=thread_id, limit=2)[1] sauce = flirt(message.text) bot.sendMessage(sauce, thread_id=thread_id, thread_type=thread_type) if __name__ == '__main__': print(flirt('hey brandon do yo...
d and saviour steely for a minute. Please brandon.')) print(flirt('Fine then')) print(flirt('Your API was shit anyway'))
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2014, 2015 CERN. # # Invenio 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 2 of the # License, or (at your option) any...
sAutoDiscoveryRegistry, self).__init__( 'testsuite', **kwargs ) def keygetter(self, key, original_value, new_value): """No key mapping.""" return key def _walk_dir(self, pkg, base, root): """Recursively register *.spec.js/*.js files.""" for root, dirs, files...
eSpecsAutoDiscoveryRegistry.pattern.match(name): filename = os.path.join(root, name) filepath = "{0}/{1}".format( pkg, filename[len(base) + 1:] ) self.register(filename, key=filepath) def...
lt([i_data], i_data, mod=mod) def test_sum_loop(): mod = relay.module.Module({}) sum_up = relay.GlobalVar('sum_up') i = relay.var('i', shape=[], dtype='int32') accum = relay.var('accum', shape=[], dtype='int32') sb = ScopeBuilder() with sb.if_scope(relay.equal(i, relay.const(0, 'int32'))): ...
testing.assert_allclose(result.asnumpy(), 10) def test_list_map(): mod = relay.Module() p = Prelude(mod) x = relay.var('x', 'int32') add_one_func = relay.Function([x], relay.const(1) + x) nil = p.nil cons = p.cons
map = p.map l = cons(relay.const(2), cons(relay.const(1), nil())) f = relay.Function([], map(add_one_func, l)) mod["main"] = f result = veval(mod) tvm.testing.assert_allclose(vmobj_to_list(result), np.array([3, 2])) def test_list_foldl(): mod = relay.Module() p = Prelude(mod) nil...
# # Contain the transformation procedure # import sys import module.loop.ast #----------------------------------------- def __makeForLoop(id, lbound, ubound, stride, loop_body): '''Generate a for loop: for (id=lbound; id<=ubound; id=id+stride) loop_body''' init_exp = None test_exp = ...
.init, module.loop.ast.BinOpExp) and cur_stmt.init.op_type == module.loop.ast.BinOpExp.EQ_ASGN and isinstance(cur_stmt.init.lhs, module.loop.ast.IdentExp)): iname = cur_stmt.init.lhs.name if iname in seen_loops: if all_unseen_optional: ...
print ('error:%s: loop "%s" cannot occur repeatedly' % (cur_stmt.line_no, iname)) sys.exit(1) if iname not in unseen_loops: if all_unseen_optional: loop_body = cur_stmt break else: ...
import unittest from django.test.client import Client from django.forms import ValidationError from fields import MultipleEmailField class CaseTests(unittest.TestCase): def setUp(self): self.c = Client() self.case_id = 12345 self.status_codes = [301, 302] def test_cases(self): ...
try: self.assertEquals(response.status_code, 200) except AssertionError: self.assertEquals(response.status_code, 302) def test_cases_priority(self): response = self.c.get('/cases/priority/') try: self
.assertEquals(response.status_code, 200) except AssertionError: self.assertEquals(response.status_code, 302) def test_case_getcase(self): location = '/case/%s' % self.case_id response = self.c.get(location) if response.status_code == 301: print response.path ...
""" Shogun demo Fernando J. Iglesias Garcia This example shows the use of dimensionality reduction methods, mainly Stochastic Proximity Embedding (SPE), although Isomap is also used for comparison. The data selected to be embedded is an helix. Two different methods of SPE (global and local) are applied showing that t...
pylab.plot(X[0, y2], X[1, y2], 'go') pylab.title('SPE with global strategy') # Compute a second SPE embedding with local strategy converter.set_stra
tegy(SPE_LOCAL) converter.set_k(12) embedding = converter.embed(features) X = embedding.get_feature_matrix() fig.add_subplot(2, 2, 3) pylab.plot(X[0, y1], X[1, y1], 'ro') pylab.plot(X[0, y2], X[1, y2], 'go') pylab.title('SPE with local strategy') # Compute Isomap embedding (for comparison) converter = Isomap() con...
#!/usr/bin/python import computefarm as cf from computefarm.farm import depth_first, breadth_first import random import logging import numpy as np HOUR = 60 * 60 default_queue_properties = { 'grid': { 'num': 0, 'mem': 750, 'avg': HOUR, 'std': 0.6 * HOUR}, 'prod': { 'num': 0, 'avg': 8 * HOUR, 'std...
lf.queue = cf.JobQueue() self.farm.attach_queue(self.queue) # How many seconds per negotiation/stat gathering cycle self.int_stat = stat_freq self.int_negotiate = negotiate_interval self.int_submit = submit_interval self.next_stat = 0 self.next_negotiate = 0 ...
_set* knobs are used in callbacks by the GUI def _set_neg_df(self): self.farm.set_negotiatior_rank(depth_first) def _set_neg_bf(self): self.farm.set_negotiatior_rank(breadth_first) def _init_stat(self, hist_size): """ Statistics are kept in a constant-size numpy array that is upda...
# Note: Modified by Neui (Note: sphinx.util.compat.Directive is deprecated) # # Copyright (C) 2011 by Matteo Franchin # # This file 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...
lder = app.builder if builder.name != SingleFileHTMLBuilder.name: for node in doctree.traverse(globalindex): node.parent.remove(node) else: docname = builder.config.master_doc for node in doctree.traverse(globalindex): kwargs = dict(
maxdepth=node['maxdepth'], collapse=node['collapse'], titles_only=node['titlesonly']) rendered_toctree = builder._get_local_toctree(docname, **kwargs) # For some reason, it refers to docname.html#anchor, where just # #anchor is enou...
# coding: utf-8 """ MINDBODY Public API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: v6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 impor...
ms(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value ))
elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() ...
from django.utils import unittest from djan
go.contrib import admin from hyperadmin.sites import ResourceSite class SiteTestCase(unittest.TestCase): def test_install_from_admin_site(self): site = ResourceSite() admin.autodiscover()
site.install_models_from_site(admin.site) self.assertTrue(site.registry)
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # # 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 applica...
lf.yaml = ruamel.yaml.YAML() self.yaml.allow_duplicate_keys = True self.yaml.representer.add_representer(type(None), none_representer) self.yaml.indent(mapping=2, sequence=4, offset=2) def load(self, stream): return self.yaml.load(stream) def tr(self, x): x = x.replace(...
ine) else: newlines.append(line[2:]) return '\n'.join(newlines) def dump(self, data, *args, **kwargs): if isinstance(data, list): kwargs['transform'] = self.tr self.yaml.dump(data, *args, **kwargs) _yaml = YAML() def load(*args, **kwargs): ret...
e self.assertTrue(exception_raised) def testTargetOsInDepsFile(self): """Verifies that specifying a target_os value in a DEPS file pulls in all relevant dependencies. The target_os variable in a DEPS file allows specifying the name of an additio
nal OS which should be considered when selecting dependencies from a DEPS' deps_os. The value will be appended to the _enforced_os tuple. """ write( '.gclient', 'solutions = [\n' ' { "name": "foo",\n' ' "url": "svn://example.com/foo",\n' ' },\n' ' { "na...
' "unix": { "foo/unix": "/unix", },\n' ' "baz": { "foo/baz": "/baz", },\n' ' "jaz": { "foo/jaz": "/jaz", },\n' '}') write( os.path.join('bar', 'DEPS'), 'deps_os = {\n' ' "unix": { "bar/unix": "/unix", },\n' ' "baz": { "bar/baz": "/baz", },\n' ...
scope=Scope.settings, name='') settings_lst = List(scope=Scope.settings, name='') uss_lst = List(scope=Scope.user_state_summary, name='') user_lst = List(scope=Scope.user_state, name='') pref_lst = List(scope=Scope.preferences, name='') user_info_lst = List(scope=Scope.user_info,...
# However, the field should not ACTUALLY be marked as a field that is needing to be saved. assert_not_in('how_many', field_tester._get_fields_to_save()) # pylint: disable=W0212 def test_setting_the_same_value_marks_field_as_dirty(): """ Check that setting field to the same value marks mutable fields as...
n't changed, these fields won't be saved. """ class FieldTester(XBlock): """Test block for set - get test.""" non_mutable = String(scope=Scope.settings) list_field = List(scope=Scope.settings) dict_field = Dict(scope=Scope.settings) runtime = TestRuntime(services={'field-dat...
# -*- coding: utf-8 -*- # (c) 2015 Antiun Ingeniería S.L. - Pedro M. Baeza # (c) 2015 Av
anzOSC - Ainara Galdona # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0 { "name": "AEAT - Prorrata de IVA", "version": "8.0.2.0.0", "license": "AGPL-3", "author": "AvanzOSC, " "Antiun Ingeniería S.L., " "Serv. Tecnol. Avanzados - Pedro M. Baeza, " "...
3', ], "data": [ "data/tax_code_map_mod303_data.xml", "data/aeat_export_mod303_data.xml", 'wizard/l10n_es_aeat_compute_vat_prorrate_view.xml', 'views/mod303_view.xml' ], "installable": True, }
terials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE INC. ...
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WebPageMessages_h #define W...
/PluginData.h> #include <wtf/ThreadSafeRefCounted.h> #include <wtf/Vector.h> namespace CoreIPC { class ArgumentEncoder; class Connection; class MachPort; } namespace WTF { class String; } namespace WebKit { struct WebPreferencesStore; class WebTouchEvent; } namespace Messages { namespace We...
ost_func, default_func) = \ AbstractSMTPAccount.get_register_fields()[0] value = post_func("False", None, "user1@test.com") self.assertFalse(value) self.assertTrue(account12.default_account) def test_create_email(self): account11 = AbstractSMTPAccount(user=User(jid="user...
"250 OK\r\n", "250 Accepted\r\n",
"354 Enter message\r\n", None, None, None, None, None, None, None, None, "250 OK\r\n"], ["ehlo .*\r\n", "AUTH CRAM-M...
#!/usr/bin/env python # -*- coding: utf-8 import sys import argparse from ete3 import Tree import anvio.db as db import anvio.utils as utils import anvio.terminal as terminal from anvio.errors import ConfigError run = terminal.Run() progress = terminal.Progress() current_version, next_version = [x[1:] for x in __n...
m_orders: if item_orders[order_name]['type'] == 'newick': newick = Tree(item_orders[order_name]['data'], format=1) newick = newick.write(format=2) profile_db._exec("""UPDATE %s SET "data" = ? WHERE "name" LIKE ?""" % item_orders_table_name, (newick, order_name)) # migrat...
der_name]['data_type'] == 'newick': newick = Tree(layer_orders[order_name]['data_value'], format=1) newick = newick.write(format=2) profile_db._exec("""UPDATE %s SET "data_value" = ? WHERE "data_key" LIKE ?""" % layer_orders_table_name, (newick, order_name)) # set the version ...
import numpy as np import warnings def mean_time(t, min_threshold=0, max_threshold=1
253): """ Take a switch probability result array from the PreAmp timer, and compute mean switching time using the specified thresholds. Timing data is assumed to be a numpy array. """ t = t[np.logical_and(t > min_threshold, t < max_threshold)] if np.size(t) > 0: t_mean = np.mean(t) ...
me_diff(t, min_threshold=0, max_threshold=1253): """ Take a switch probability result array from the PreAmp timers, and compute mean switching time using the specified thresholds. """ dt = t[0][:] - t[1][:] t0_mask = np.logical_and(t[0,:] > min_threshold, t[0,:] < max_threshold) t1_mask = np...
from edge import DummyEdgeEnd from simulation_event import AbstractSimulationEvent from stats import TripStats class AbstractAntMove(AbstractSimulationEvent): def __init__(self, ant, origin,
destination, end_time, pheromone_to_drop, trip_stats): self.ant = ant self.origin = origin self.destination = de
stination if self.origin is not None and self.destination is not None: if self.origin.edge is not None and self.destination.edge is not None: #print 'origin', self.origin #print 'destination', self.destination assert self.origin.edge == self.destinatio...
''' from https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#specifying-a-custom-user-model ''' from django import forms from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.utils.translation import gette...
isplay field. """ password = ReadOnlyPasswordHashField() class Meta: model = User fields = ('email', 'password', 'is_active', 'is_superuser') def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rath
er than on the field, because the # field does not have access to the initial value return self.initial["password"] class MyUserAdmin(UserAdmin): # The forms to add and change user instances form = UserChangeForm add_form = UserCreationForm # The fields to be used in displaying the Us...
# coding: utf-8 __author__ = "@strizhechenko" import sys from morpher import Morpher from twitterbot_utils import Twibot from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() bot = Twibot() morphy = Morpher() def tweets2words(tweets): string = " ".joi
n([tweet.text for tweet in tweets]) return morphy.process_to_words(string) @sched.scheduled_job('interval', minutes=15) def do_tweets(): print 'New tick' words = tweets2words(bot.fetch_list(list_id=217926157)) for word in words: tweet = morphy.word2phrase(word) bot.tweet(tweet) ...
duled_job('interval', hours=24) def do_wipe(): print 'Wipe time' bot.wipe() if __name__ == '__main__': do_tweets() if '--test' in sys.argv: exit(0) sched.start()
"""Modify Group Entry Message.""" from enum import IntEnum from pyof.foundation.base import GenericMessage from pyof.foundation.basic_types import ( FixedTypeList, Pad, UBInt8, UBInt16, UBInt32) from pyof.v0x04.common.header import Header, Type from pyof.v0x04.controller2switch.common import Bucket __all__ = ('Gr...
ucket): Instance or a list of instances. """ super().__init__(pyof_class=Bucket, items=items) class GroupMod(GenericMessage): """Group setup and teardown (controller -> datapath).""" header = Header(message_type=Type.OFPT_GROUP_MOD) command = UBInt16(enum_ref=GroupModCommand) group_ty...
def __init__(self, xid=None, command=None, group_type=None, group_id=None, buckets=None): """Create a GroupMod with the optional parameters below. Args: xid (int): Header's transaction id. Defaults to random. command (GroupModCommand): One of OFPGC_*. ...
r to be rendered on top (True) or closes the figure for plotting (False) :param list xlim: Lower and upper bounds for x-axis :param list ylim: Lower and upper bounds for y-axis """ if not data: print("No pairs found - abandoning plot!") return fig = plt.figure...
ighx = highy xbins = np.linspace(lowx - 0.05, highx + 0.05, ((highx + 0.05 - lowx - 0.05) / 0.1) + 2.0) ybins = np.linspace(lowx - 0.05, highx + 0.05, ((highx + 0.05 - lowx - 0.05) / 0.1) + 2.0) density = sample_agency_magnitude_pairs(data, xbins, ybins, num...
(figsize=figure_size) if lognorm: cmap = deepcopy(matplotlib.cm.get_cmap("jet")) data_norm = LogNorm(vmin=0.1, vmax=np.max(density)) else: cmap = deepcopy(matplotlib.cm.get_cmap("jet")) cmap.set_under("w") data_norm = Normalize(vmin=0.1, vmax=np.max(density)) #de...
import socket from subprocess import Popen, PIPE, STDOUT import os import time import string import requests import json import omxplayer class UnsupportedFileTypeException(Exception): '''Raised if the file type is not among the list of supported types''' pass class FileNotFoundException(Exception): '''...
in the player at all times self._playlist = [] self._player = None # used to dete
rmine if a self.supported = ["mp4", "avi", "mkv", "flv", ".aac", "3gp"] # add more later # creating an instance of the vlc window # local socket connection to the vlc player @property def playlist(self): '''returns list of file paths''' return...
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak from reportlab.lib.styles import getSampleStyleSheet from reportlab.rl_config import defaultPageSize from reportlab.lib.units import cm import operator import os import ConfigParser import string config = ConfigP...
tyle(TableStyle([('VALIGN',(0,0),(-1,-1),"TOP"), ('ALIGN',(0,-1),(0,-1),'RIGHT')])) Story.append(p
) doc.build(Story, onFirstPage=Pages, onLaterPages=Pages) go(buchstabe)
import sqlite3 class Database: def __init__(self, dbfile, page_rows=100): self.dbfile = dbfile self.page_rows = page_rows self.conn = sqlite3.connect(self.dbfile) self.conn.row_factory = sqlite3.Row cursor = self.conn.cursor() cursor.execute( "CREATE TAB...
, offset] ).fetchall() return [ dict(row) for row in rows ] def save(self, item): saved = False if item.item_type == 'message': timestamp = item.content['timestamp'] message = item.asJson()
cursor = self.conn.cursor() cursor.execute( "INSERT INTO messages VALUES (?,?)", [timestamp, message] ) self.conn.commit() saved = True return saved
from flask import Flask from os.path import expanduser def c
reate_app(): app = Flask(__name__) app.config.from_pyfile(expanduser('~/.directory-tools.py'
)) from directory_tools.frontend import frontend app.register_blueprint(frontend) return app
import array class vec(object): @staticmethod def sized(size, type='d'): return vec([0] * size, type) @staticmethod def of(content, type='d'): return vec(content, type) def __init__(self, content, type='d'): self.size = len(content) self.type = type self.a...
er, vec) result = out if result is None:
result = vec([0] * self.size, self.type) if self.size != other.size: raise Exception("size mismatch! %d != %d" % (self.size,other.size)) i = 0 while i < self.size: result.array[i] = self.array[i] + other.array[i] i += 1 return result def ...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2013 PolyBeacon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Server Specific Configurations server = { 'port': '9859', 'host': '0.0.0.0', } # Pecan Application Configurations app = { 'root': 'payload.api.controllers.root.Root...
plate_path': '%(confdir)s/payload/api/templates', }
#!/usr/bin/env python """ $ python cmdln_main2.py This is my shell. $ python cmdln_main2.py foo
hello from foo """ import sys import cmdln class Shell(cmdln.RawCmdln): "This is my shell." name = "shell" def do_foo(self, argv): print("hello from foo") if __name__ == "__main__": shell = S
hell() retval = shell.cmd(sys.argv[1:]) # just run one command sys.exit(retval)
# coding: utf-8 from libs.redis_storage import db1 class User(object): def __init__(self, **kwargs): pk = kwargs.get('pk') or db1.incr('new_user_id') kwargs['pk'] = pk db1.hmset('user::{}'.format(pk), kwargs) super(User, self).__setattr__('pk', pk) super(User, self).__seta...
'defeats', 'last_update' ]}
@property def db_key(self): return 'user::{}'.format(self.pk) @property def fio(self): return u'{} {}'.format(self.last_name or u'', self.first_name or u'') @property def battles(self): return int(self.__info__.get('battles', 0)) @property def wins(self): ...
'}, {'type': 'text', 'label': 'IP / Host *', 'name': 'mylar_host'}, {'type': 'text', 'label': 'Port *', 'name': 'mylar_port'}, {'type': 'text', 'label': 'Basepath', 'name': 'mylar_basepath'}, {'type': 'text', 'label': 'API key', 'name': 'mylar_apikey'}, ...
rn self.fetch('shutdown', text=True) @cherrypy.expose() @require(mem
ber_of(htpc.role_user)) def UpDate(self): return self.fetch('update', text=True) @cherrypy.expose() @require(member_of(htpc.role_user)) def ReStart(self): return self.fetch('restart', text=True) def fetch(self, command, url=None, api_key=None, img=False, json=True, text=False): ...
"""Custom keras layers """ # Coding: utf-8 # File name: custom_layer.py # Created: 2016-07-24 # Description: ## v0.0: File created. MergeRowDot layer. from __future__ import division from __future__ import print_function __author__ = "Hoang Nguyen" __email__ = "hoangnt@ai.cs.titech.ac.jp" from keras import backend a...
s RowDot(Merge): """ Layer for element wise merge mul and take sum along the second axis. """ ##################################################################### __init__ def __init__
(self, layers=None, **kwargs): """ Init function. """ super(RowDot, self).__init__(layers=None, **kwargs) ######################################################################### call def call(self, inputs, **kwargs): """ Layer logic. """ print('Inputs 0 shape: %s' % str(inputs[0]....
Numeric array + Non-numeric array for numeric_col in self.numeric_array_df_cols: for non_numeric_col in self.non_numeric_array_df_cols: self.assertRaises(TypeError, lambda: psdf[numeric_col] + psdf[non_numeric_col]) def test_sub(self): self.assertRaises(TypeError, lambd...
df["this_struct"] != pdf["that_struct"], psdf["this_struct"] != psdf["that_struct"] ) self.assert_eq( pdf["this_array"] != pdf["this_array"], psdf["this_array"] != psdf["this_array"] ) self.assert_eq( pdf["this_struct"] !
= pdf["this_struct"], psdf["this_struct"] != psdf["this_struct"] ) def test_lt(self): pdf, psdf = self.complex_pdf, self.complex_pdf self.assert_eq( pdf["this_array"] < pdf["that_array"], psdf["this_array"] < psdf["that_array"] ) self.assert_eq( pdf["...
ase_value: val['value_residual'] = purchase_value - salvage_value if salvage_value: val['value_residual'] = purchase_value - salvage_value return {'value': val} def _entry_count(self, cr, uid, ids, field_name, arg, context=None): MoveLine = self.pool('...
)]}), 'note': fields.text('Note'), 'category_id': fields.many2one('account.asset.category', 'Asset Category', required=True, change_default=True, readonly=True, states={'draft':[('readonly',False)]}), 'parent_id': fields.many2one('acc
ount.asset.asset', 'Parent Asset', readonly=True, states={'draft':[('readonly',False)]}), 'child_ids': fields.one2many('account.asset.asset', 'parent_id', 'Children Assets', copy=True), 'purchase_date': fields.date('Purchase Date', required=True, readonly=True, states={'draft':[('readonly',False)]}), ...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Pu...
WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licen...
house Management', 'sequence': 14, 'summary': '', 'description': """ Stock Multic Fix ================================== """, 'author': 'ADHOC SA', 'website': 'www.adhoc.com.ar', 'license': 'AGPL-3', 'images': [ ], 'depends': [ 'stock_account', ], 'data': ['stock...
from button import Button class SellButton(Button): def __init__(self, image, x, y, parent): super(SellButton, self).__init__(image, x, y, parent) def get_click
ed(self): self.parent.s
ell_tower()
# -*- coding: utf-8 -*- # Copyright 2022 Google 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...
d on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for DeleteRegistration # NOTE: This snippet has been automatically generat...
e modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-domains # [START domains_v1_generated_Domains_DeleteRegistration_sync] from google.cloud import domains_v1 def sample_delete_registration(): # Create...
"""Defines chart-wide shared test fixtures.""" import numpy as np import pandas as pd import pytest from bokeh.sampledata.autompg import autompg class TestData(object): """Contains properties with easy access to data used across tests.""" def __init__(self): self.cat_list = ['a', 'c', 'a', 'b'] ...
_data): data = test_data.dict_data.copy() data['col3'] = test_data.cat_list return data @pytest.fixture(scope='module') def df_with_cat_index(test_data): return pd.DataFrame(test_data.dict_data, index=test_data.cat
_list)
#!/usr/bin/env python import asyncio import os import signal import websockets async def echo(websocket): asy
nc for message in websocket: awai
t websocket.send(message) async def main(): # Set the stop condition when receiving SIGTERM. loop = asyncio.get_running_loop() stop = loop.create_future() loop.add_signal_handler(signal.SIGTERM, stop.set_result, None) async with websockets.serve( echo, host="localhost", po...
#! /usr/bin/env python # Print digits of pi forever. # # The algorithm, using Python's 'long' integers ("bignums"), works # with continued fractions, and was conceived by Lambert Meertens. # # See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton, # published by Prentice-Hall (UK) Ltd., 1990. import...
a1//b1 while d == d1: output(d)
a, a1 = 10L*(a%b), 10L*(a1%b1) d, d1 = a//b, a1//b1 def output(d): # Use write() to avoid spaces between the digits # Use str() to avoid the 'L' sys.stdout.write(str(d)) # Flush so the output is seen immediately sys.stdout.flush() if __name__ == "__main__": main()
or a CSV file column # containing URLs for video encodings for the named profile # (e.g. desktop, mobile high quality, mobile low quality) return _("{profile_name} URL").format(profile_name=profile) profile_whitelist = VideoUploadConfig.get_profile_whitelist() videos = list(_get_videos...
e_name": file_name, "upload_url": upload_url}) return JsonResponse({"files": resp_files}, status=200) def storage_service_bucket(): """ Returns an S3 bucket for video uploads. """ conn = s3.connection.S3Connection( settings.AWS
_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY ) return conn.get_bucket(settings.VIDEO_UPLOAD_PIPELINE["BUCKET"]) def storage_service_key(bucket, file_name): """ Returns an S3 key to the given file in the given bucket. """ key_name = "{}/{}".format( settings.VIDEO_UPLOAD_PIPELI...
import click from do_cli.contexts import CTX from do_cli.commands.common import host_commands @click.command('list') @click.option('-f', '--force-refresh', is_flag=True, help='Pull data from the API') @click.option('-h', '--host-names', help='Comma separated list of host names') @CTX def cli(ctx, force_refresh, host_...
st names Show minimal data for specific droplets """ if ctx.verbose: click.echo("Show minimal data for droplets") click.echo(host_commands(ctx, force_refresh, host_names)) if ctx.verbose:
click.echo('---- cmd_list done ----')
import base64 import csv import io import multiprocessing import numpy as np import sys from collections import defaultdict from io import StringIO from pathlib import Path # Import matplotlib ourselves and make it use agg (not any GUI anything) # before the analyze module pulls it in. import matplotlib matplotlib.use...
eat.perminute.png".format(trackrel)) plotter.plot_trace() saveplot("{}.20.plot.svg".format(trackrel)) @post('/analyze/') def post_analyze(): trackrel = request.query.trackrel try: _do_analyze(trackrel) ex
cept ValueError: # often 'wrong number of columns' due to truncated file from killed experiment raise(TrackParseError(trackrel, sys.exc_info())) redirect("/view/{}".format(trackrel)) def _analyze_selection(trackrels): for trackrel in trackrels: try: _do_analyze(trackrel) ...
# project/models.py from project import db from project.uuid_gen import id_column class Payment(db.Model): id = id_column() email = db.Column(db.String(255), unique=False, nullable=False) names = db.Column(db.String(255), unique=False, nullable=False) cardNumber = db.Column(db.String(255), unique=Fals...
se): self.names = names self.email = email self.ca
rdNumber = card_number self.phone = phone self.amount = amount self.object_payment = object_payment self.status = status
############################################################################## # Copyright (c) 2015 Huawei Technologies Co.,Ltd. and others # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, ...
self.connection = ssh.SSH(user, ip, key_filename=key_filename) self.connection.wait(timeout=600) LOG.debug("ssh host success!") self.check_script = self.get_script_fullpath( "ha_tools/check_openstack_cmd.bash") self.cmd = self._config["command_name"] de...
exit_status = 0 if self.connection: exit_status, stdout, stderr = self.connection.execute( "/bin/bash -s '{0}'".format(self.cmd), stdin=open(self.check_script, "r")) LOG.debug("the ret stats: %s stdout: %s stderr: %s" % (exit_s...
#coding=utf-8 from selenium import webdriver import pymysql import unittest,time from selenium.webdriver.common.keys import Keys print("test36") wf = webdriver.Firefox() mark_01=0 n=0 wf.get("http://192.168.17.66:8080/LexianManager/html/login.html") wf.find_element_by_xpath(".//*[@id='login']").click() time.sleep(1) w...
ck() time.sleep(1) wf.find_element_by_xpath(".//*[@id='leftMenus']/div[8]/div[2]/ul/li[2]/a").click() time.sleep(1) wf.switch_to_frame("manager")
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2013 The Plaso Project Authors. # Please see the AUTHORS file for details on individual 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 L...
buted under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
See the License for the specific language governing permissions and # limitations under the License. """Formatter for Android contacts2.db database events.""" from plaso.lib import eventdata class AndroidCallFormatter(eventdata.ConditionalEventFormatter): """Formatter for Android call history events.""" DATA_T...
# Copyright 2021 The TensorFlow A
uthors. 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, ...
# [1] https://doi.org/10.1016/0009-2614(91)90115-P # Helgaker, 1991 import numpy as np from scipy.optimize import newton from pysisyphus.tsoptimizers.TSHessianOptimizer import TSHessianOptimizer class TRIM(TSHessianOptimizer): def optimize(self): energy, gradient, H, eigvals, eigvecs, resetted = s...
the mode to follow uphill. eigvals_ = eigvals.copy() eigvals_[self.root] *= -1 gradient_ = gradient_.copy() gradient_[s
elf.root] *= -1 def get_step(mu): zetas = -gradient_ / (eigvals_ - mu) # Replace nan with 0. zetas = np.nan_to_num(zetas) # Transform to original basis step = eigvecs * zetas step = step.sum(axis=1) return step def get...
class Node: def __init__(self,val): self.value = val self.nextNode = None def getValue(self): return self.value def getNextNode(self): return self.nextNode def setValue(self,val): self.value = val def setNextNode(self,nxtNode): self.nextNode = n...
ng on the size of the LL def isEmpty(self): if(self.head == None): return True else: return False # Add a node to the head of the LL def add(self,value): temp = Node(value) temp.setNextNode(self.head) self.head = temp
# gives the total number of elements def size(self): temp = self.head count = 0 if(temp != None): count = 1 while(temp.getNextNode() != None): count += 1 temp = temp.getNextNode() return count # prints the elemnts in the Lis...
from flask.ext.flails import FlailsView from flask import render_template, redirect, url_for, request #from config import db import models import forms class PrivatePostView(FlailsView): def private_post_index(self): object_list = models.Post.query.all() return render_template('post/index.slim', ob...
ion.add(comment) #db.session.commit() return redirect(url_for('.show', ident=post_id)) return render_template('post/show.slim', post=post, form=form) def private_comment_del
ete(self, post_id, ident): comment = models.Comment.query.get(ident) #db.session.delete(comment) #db.session.commit() return redirect(url_for('.show', ident=post_id))
from flask import Response from flask.views import View from bson import json_util from mcp import mongo class Map(View): def dispatch_request(self, komuna, viti): json = mongo.db.procurements.aggregate([ { "$match": { "komuna.slug": komuna, ...
"$group": { "_id": { "selia": "$kompania.selia.slug", "emri": "$kompania.selia.emri", "gjeresi": "$kompania.selia.kordinatat.gjeresi",
"gjatesi": "$kompania.selia.kordinatat.gjatesi", }, "cmimi": { "$sum": "$kontrata.qmimi" }, "vlera": { "$sum": "$kontrata.vlera" }, "numriKontratave"...
for the built-in windowing primitives here. Integer or floating point seconds can be passed to these primitives. Internally, seconds, with microsecond granularity, are stored as timeutil.Timestamp and timeutil.Duration objects. This is done to avoid precision errors that would occur with floating point representation...
window. """ def __init__(self, end): self.end = Timestamp.of(end) def max_timestamp(self): return self.end.predecessor() def __eq__(self, other): raise NotImplementedError def _
_ne__(self, other): # Order first by endpoint, then arbitrarily return self.end != other.end or hash(self) != hash(other) def __lt__(self, other): if self.end != other.end: return self.end < other.end return hash(self) < hash(other) def __le__(self, other): if self.end != other.end: ...
to make it look better # here - probably want to avoid high values of # all because it will be white # (Emphasise/Reduce bass, mids, treble) l[i] *= float(equalizer[i]) l[i] = (l[i] * 256) - 1 # Use new val if > previous m...
sicColor = setting.split('#') else: MusicColor = setting print "starting " + mode + "-service with " + str(MusicColor) + " color settings" if not mode == old_mode: start_new_thread(self.ac.loop, ()) elif (mode == "F...
a tempo of " + str(tempo) if not mode == old_mode: start_new_thread(self.ef.Flasher, ()) elif (mode == "Strobe"): global tempo tempo = float(setting) print "starting " + mode + "-service with a tempo of " + str(tempo)...
from time import time from benchmark import Benchmark from optimizer.optimizer import Optimizer from optimizer.simulator import Simulator from optimizer.evaluator import Evaluator from extra.printer import pprint, BLUE class EvaluatorPerf(Benchmark): def __init__(self, plant, orderList, testNumber): Benchmark.__...
elf): orders = self.orderList.orders[:] self.orderList.orders = [] i = self.startValue while i <= len(orders): pprint("PERF Number of orders = " + str(i), BLUE) self.orderList.orders = orders[:i] optimizer = Optimizer(self.plant, self.orderList, Simulator(self.plant), Evaluator...
imizer.indivMutationRate = 0.5 optimizer.selectionRate = 0.5 optimizer.mutationRange = 10 schedules = optimizer.run() evaluator = Evaluator(self.plant) t = time() evaluator.evaluate(schedules[0]) t = time() - t self.addCairoPlotTime(t) self.addGnuPlotTime(i, t) ...
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages EXCLUDE_FROM_PACKAGES = ['test_*',] VERSION = "1.1.0" INSTALL_REQUIRES = [ 'requests', 'Flask' ] TESTS_REQUIRE = [ 'nose', 'httpretty' ] setup( name='Flask-HTTP-Forwarding', version=VERSION, url='http://www.gi...
rs=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'Topic :: Software Developm...
: Python Modules' ] )
i": "//", "em": "//", "u": "__", "ins": "__", "mark": "__", "pre": "''", "code": "''", "blockquote": "", "strike": "~~", "del": "~~", ...
.zim_str += '"' elif tag == "time": datetime = assoc("datetime", attrs) if datetime is not None: self.tag_attrib = " (" + datetime + ")" elif tag == "a": href = assoc("href", attrs) self.a_href
= href #ref of tag if href is None: href = "#" #Add blank when tag not start line if self.zim_str.endswith(("\n", "(", "[", "\t", "\"", " ", "/", '\xa0')): blank = "" else: blank = " " #If we are in a table we ...
from setuptools import setup, find_packages from helga_github_meta import __version__ as version setup( name='helga-github-meta', version=version, description=('Provide information for github related metadata'), classifiers=[ 'Development Status :: 4 - Beta', 'Topic :: Communications :...
nt :: Libraries :: Python Modules', 'Topic :: Communications :: Chat :: Internet Relay Chat'], ke
ywords='irc bot github-meta urbandictionary urban dictionary ud', author='Jon Robison', author_email='narfman0@gmail.com', url='https://github.com/narfman0/helga-github-meta', license='LICENSE', packages=find_packages(), include_package_data=True, py_modules=['helga_github_meta.plugin'], ...
from django.contrib import admin from library.models import Author,
Book, Genre, Review ad
min.site.register(Author) admin.site.register(Book) admin.site.register(Genre) admin.site.register(Review)
# -*- coding: utf-8 -*- """ Largest product in a grid https://projecteuler.net/problem=11 """ GRID = """ 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56...
[i + 3][j - 3] yield a, b, c, d grid = [] for line in GRID.strip().split('\n'): grid.append([int(x.strip()) for x in line.split()]) max_product = 0 for a, b, c, d in ad
jacent_numbers_gen(grid): max_product = max(max_product, a * b * c * d) print max_product
from
split_settings.tools import optional, include include( 'components/base.py', 'components/pagination.py', optional('components/global.py'), ## # Local should be after product.py because if default value has not # been defined in the DATABASE dictionary then it must be defined. 'components...
scope=globals() )
cal path containing test files. There should be a folder called Workflow containing (the files can be simple textfiles) # FolderA # -FolderAA # --FileAA # -FileA # FolderB # -FileB # File1 # File2 # File3 def _mul(txt): """ Multiply the input text enough time so that we reach the expected file size """ re...
the older Directory ================") workflow_folder = DESTINATION_PATH + '/Workflow' res = self.writeSE.removeDirectory(workflow_folder) if not res['OK']: print("basicTest.clearDirectory: Workflow folder maybe not empty") print("==================================================") def testWo...
putDir = {os.path.join(DESTINATION_PATH, 'Workflow/FolderA'): os.path.join(self.LOCAL_PATH, 'Workflow/FolderA'), os.path.join(DESTINATION_PATH, 'Workflow/FolderB'): os.path.join(self.LOC...
# -*- coding:utf-8 -*- import tornado.web from wechatpy.parser import parse_message from wechatpy import WeChatClient TOKEN = '123456' APPID = 'wxecb5391ec8a58227' SECRET = 'fa32576b9daa6fd0
20c0104e6092196a' import sys reload(sys) sys.setdefaultencoding("utf-8") class BaseHandler(object): def get_client(self): client = WeChatClient(APPID, SECRET) a = client.menu.create({ "button": [ {
"type": "click", "name": "阅读", "key": "TODAY_READ" }, { "type": "click", "name": "音乐", "key": "TODAY_MUSIC" }, { "name": "时光", ...
############################################################################## # Copyr
ight (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is
part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the ter...
t.mark.parametrize('name, expected', convert_to_name_pair_list) def test_convert_to_name_pair(self, name, expected): """ Test if name pairing works """ assert self.test_class._convert_to_name_pair(name) == expected @pytest.mark.parametrize('author_elem, expected', [(dict(), Non...
expected def test_get_abstract(self, citeproc): """ Abstract must be set """ assert self.test_class._get_abstract(citeproc) == citeproc['abstract'] def test_get_abstact_missing(self, citeproc):
""" If no abstract, assert blank """ del citeproc['abstract'] assert self.test_class._get_abstract(citeproc) == '' def test_get_abstract_escaping(self, citeproc): """ Must do some escaping, e.g. we sometimes get some jats tags """ # We wrap the c...
# Copyright 2020 The Pigweed Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the Licens
e. You may obtain a copy of # the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. """Runs the main function in detokenize.py.""" from pw_tokenizer import detokenize detokeniz...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("migrations", "0002_second")] operations = [ migrations.CreateModel( "OtherAuthor", [ ("id", mode...
ls.SlugField(null=True)), ("age", models.IntegerField(default
=0)), ("silly_field", models.BooleanField(default=False)), ], ), ]
#!/usr/bin/env python3 import os, sys, signal, argparse, configparser, traceback, time from contextlib import closing from ananas import PineappleBot import ananas.default # Add the cwd to the module search path so that we can load user bot classes sys.path.append(os.getcwd()) bots = [] def shutdown_all(signum, fram...
rom {0} import {1}; bots.append({1}('{2}', name='{3}', interactive={4}, verbose={5}))" .format(module, botclass, args.config, bot, args.interactive, args.verbose)) except ModuleNotFoundError as e: print("{}: encountered the following error loading module {}:".format(pro
g, module)) print("{}: the error was: {}".format(prog, e)) print("{}: skipping {}!".format(prog, bot)) continue except Exception as e: print("{}: fatal exception loading bot {}: {}\n{}".format(prog, bot, repr(e), traceback.format_exc())) continue ...
#!/usr/bin/env python """ Copyright (c) 2020 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
el(logging.DEBUG) cocotb.start_soon(Clock(dut.gtx_clk, 8, units="ns").start()) cocotb.start_soon(Clock(dut.logic_clk, 8, units="ns").start()) self.gmii_phy = GmiiPhy(dut.gmii_txd, dut.gmii
_tx_er, dut.gmii_tx_en, dut.mii_tx_clk, dut.gmii_tx_clk, dut.gmii_rxd, dut.gmii_rx_er, dut.gmii_rx_dv, dut.gmii_rx_clk, speed=speed) self.axis_source = AxiStreamSource(AxiStreamBus.from_prefix(dut, "tx_axis"), dut.logic_clk, dut.logic_rst) self.axis_sink = AxiStreamSink(AxiStreamBus.from_pr...
# -*- coding: utf-8 -*- from celery import Celery from server import config """ Celery configuration module. """ def make_celery(app): """ Flask integration with celery. Taken from http://flask
.pocoo.org/docs/0.12/patterns/celery/ """ celery = Celery(app.import_name, backend=config.CELERY_RESULT_BACKEND, broker=config.CELERY_BROKER_URL)
celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-09-15 15:28 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('silo', '0029_auto_20170915_0810'), ] operations = ...
workflowlevel1', ), migrations.AddField( model_name='silo', name='workflowlevel1', field=models.ManyToManyField(blank=True, null=True, to='silo.WorkflowLevel1'), ), migrations.AlterField( model_name='tolauser', name='workflowlev...
ADE, to='silo.WorkflowLevel1'), ), migrations.AlterField( model_name='workflowlevel2', name='workflowlevel1', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='silo.WorkflowLevel1'), ), ]
# Copyright (c) 2008 Mikeal Rogers # # 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 agre...
equest to use to construct the RequestContext for rendering this template. If not supplied, the current request will be used. """ template_name = get_template_path(template_name) context_instance = Context(dictionary) # add dictionary to context_instance context_instance.update(diction...
pse context_instance to a single dictionary for mako context_dictionary = {} context_instance['settings'] = settings context_instance['EDX_ROOT_URL'] = settings.EDX_ROOT_URL context_instance['marketing_link'] = marketing_link context_instance['is_any_marketing_link_set'] = is_any_marketing_link_set ...
import random import re import vsphere_inventory as vsphere from os.path import join, dirname try: import json except ImportError: import simplejson as json def readNamesFrom(filepath): with open(filepath) as f: return f.readlines() def randomName(lefts, rights): left = random.choice(lefts)....
name = randomName(leftSides, rightSides) if not nodeExists(knownNames, name): return name else: print('Failed to generate a new, unique, name after 10 attempts') exit(2) if __name__ == '__main__': parser = vsphere.argparser() args = parser.parse_args() vs =...
ssword) vimSession = vsphere.vimLogin(vs) vms = vsphere.vmsAtPath(vs, vimSession, args.path) vmList = [vm['hostname'] for vm in vms] newName = generateName(vmList) print(newName)
# -*- coding: utf-8 -*- # # This file is part of PyGaze - the open-source toolbox for eye tracking # # PyGaze is a Python module for easily creating gaze contingent experiments # or other software (as well as non-gaze contingent experiments/software) # Copyright (C) 2012-2013 Edwin S. Dalmaijer # # ...
# but WITHOUT ANY WARRANTY; without even the implied warranty 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, see <http://www.gnu.org/licenses/> from pygaze.sound import Sound
# Autogenerated with SMOP version 0.23 # main.py ../../assessing-mininet/MATLAB/load_function.m ../../assessing-mininet/MATLAB/process_complete_test_set.m ../../assessing-mininet/MATLAB/process_single_testfile.m ../../assessing-mininet/MATLAB/ProcessAllLogsMain.m from __future__ import division from numpy import arang...
range(0,len(pktloss) - 1),pktloss,'-') # title('Packet loss') # xlabel('time [s]') # ylabel('[pps]') # axis(cat(sort(cat(0,max(t_conv))),sort(cat(round_(max(pktloss)) + 1,round_(min(pktloss)) - 1)))) # grid('on') # saveas(packetloss_picture,strcat('pl_',current_picture_fi...
straffic) process_single_testfile(load_octave_decoded_file_as_matrix('/tmp/octave.dat'),'pic.jpg',"jpg")
""" Plugin for ResolveURL Copyright (C) 2020 gujal This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later ve
rsion. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty 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 t...
eric from resolveurl.plugins.lib import helpers class OoglyResolver(ResolveGeneric): name = "oogly.io" domains = ['oogly.io'] pattern = r'(?://|\.)(oogly\.io)/(?:embed-)?([0-9a-zA-Z]+)' def get_media_url(self, host, media_id): return helpers.get_media_url(self.get_url(host, media_id), ...
from audio_pipeline.util import Tag import re from audio_pipeline.util import Exceptions class BaseTag(Tag.Tag): def extract(self): super().extract() if self._value is not None: self._value = self._value[0] def set(self, value=Tag.CurrentTag): if value is not Tag.CurrentT...
ype = "releasetype" _media_format = "media" # track-level serialization names _title = "title" _artist = "artist" _disc_total = "disctotal" _disc_total_picard = "totaldiscs" _disc_num = "discnumber" _track_total = "tracktotal" _track_total_picard = "totaltracks" _track_num =...
## # release-level tags ################ @classmethod def album(cls, tags): tag = BaseTag(cls._album_name, cls._album, tags) return tag @classmethod def album_artist(cls, tags): tag = BaseTag(cls._album_artist_name, cls._album_artist, tags) return tag @cl...
from django.http impor
t Http404 from django.shortcuts import render from directory.forms import SearchForm def home(request): searchform = SearchForm() return render(request, 'onigiri/index.html',
{'searchform' : searchform})
#!/usr/bin/env python from raspledstrip.ledstrip import * from raspledstrip.animation import * from raspledstrip.color import Color import requests import json import time import sys import traceback # Things that should be configurable ledCount = 32 * 5 api = 'http://lumiere.lighting/' waitTime = 6 class Lumiere: ...
.currentID = None self.ledArray = [] self.waitTime = waitTime self.led = LEDStrip(ledCount) self.led.all_off() def listen(self): """ Handles the continual checking. "
"" while True: try: self.queryLights() time.sleep(self.waitTime) except (KeyboardInterrupt, SystemExit): raise except: print traceback.format_exc() def updateLights(self): """ Change the lights. """ self.fillArray() # Animate anim = Fire...
from django.test import TestCase, TransactionTestCase from django.contrib.auth.models import Group, User from django.http import HttpRequest, QueryDict from hs_core.hydroshare import resource from hs_core import hydroshare from hs_script_resource.models import ScriptSpecificMetadata, ScriptResource from hs_script_re...
element_name="ScriptSpecificMetadata", request=request) self.assertTrue(data["is_valid"]) request.POST = None data = script
_metadata_pre_update_handler(sender=ScriptResource, element_name="ScriptSpecificMetadata", request=request) self.assertFalse(data["is_valid"]) def test_bulk_metadata_update(self): # here we are test...
""" --- Day 25: The Halting Problem --- Following the twisty passageways deeper and deeper into the CPU, you finally reach the core of the computer. Here, in the expansive central chamber, you find a grand apparatus that fills the entire room, suspended nanometers above your head. You had always imagined CPUs to be ...
ksum is 3. Recreate the Turing machine and save the computer! What is the diagnostic checksum it produces once it's working again
? --- Part Two --- The Turing machine, and soon the entire computer, springs back to life. A console glows dimly nearby, awaiting your command. > reboot printer Error: That command requires priority 50. You currently have priority 0. You must deposit 50 stars to increase your priority to the required level. The co...