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.""" visa_electron_string = '4175004688713760' self.assertTrue(formatter.is_visa_electron(visa_electron_string)) def test_mastercard_number(self): """should identify mastercard card numbers.""" mastercard_number = 5409219472999830 self.assertTrue(formatter.is_mastercard(mastercard_number)) def test_mastercard_number_string(self): """should identify mastercard card number strings.""" mastercard_string = '5409219472999830' self.assertTrue(formatter.is_mastercard(mastercard_string)) def test_amex_number(self): """should identify american express card numbers.""" amex_number = 374619657687666 self.assertTrue(formatter.is_amex(amex_number)) def test_amex_number_string(self): """should identify american express card number strings.""" amex_string = '374619657687666' self.assertTrue(formatter.is_amex(amex_string)) def test_maestro_number(self): """should identify maestro card numbers.""" maestro_number = 6304236404755563 self.assertTrue(formatter.is_maestro(maestro_number)) def test_maestro_number_string(self): """should identify maestro card number strings.""" maestro_string = '6304236404755563' self.assertTrue(formatter.is_maestro(maestro_string)) def test_discover_number(self): """should identify discovery card numbers.""" discover_number = 6011359876556543 self.assertTrue(formatter.is_discover(discover_number)) def test_discover_number_string(self): """should identify discovery card number strings.""" discover_string = '6011359876556543' self.assertTrue(formatter.is_discover(discover_string)) def test_unknown_formats(self): """should return none for unknown card formats.""" unknown = 1234567890 self.assertEqual(formatter.get_format(unknown), []) def test_single_format_of_number(self): """should get the format of a card number.""" number = 5409219472999830 self.assertEqual(formatter.get_format(number), ['mastercard']) def test_dual_formats_of_number(self): """should get multiple formats of a card number.""" number = 4508077077058854 self.assertEqual(formatter.get_format(number), ['visa', 'visa electron'])
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) # any later version. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru, modulation_utils2 from gnuradio import usrp from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser from gnuradio import usrp_options import random import struct import sys # from current dir from receive_path import receive_path from pick_bitrate2 import pick_rx_bitrate try: from gnuradio.qtgui import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Please install gr-qtgui." sys.exit(1) try: from qt_rx_window2 import Ui_DigitalWindow except ImportError: print "Error: could not find qt_rx_window2.py:" print "\tYou must first build this from qt_rx_window2.ui with the following command:" print "\t\"pyuic4 qt_rx_window2.ui -o qt_rx_window2.py\"" sys.exit(1) #import os #print os.getpid() #raw_input('Attach and press enter: ') # //////////////////////////////////////////////////////////////////// # Define the QT Interface and Control Dialog # //////////////////////////////////////////////////////////////////// class dialog_box(QtGui.QMainWindow): def __init__(self, snkRxIn, snkRx, fg, parent=None): QtGui.QWidget.__init__(self, parent) self.gui = Ui_DigitalWindow() self.gui.setupUi(self) self.fg = fg self.set_frequency(self.fg.frequency()) self.set_gain(self.fg.gain()) self.set_decim(self.fg.decim()) self.set_gain_clock(self.fg.rx_gain_clock()) self.set_gain_phase(self.fg.rx_gain_phase()) self.set_gain_freq(self.fg.rx_gain_freq()) # Add the qtsnk widgets to the hlayout box self.gui.sinkLayout.addWidget(snkRxIn) self.gui.sinkLayout.addWidget(snkRx) # Connect up some signals self.connect(self.gui.freqEdit, QtCore.SIGNAL("editingFinished()"), self.freqEditText) self.connect(self.gui.gainEdit, QtCore.SIGNAL("editingFinished()"), self.gainEditText) self.connect(self.gui.decimEdit, QtCore.SIGNAL("editingFinished()"), self.decimEditText) self.connect(self.gui.gainClockEdit, QtCore.SIGNAL("editingFinished()"), self.gainClockEditText) self.connect(self.gui.gainPhaseEdit, QtCore.SIGNAL("editingFinished()"), self.gainPhaseEditText) self.connect(self.gui.gainFreqEdit, QtCore.SIGNAL("editingFinished()"), self.gainFreqEditText) # Build a timer to update the packet number and PER fields self.update_delay = 250 # time between updating packet rate fields self.pkt_timer = QtCore.QTimer(self) self.connect(self.pkt_timer, QtCore.SIGNAL("timeout()"), self.updatePacketInfo) self.pkt_timer.start(self.update_delay) # Accessor functions for Gui to manipulate receiver parameters def set_frequency(self, fo): self.gui.freqEdit.setText(QtCore.QString("%1").arg(fo)) def set_gain(self, gain): self.gui.gainEdit.setText(QtCore.QString("%1").arg(gain)) def set_decim(self, decim): self.gui.decimEdit.setText(QtCore.QString("%1").arg(decim)) def set_gain_clock(self, gain): self.gui.gainClockEdit.setText(QtCore.QString("%1").arg(gain)) def set_gain_phase(self, gain_phase): self.gui.gainPhaseEdit.setText(QtCore.QString("%1").arg(gain_phase)) def set_gain_freq(self, gain_freq): self.gui.gainFreqEdit.setText(QtCore.QString("%1").arg(gain_freq)) def freqEditText(self): try: freq = self.gui.freqEdit.text().toDouble()[0] self.fg.set_freq(freq) except RuntimeError: pass def gainEditText(self): try: gain = self.gui.gainEdit.text().toDouble()[0] self.fg.set_gain(gain) except RuntimeError: pass def decimEditText(self): try: decim = self.gui.decimEdit.text().toInt()[0] self.fg.set_decim(decim) except RuntimeError: pass def gainPhaseEditText(self): try: gain_phase = self.gui.gainPhaseEdit.text().toDouble()[0] self.fg.set_rx_gain_phase(gain_phase) except RuntimeError: pass def gainClockEditText(self): try: gain = self.gui.gainClockEdit.text().toDouble()[0] self.fg.set_rx_gain_clock(gain) except RuntimeError: pass def gainFreqEditText(self): try: gain = self.gui.gainFreqEdit.text().toDouble()[0] self.fg.set_rx_gain_freq(gain) except RuntimeError: pass # Accessor function for packet error reporting def updatePacketInfo(self): # Pull these globals in from the main thread global n_rcvd, n_right, pktno per = float(n_rcvd - n_right)/float(pktno) self.gui.pktsRcvdEdit.setText(QtCore.QString("%1").arg(n_rcvd)) self.gui.pktsCorrectEdit.setText(QtCore.QString("%1").arg(n_right)) self.gui.perEdit.setText(QtCore.QString("%1").arg(per, 0, 'e', 4)) # //////////////////////////////////////////////////////////////////// # Define the GNU Radio Top Block # //////////////////////////////////////////////////////////////////// class my_top_block(gr.top_block): def __init__(self, demodulator, rx_callback, options): gr.top_block.__init__(self) self._rx_freq = options.rx_freq # receiver's center frequency self._rx_gain = options.rx_gain # receiver's gain self._rx_subdev_spec = options.rx_subdev_spec # daughterboard to use self._decim = options.decim # Decimating rate for the USRP (prelim) self._bitrate = options.bitrate self._samples_per_symbol = options.samples_per_symbol self._demod_class = demodulator self.gui_on = options.gui if self._rx_freq is None: sys.stderr.write("-f FREQ or --freq FREQ or --rx-freq FREQ must be specified\n") raise SystemExit # Set up USRP source self._setup_usrp_source(options) # copy the final answers back into options for use by demodulator options.samples_per_symbol = self._samples_per_symbol options.bitrate = self._bitrate options.decim = self._decim ok = self.set_freq(self._rx_freq) if not ok: print "Failed to set Rx frequency to %s" % (e
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_clock = self.rxpath.packet_receiver._demodulator._timing_alpha
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_in = self.u.adc_rate() / self.d
parano/databricks_notebooks
notebooks/Users/chaoyu@databricks.com/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 request.""" if request.user.is_authenticated():
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 constants pi = tf.constant(np.pi) two = tf.constant(2, tf.float32) # our first computation graph! 2*pi two_pi = t
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 is pi*r^2 area = tf.multiply(pi, radius_squared) # start our session and run our circumference and area computation graphs with tf.Sess
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 " "approximately %s and %s, respectively") % (r, c, a))
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 <vkozhukalov@mirantis.com> # # 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 the License. # # 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 this program. If not, see <http://www.gnu.org/licenses/>. from base64 import b64encode from cStringIO import StringIO from gzip import GzipFile import commands, os TEMPLATE_FILE = ( "sh -c 'filename=${1}; shift; echo ${0} | base64 --decode | " "gunzip -c > ${filename} && chmod %(mode)s ${filename}' " "%(content64)s %(destfile)s" ) TEMPLATE_COMMAND = ( "sh -c 'echo ${0} | base64 --decode | gunzip -c | sh -' %(content64)s" ) TEMPLATE_FILE_PLAIN = ( "sh -c 'filename=${1}; shift; echo ${0} | base64 --decode " "> ${filename} && chmod %(mode)s ${filename}' " "%(content64)s %(destfile)s" ) TEMPLATE_COMMAND_PLAIN = ( "sh -c 'echo ${0} | base64 --decode | sh -' %(content64)s" ) def base64_gzip(content, gzip=True): """ This method returns content gzipped and then base64 encoded so such line can be inserted into preseed file """ if gzip: gzipped = StringIO() gzip_file = GzipFile(fileobj=gzipped, mode="wb", compresslevel=9) gzip_file.wri
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() except: return "" else: return content return source def get
_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, source_method, True), 'destfile': destfile, } else: return TEMPLATE_FILE_PLAIN % { 'mode': mode, 'content64': get_content64(source, source_method, False), 'destfile': destfile, } def late_command(source, source_method='file', gzip=True): if gzip: return TEMPLATE_COMMAND % { 'content64': get_content64(source, source_method, True) } else: return TEMPLATE_COMMAND_PLAIN % { 'content64': get_content64(source, source_method, False) }
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 program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import time import torch import torch.autograd.profiler as profiler from dendritic_speed_experiments import OneSegmentDendriticLayer from models import DendriticMLP, SparseMLP from nupic.research.frameworks.pytorch.model_utils import count_nonzero_params from nupic.research.frameworks.pytorch.models.common_models import Standa
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: with profiler.record_function("model_inference"): res = model(dummy_tensor, dummy_context) else: s = time.time() with profiler.profile(record_shapes=True, use_cuda=use_cuda) as prof: with profiler.record_function("model_inference"): res = model(dummy_tensor) wall_clock += time.time() - s print("Wall clock:", wall_clock / epochs) if device.type == "cuda": print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=10)) else: print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=10)) dense_params, sparse_params = count_nonzero_params(model) print(f"Total params:{dense_params}, non-zero params:{sparse_params}") if res.sum() == 0: # Just to make Python think we need res print(res.sum()) return wall_clock / epochs if __name__ == "__main__": if torch.cuda.is_available(): device = torch.device("cuda") else: device = torch.device("cpu") dim_context = 10 dendritic_net_ff_input_dim = 11 non_dendritic_net_input_dim = dendritic_net_ff_input_dim + dim_context output_dim = 10 dendrite_net = DendriticMLP( hidden_sizes=(2048, 2048, 2048), input_size=dendritic_net_ff_input_dim, output_dim=output_dim, k_winners=True, relu=False, k_winner_percent_on=0.1, dim_context=dim_context, num_segments=(1, 1, 1), sparsity=0.5, dendritic_layer_class=OneSegmentDendriticLayer ).to(device) dense_net = StandardMLP( input_size=non_dendritic_net_input_dim, num_classes=output_dim, hidden_sizes=(2048, 2048, 2048), ).to(device) sparse_net = SparseMLP( input_size=non_dendritic_net_input_dim, output_dim=output_dim, hidden_sizes=(2048, 2048, 2048), linear_activity_percent_on=(0.1, 0.1, 0.1), linear_weight_percent_on=(0.5, 0.5, 0.5), k_inference_factor=1.0, use_batch_norm=False, ).to(device) print("=================== DENSE NETWORK =====================") print(dense_net) dense_time = func(dense_net, input_size=non_dendritic_net_input_dim, device=device) print("\n\n=================== SPARSE NETWORK =====================") print(sparse_net) sparse_time = func(sparse_net, input_size=non_dendritic_net_input_dim, device=device) print("\n\n=================== SPARSE DENDRITIC NETWORK =====================") print(dendrite_net) dendrite_time = func(dendrite_net, input_size=dendritic_net_ff_input_dim, device=device, dendrite=True) print(f"Ratio of sparse to dense: {sparse_time/dense_time}") print(f"Ratio of dendritic to dense: {dendrite_time/dense_time}")
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 GeventWebSocketClient(object): def __init__(self, environ, fd, send_event, send_queue, recv_event, recv_queue, timeout=5): self.environ = environ self.fd = fd self.send_event = send_event self.send_queue = send_queue self.recv_event = recv_event self.recv_queue = recv_queue self.timeout = timeout self.id = str(uuid.uuid1()) self.connected = True def send(self, msg, binary=True): if binary: return self.send_binary(msg) self.send_queue.put(msg) self.send_event.set() def send_binary(self, msg): self.send_queue.put(msg) self.send_event.set() def receive(self): return self.recv() def recv(self): return self.recv_queue.get() def close(self): self.connected = False class GeventWebSocketMiddleware(WebSocketMiddleware): client = GeventWebSocketClient def __call__(self, environ, start_response): urls = self.websocket.url_map.bind_to_environ(environ) try: endpoint, args = urls.match() handler = self.websocket.view_functions[endpoint] except HTTPException: handler = None if not handler or 'HTTP_SEC_WEBSOCKET_KEY' not in environ: return self.ws
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_queue = Queue() # create websocket client client = self.client(environ
, 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.timeout` seconds to allow ping to be sent select([client.fd], [], [], client.timeout) recv_event.set() listening = spawn(listener, client) while True: if not client.connected: recv_queue.put(None) listening.kill() handler.join(client.timeout) return '' # wait for event to draw our attention wait([handler, send_event, recv_event], None, 1) # handle send events if send_event.is_set(): try: while True: uwsgi.websocket_send(send_queue.get_nowait()) except Empty: send_event.clear() except IOError: client.connected = False # handle receive events elif recv_event.is_set(): recv_event.clear() try: message = True # More than one message may have arrived, so keep reading # until an empty message is read. Note that select() # won't register after we've read a byte until all the # bytes are read, make certain to read all the data. # Experimentally, not putting the final empty message # into the queue caused websocket timeouts; theoretically # this code can skip writing the empty message but clients # should be able to ignore it anyway. while message: message = uwsgi.websocket_recv_nb() recv_queue.put(message) listening = spawn(listener, client) except IOError: client.connected = False # handler done, we're outta here elif handler.ready(): listening.kill() return '' class GeventWebSocket(WebSocket): middleware = GeventWebSocketMiddleware def init_app(self, app): aggressive = app.config.get('UWSGI_WEBSOCKET_AGGRESSIVE_PATCH', True) patch_all(aggressive=aggressive) super(GeventWebSocket, self).init_app(app)
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 import assert_true, assert_equal # pylint: disable=E0611 from opaque_keys.edx.locations import SlashSeparatedCourseKey from courseware.tests.modulestore_config import TEST_DATA_MIXED_MODULESTORE from django_comment_client.base import views from django_comment_client.tests.unicode import UnicodeTestMixin from django_comment_common.models import Role, FORUM_ROLE_STUDENT from django_comment_common.utils import seed_permissions_roles from student.tests.factories import CourseEnrollmentFactory, UserFactory from util.testing import UrlResetMixin from xmodule.modulestore.tests.factories import CourseFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase log = logging.getLogger(__name__) CS_PREFIX = "http://localhost:4567/api/v1" class MockRequestSetupMixin(object): def _create_repsonse_mock(self, data): return Mock(text=json.dumps(data), json=Mock(return_value=data))\ def _set_mock_request_data(self, mock_request, data): mock_request.return_value = self._create_repsonse_mock(data) @override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE) @patch('lms.lib.comment_client.utils.requests.request') class ViewsTestCase(UrlResetMixin, ModuleStoreTestCase, MockRequestSetupMixin):
@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(ViewsTestCase, self).setUp(creat
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', self.course_id.to_deprecated_string()) # Patch the comment client user save method so it does not try # to create a new cc user when creating a django user with patch('student.models.cc.User.save'): uname = 'student' email = 'student@edx.org' password = 'test' # Create the user and make them active so we can log them in. self.student = User.objects.create_user(uname, email, password) self.student.is_active = True self.student.save() # Enroll the student in the course CourseEnrollmentFactory(user=self.student, course_id=self.course_id) self.client = Client() assert_true(self.client.login(username='student', password='test')) def test_create_thread(self, mock_request): mock_request.return_value.status_code = 200 self._set_mock_request_data(mock_request, { "thread_type": "discussion", "title": "Hello", "body": "this is a post", "course_id": "MITx/999/Robot_Super_Course", "anonymous": False, "anonymous_to_peers": False, "commentable_id": "i4x-MITx-999-course-Robot_Super_Course", "created_at": "2013-05-10T18:53:43Z", "updated_at": "2013-05-10T18:53:43Z", "at_position_list": [], "closed": False, "id": "518d4237b023791dca00000d", "user_id": "1", "username": "robot", "votes": { "count": 0, "up_count": 0, "down_count": 0, "point": 0 }, "abuse_flaggers": [], "type": "thread", "group_id": None, "pinned": False, "endorsed": False, "unread_comments_count": 0, "read": False, "comments_count": 0, }) thread = { "thread_type": "discussion", "body": ["this is a post"], "anonymous_to_peers": ["false"], "auto_subscribe": ["false"], "anonymous": ["false"], "title": ["Hello"], } url = reverse('create_thread', kwargs={'commentable_id': 'i4x-MITx-999-course-Robot_Super_Course', 'course_id': self.course_id.to_deprecated_string()}) response = self.client.post(url, data=thread) assert_true(mock_request.called) mock_request.assert_called_with( 'post', '{prefix}/i4x-MITx-999-course-Robot_Super_Course/threads'.format(prefix=CS_PREFIX), data={ 'thread_type': 'discussion', 'body': u'this is a post', 'anonymous_to_peers': False, 'user_id': 1, 'title': u'Hello', 'commentable_id': u'i4x-MITx-999-course-Robot_Super_Course', 'anonymous': False, 'course_id': u'MITx/999/Robot_Super_Course', }, params={'request_id': ANY}, headers=ANY, timeout=5 ) assert_equal(response.status_code, 200) def test_delete_comment(self, mock_request): self._set_mock_request_data(mock_request, { "user_id": str(self.student.id), "closed": False, }) test_comment_id = "test_comment_id" request = RequestFactory().post("dummy_url", {"id": test_comment_id}) request.user = self.student request.view_name = "delete_comment" response = views.delete_comment(request, course_id=self.course.id.to_deprecated_string(), comment_id=test_comment_id) self.assertEqual(response.status_code, 200) self.assertTrue(mock_request.called) args = mock_request.call_args[0] self.assertEqual(args[0], "delete") self.assertTrue(args[1].endswith("/{}".format(test_comment_id))) def _setup_mock_request(self, mock_request, include_depth=False): """ Ensure that mock_request returns the data necessary to make views function correctly """ mock_request.return_value.status_code = 200 data = { "user_id": str(self.student.id), "closed": False, } if include_depth: data["depth"] = 0 self._set_mock_request_data(mock_request, data) def _test_request_error(self, view_name, view_kwargs, data, mock_request): """ Submit a request against the given view with the given data and ensure that the result is a 400 error and that no data was posted using mock_request """ self._setup_mock_request(mock_request, include_depth=(view_name == "create_sub_comment")) response = self.client.post(reverse(view_name, kwargs=view_kwargs), data=data) self.assertEqual(response.status_code, 400) for call in mock_request.call_args_list: self.assertEqual(call[0][0].lower(), "get") def test_create_thread_no_title(self, mock_request): self._test_request_error( "create_thread", {"commentable_id": "dummy", "course_id": self.course_id.to_deprecated_string()}, {"body": "foo"}, mock_request ) def test_create_thread_empty_title(self, mock_request): self._test_request_error( "create_thread", {"commentable_id": "dummy", "course_id": self.course_id.to_deprecated_string()}, {"body": "foo", "title": " "}, mock_request ) def test_create_thread_no_body(self, mock_request): self._test_request_error( "create_thread", {"commentable_id": "dummy", "course_id": self.course_id.to_deprecated_string()}, {"title": "foo"}, mock_request )
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 password: self.user_cache = authenticate(username=username, password=password) if self.user_cache is None: raise forms.ValidationError( self.error_messages['invalid_login'], code='valid_login',
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 <tkeffer@gmail.com> # # 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 seconds: # Useful for calculating 'uptime.' launchtime_ts = time.time() # Set to true for extra debug information: debug = False # Exit return codes CMD_ERROR = 2 CONFIG_ERROR = 3 IO_ERROR = 4 DB_ERROR = 5 # Constants used to indicate a unit system: METRIC = 0x10 METRICWX = 0x11 US = 0x01 # ============================================================================= # Define possible exceptions that could get thrown. # ============================================================================= class WeeWxIOError(IOError): """Base class of exceptions thrown when encountering an input/output error with the hardware.""" class WakeupError(WeeWxIOError): """Exception thrown when unable to wake up or initially connect with the hardware.""" class CRCError(WeeWxIOError): """Exception thrown when unable to pass a CRC check.""" class RetriesExceeded(WeeWxIOError): """Exception thrown when max retries exceeded.""" class HardwareError(Exception): """Exception thrown when an error is detected in the hardware.""" class UnknownArchiveType(HardwareError): """Exception thrown after reading an unrecognized archive type.""" class UnsupportedFeature(Exception): """Exception thrown when attempting to access a feature that is not supported (yet).""" class ViolatedPrecondition(Exception): """Exception thrown when a function is called with violated preconditions.""" class StopNow(Exception): """Exception thrown to stop the engine.""" class UnknownDatabase(Exception): """Exception thrown when attempting to use an unknown database.""" class UnknownDatabaseType(Exception): """Exception thrown when attempting to use an unknown database type.""" class UnknownBinding(Exception): """Exception thrown when attempting to use an unknown data binding.""" class UnitError(ValueError): """Exception thrown when there is a mismatch in unit systems.""" class UnknownType(ValueError): """Exception thrown for an unknown observation type""" class UnknownAggregation(ValueError): """E
xception thrown for an unknown aggregation type""" class CannotCalculate(ValueError): """Exception raised when a type cannot be calculated.""" # ============================================================================= # Possible event types. # ============================================================================= class STARTUP(object): """Event issued when the engine first starts up. Services have been load
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): """Event issued in the main loop, right after a new LOOP packet has been processed. Generally, it is used to throw an exception, breaking the main loop, so the console can be used for other things.""" class END_ARCHIVE_PERIOD(object): """Event issued at the end of an archive period.""" class NEW_ARCHIVE_RECORD(object): """Event issued when a new archive record is available. The event contains attribute 'record', which is the new archive record.""" class POST_LOOP(object): """Event issued right after the main loop has been broken. Services hook into this to access the console for things other than generating LOOP packet.""" # ============================================================================= # Service groups. # ============================================================================= # All existent service groups and the order in which they should be run: all_service_groups = ['prep_services', 'data_services', 'process_services', 'xtype_services', 'archive_services', 'restful_services', 'report_services'] # ============================================================================= # Class Event # ============================================================================= class Event(object): """Represents an event.""" def __init__(self, event_type, **argv): self.event_type = event_type for key in argv: setattr(self, key, argv[key]) def __str__(self): """Return a string with a reasonable representation of the event.""" et = "Event type: %s | " % self.event_type s = "; ".join("%s: %s" %(k, self.__dict__[k]) for k in self.__dict__ if k!="event_type") return et + s def require_weewx_version(module, required_version): """utility to check for version compatibility""" from distutils.version import StrictVersion if StrictVersion(__version__) < StrictVersion(required_version): raise UnsupportedFeature("%s requires weewx %s or greater, found %s" % (module, required_version, __version__))
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') infrafilter.filter(r
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.test.logs_test', record.fullModuleName) def test_filters_by_module_name(self): record = logging.makeLogRecord({}) infrafilter = logs.InfraFilter( 'US/Pacific', module_name_blacklist=r'^other\.module') self.assertTrue(infrafilter.filter(record)) infrafilter = logs.InfraFilter( 'US/Pacific', module_name_blacklist=r'^infra_libs\.logs\.test\.logs_test$') self.assertFalse(infrafilter.filter(record))
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): ''' Loads a KAM by name. This function will sleep until the KAM's loadStatus is 'COMPLETE'. ''' def call(): ''' Load the KAM and return result. Exit with error if 'loadStatus' is FAILED. ''' kam = client.create('Kam') kam.name = kam_name result = client.service.LoadKam(kam) status = result['loadStatus'] if status == 'FAILED': print 'FAILED!' print sys.exc_info()[1] exit_failure() return result # load kam and wait for completion result = call() while result['loadStatus'] != 'COMPLETE': time.sleep(0.5) result = call() return result['handle'] if __name__ == '__main__': from sys import argv, exit, stderr if len(argv) != 3: msg = 'usage: find-kam-node.py <kam name> <source_bel_term>\n' stderr.write(msg) exit(1) # unpack command-line arguments; except the first script name argument (kam_name, source_term) = argv[1:] client = WS('http://localhost:8080/openbel-ws/belframework
.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) if len(result) == 1 and result[0]: the_node = result[0] print "foun
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).""" try: dummy = s + " " return True except TypeError: return False def list_strings(arg): """ Always return a list of strings, given a string or list of strings as input. :Examples: >>> list_strings('A single string') ['A single string'] >>> list_strings(['A single string in a list']) ['A single string in a list'] >>> list_strings(['A','list','of','strings']) ['A', 'list', 'of', 'strings'] """ if is_string(arg): return [arg] else: return arg class WildCard(object): """ This object provides an easy-to-use interface for filename matching with shell patterns (fnmatch). .. example: >>> w = WildCard("*.nc|*.pdf") >>> w.filter(["foo.nc", "bar.pdf", "hello.txt"]) ['foo.nc', 'bar.pdf'] >>> w.filter("foo.nc") ['foo.nc'] """ def __init__(self, wildcard, sep="|"): """ Args: wildcard: String of tokens separated by sep. Each token represents a pattern. sep: Separator for shell patterns. """ self.pats = ["*"] if wildcard: self.pats = wildcard.split(sep) def __str__(self): return "<%s, patterns = %s>" % (self.__class__.__name__, self.pats) def filter(self, names): """ Returns a list with the names matching the pattern. """ names = list_strings(names) fnames = [] for f in names: for pat in self.pats: if fnmatch.fnmatch(f, pat): fnames.append(f) return fnames def match(self, name): """ Returns True if name matches one of the patterns. """ for pat in self.pats: if fnmatch.fnmatch(name, pat): return True return False def robodoc_dheader(dirname): """Return a string with the ROBODOC header for the specified directory.""" dirname = os.path.basename(dirname) return """\ !!****d* ABINIT/%(dirname)s !! NAME !! %(dirname)s !! !! DESCRIPTION !! FIXME: Description is missing !! !! COPYRIGHT !! Copyright (C) 2020-2021 ABINIT Group !! This file is distributed under the terms of the !! GNU General Public License, see ~abinit/COPYING !! or http://www.gnu.org/copyleft/gpl.txt . !! For the initials of contributors, see ~abinit/doc/developers/contributors.txt . !! !! CHILDREN """ % locals() def mkrobodoc_files(top): """ Generate the ROBODOC files in all the ABINIT directories located within the top level directory
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 = "_" + dirname + "_" if robo_dfile not in filenames: # Not an abinit dir. wrong_dirpaths.append(os.path.abspath(dirpath)) continue robo_dfile = os.path.abspath(os.path.join(dirpath, robo_dfile)) with open(robo_dfile, "r") as f: robotext = [] for line in f: robotext.append(line.strip()) if line.startswith("!! CHILDREN"): break else: raise ValueError("File %s does not have a valid '!! CHILDREN' section'" % robo_dfile) # Get source files, sort them in alphabetical order and generate new robodoc file. src_files = wildcard.filter(os.listdir(dirpath)) if not src_files: continue src_files = sorted(src_files) robotext += ["!! " + src_file for src_file in src_files] robotext += ["!!", "!!***"] #for line in robotext: print(line) # Write new robodoc file. with open(robo_dfile, "w") as f: f.write("\n".join(robotext) + "\n") if wrong_dirpaths: # Some dirs should not have a ROBODOC file. # This code does not work if we have the same basename but oh well. EXCLUDE_BASEDIRS = set([ "src", "replacements", "01_interfaces_ext", "ptgroup_data", "incs", "libs", "mods", ]) # Remove dirs in EXCLUDE_BASEDIRS wrong_dirpaths = [d for d in wrong_dirpaths if os.path.basename(d) not in EXCLUDE_BASEDIRS] if wrong_dirpaths: print("dirs_without_files") for i, dirpath in enumerate(wrong_dirpaths): print("%d) %s" % (i, dirpath)) robodoc_dfile = os.path.join(dirpath, "_" + os.path.basename(dirpath) + "_") assert not os.path.isfile(robodoc_dfile) with open(robodoc_dfile, "w") as f: f.write(robodoc_dheader(dirpath)) return len(wrong_dirpaths) def main(): try: top = os.path.abspath(sys.argv[1]) except: raise ValueError("Top level directory must be specified.\nEx: mkrobodoc_dirs.py ./70_gw") return mkrobodoc_files(top) if __name__ == "__main__": sys.exit(main())
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 module for sre""" # update when constants are
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_EXISTS = "groupref_exists" IN = "in" IN_IGNORE = "in_ignore" INFO = "info" JUMP = "jump" LITERAL = "literal" LITERAL_IGNORE = "literal_ignore" MARK = "mark" MAX_REPEAT = "max_repeat" MAX_UNTIL = "max_until" MIN_REPEAT = "min_repeat" MIN_UNTIL = "min_until" NEGATE = "negate" NOT_LITERAL = "not_literal" NOT_LITERAL_IGNORE = "not_literal_ignore" RANGE = "range" REPEAT = "repeat" REPEAT_ONE = "repeat_one" SUBPATTERN = "subpattern" MIN_REPEAT_ONE = "min_repeat_one" # positions AT_BEGINNING = "at_beginning" AT_BEGINNING_LINE = "at_beginning_line" AT_BEGINNING_STRING = "at_beginning_string" AT_BOUNDARY = "at_boundary" AT_NON_BOUNDARY = "at_non_boundary" AT_END = "at_end" AT_END_LINE = "at_end_line" AT_END_STRING = "at_end_string" AT_LOC_BOUNDARY = "at_loc_boundary" AT_LOC_NON_BOUNDARY = "at_loc_non_boundary" AT_UNI_BOUNDARY = "at_uni_boundary" AT_UNI_NON_BOUNDARY = "at_uni_non_boundary" # categories CATEGORY_DIGIT = "category_digit" CATEGORY_NOT_DIGIT = "category_not_digit" CATEGORY_SPACE = "category_space" CATEGORY_NOT_SPACE = "category_not_space" CATEGORY_WORD = "category_word" CATEGORY_NOT_WORD = "category_not_word" CATEGORY_LINEBREAK = "category_linebreak" CATEGORY_NOT_LINEBREAK = "category_not_linebreak" CATEGORY_LOC_WORD = "category_loc_word" CATEGORY_LOC_NOT_WORD = "category_loc_not_word" CATEGORY_UNI_DIGIT = "category_uni_digit" CATEGORY_UNI_NOT_DIGIT = "category_uni_not_digit" CATEGORY_UNI_SPACE = "category_uni_space" CATEGORY_UNI_NOT_SPACE = "category_uni_not_space" CATEGORY_UNI_WORD = "category_uni_word" CATEGORY_UNI_NOT_WORD = "category_uni_not_word" CATEGORY_UNI_LINEBREAK = "category_uni_linebreak" CATEGORY_UNI_NOT_LINEBREAK = "category_uni_not_linebreak" OPCODES = [ # failure=0 success=1 (just because it looks better that way :-) FAILURE, SUCCESS, ANY, ANY_ALL, ASSERT, ASSERT_NOT, AT, BRANCH, CALL, CATEGORY, CHARSET, BIGCHARSET, GROUPREF, GROUPREF_EXISTS, GROUPREF_IGNORE, IN, IN_IGNORE, INFO, JUMP, LITERAL, LITERAL_IGNORE, MARK, MAX_UNTIL, MIN_UNTIL, NOT_LITERAL, NOT_LITERAL_IGNORE, NEGATE, RANGE, REPEAT, REPEAT_ONE, SUBPATTERN, MIN_REPEAT_ONE ] ATCODES = [ AT_BEGINNING, AT_BEGINNING_LINE, AT_BEGINNING_STRING, AT_BOUNDARY, AT_NON_BOUNDARY, AT_END, AT_END_LINE, AT_END_STRING, AT_LOC_BOUNDARY, AT_LOC_NON_BOUNDARY, AT_UNI_BOUNDARY, AT_UNI_NON_BOUNDARY ] CHCODES = [ CATEGORY_DIGIT, CATEGORY_NOT_DIGIT, CATEGORY_SPACE, CATEGORY_NOT_SPACE, CATEGORY_WORD, CATEGORY_NOT_WORD, CATEGORY_LINEBREAK, CATEGORY_NOT_LINEBREAK, CATEGORY_LOC_WORD, CATEGORY_LOC_NOT_WORD, CATEGORY_UNI_DIGIT, CATEGORY_UNI_NOT_DIGIT, CATEGORY_UNI_SPACE, CATEGORY_UNI_NOT_SPACE, CATEGORY_UNI_WORD, CATEGORY_UNI_NOT_WORD, CATEGORY_UNI_LINEBREAK, CATEGORY_UNI_NOT_LINEBREAK ] def makedict(list): d = {} for i, item in enumerate(list): d[item] = i return d OPCODES = makedict(OPCODES) ATCODES = makedict(ATCODES) CHCODES = makedict(CHCODES) # replacement operations for "ignore case" mode OP_IGNORE = { GROUPREF: GROUPREF_IGNORE, IN: IN_IGNORE, LITERAL: LITERAL_IGNORE, NOT_LITERAL: NOT_LITERAL_IGNORE } AT_MULTILINE = { AT_BEGINNING: AT_BEGINNING_LINE, AT_END: AT_END_LINE } AT_LOCALE = { AT_BOUNDARY: AT_LOC_BOUNDARY, AT_NON_BOUNDARY: AT_LOC_NON_BOUNDARY } AT_UNICODE = { AT_BOUNDARY: AT_UNI_BOUNDARY, AT_NON_BOUNDARY: AT_UNI_NON_BOUNDARY } CH_LOCALE = { CATEGORY_DIGIT: CATEGORY_DIGIT, CATEGORY_NOT_DIGIT: CATEGORY_NOT_DIGIT, CATEGORY_SPACE: CATEGORY_SPACE, CATEGORY_NOT_SPACE: CATEGORY_NOT_SPACE, CATEGORY_WORD: CATEGORY_LOC_WORD, CATEGORY_NOT_WORD: CATEGORY_LOC_NOT_WORD, CATEGORY_LINEBREAK: CATEGORY_LINEBREAK, CATEGORY_NOT_LINEBREAK: CATEGORY_NOT_LINEBREAK } CH_UNICODE = { CATEGORY_DIGIT: CATEGORY_UNI_DIGIT, CATEGORY_NOT_DIGIT: CATEGORY_UNI_NOT_DIGIT, CATEGORY_SPACE: CATEGORY_UNI_SPACE, CATEGORY_NOT_SPACE: CATEGORY_UNI_NOT_SPACE, CATEGORY_WORD: CATEGORY_UNI_WORD, CATEGORY_NOT_WORD: CATEGORY_UNI_NOT_WORD, CATEGORY_LINEBREAK: CATEGORY_UNI_LINEBREAK, CATEGORY_NOT_LINEBREAK: CATEGORY_UNI_NOT_LINEBREAK } # flags SRE_FLAG_TEMPLATE = 1 # template mode (disable backtracking) SRE_FLAG_IGNORECASE = 2 # case insensitive SRE_FLAG_LOCALE = 4 # honour system locale SRE_FLAG_MULTILINE = 8 # treat target as multiline string SRE_FLAG_DOTALL = 16 # treat target as a single string SRE_FLAG_UNICODE = 32 # use unicode "locale" SRE_FLAG_VERBOSE = 64 # ignore whitespace and comments SRE_FLAG_DEBUG = 128 # debugging SRE_FLAG_ASCII = 256 # use ascii "locale" # flags for INFO primitive SRE_INFO_PREFIX = 1 # has prefix SRE_INFO_LITERAL = 2 # entire pattern is literal (given by prefix) SRE_INFO_CHARSET = 4 # pattern starts with character from given set if __name__ == "__main__": def dump(fp, d, prefix): for k, v in sorted(d.items(), key=lambda a: a[1]): fp.write("#define %s_%s %s\n" % (prefix, k.upper(), v)) from sys import argv try: header = argv[1] except IndexError: header = "include/corgi/constants.h" with open(header, "w") as fp: fp.write("""\ #if !defined(CORGI_CONSTANTS_H_INCLUDED) #define CORGI_CONSTANTS_H_INCLUDED /** * Secret Labs' Regular Expression Engine * * regular expression matching engine * * NOTE: This file is generated by sre_constants.py. If you need * to change anything in here, edit sre_constants.py and run it. * * Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved. * * See the _sre.c file for information on usage and redistribution. */ """) fp.write("#define SRE_MAGIC %d\n" % MAGIC) dump(fp, OPCODES, "SRE_OP") dump(fp, ATCODES, "SRE") dump(fp, CHCODES, "SRE") fp.write("#define SRE_FLAG_TEMPLATE %d\n" % SRE_FLAG_TEMPLATE) fp.write("#define SRE_FLAG_IGNORECASE %d\n" % SRE_FLAG_IGNORECASE) fp.write("#define SRE_FLAG_LOCALE %d\n" % SRE_FLAG_LOCALE) fp.write("#define SRE_FLAG_MULTILINE %d\n" % SRE_FLAG_MULTILINE) fp.write("#define SRE_FLAG_DOTALL %d\n" % SRE_FLAG_DOTALL) fp.write("#define SRE_FLAG_UNICODE %d\n" % SRE_FLAG_UNICODE) fp.write("#define SRE_FLAG_VERBOSE %d\n" % SRE_FLAG_VERBOSE) fp.write("#define SRE_INFO_PREFIX %d\n" % SRE_INFO_PREFIX) fp.write("#define SRE_INFO_LITERAL %d\n" % SRE_INFO_LITERAL) fp.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET) fp.write("""\ #endif """) # vim: tabstop=4 shiftwidth=4 expandtab softtabstop=4
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_len*self.flare # buffers the index for main card display self.
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 [Q] :: Quit Game" self.choose_action = self.make_title("Choose_Action").replace("_"," ") self.welcome2 = \ """ __ - - /, /, ,- _~, _-_- ,- _~. ,-||-, /\\,/\\, ,- _~, )/ )/ ) (' /| / /, (' /| ('||| ) /| || || (' /| / )__)__) (( ||/= || (( || (( |||--)) || || || (( ||/= ~)__)__) (( || ~|| (( || (( |||--)) ||=|= || (( || ) ) ) ( / | || ( / | ( / | ) ~|| || || ( / | /-_/-_/ -____- ( -__, -____- -____- |, \\,\\, -____- _- """ self.shop=\ """ ( ) ) ) ( ( /\ (_) / \ /\ ________[_]________ /\/ \/ \ /\ /\ ______ \ / /\/\ /\/\ / \ //_\ \ /\ \ /\/\/ \/ \ /\ / /\/\ //___\ \__/ \ \/ / \ /\/ \//_____\ \ |[]| \ /\/\/\/ //_______\ \|__| \ Welcome / \ /XXXXXXXXXX\ \ to the \ /_I_II I__I_\__________________\ Shop I_I| I__I_____[]_|_[]_____I I_II I__I_____[]_|_[]_____I I II__I I XXXXXXX I ~~~~~" "~~~~~~~~~~~~~~~~~~~~~~~~ """ self.welcome = \ """ |ZZzz ;; :: |Zzz | |Zzz ; :: o :: ; :: `:;;`:: /_\ /\ | /\ /_\ o::\ :| ::o/:: ` ::;;\`::\/ |*|_||/_\||_|*| :::o::o;::o:; :::\ ::::'` |.....|*|.....| __ o :\:::/:: ; :`::\://:: __~| .. !~! .. |~___ (~ \____ | |__ ; ____________ _____| |__ .*.|____|_|____|.*. (' ) | | o )~~~~( |^| ~~~~~ /' `\ ~) ~ ~( / ^ \ )~ o< ~~( )~~ ~ ~ ~~~( )~~ 0< ~ 0< ~~( """ self.goodbye = \ """ , / \ JL / \ TT /_____\ LJ L=====J J==L J # L\ T: T L===J \ L==J . T T--J =J L= / \ | ::|==| T ::T /---\ |===| | L====J L===J | | |H__H__H | T |H__H|__H|==| / | J===\ /:: |====|H__H__H _--^I^--_ ..|| ..| ::| :: | / / /~~|~~\ \==||===|/\ /\____|====| / / | \ \ || /__\/__\ ___ ___ | | | | | |===||| || | | :| | ~~~~~~~ | |o | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | ------- | | | ----------------------------------------------- ------- | | | ----------------------------------------------- ======= |===|===| =============================================== """ self.goodbye_mini = \ """ /| ________________ O|===|* >________________> \| """ pass def check_terminal_width(self): """Checks the terminal can fit the game""" rows, columns = subprocess.check_output(['stty', 'size']).split() check = (int(columns) >= 78 and rows >= 90) return check def make_title(self, title, center=False): """makes a pretty title""" if center: title = title.center( self.title_len, self.flare2) else: title = title.replace(" ","_") title = self.title_start + title title = title.ljust(self.title_len) title = title.replace(" ", self.flare) title = title.replace("_"," ") return title
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 import devil_env from devil.android import device_errors from devil.android.constants import file_system from devil.android.sdk import adb_wrapper from devil.android.valgrind_tools import base_tool from devil.utils import cmd_helper logger = logging.getLogger(__name__) # If passed as the device port, this will tell the forwarder to allocate # a dynamic port on the device. The actual port can then be retrieved with # Forwarder.DevicePortForHostPort. DYNAMIC_DEVICE_PORT = 0 def _GetProcessStartTime(pid): p = psutil.Process(pid) if inspect.ismethod(p.create_time): return p.create_time() else: # Process.create_time is a property in old versions of psutil. return p.create_time def _DumpHostLog(): # The host forwarder daemon logs to /tmp/host_forwarder_log, so print the end # of that. try: with open('/tmp/host_forwarder_log') as host_forwarder_log: logger.info('Last 50 lines of the host forwarder daemon log:') for line in host_forwarder_log.read().splitlines()[-50:]: logger.info(' %s', line) except Exception: # pylint: disable=broad-except # Grabbing the host forwarder log is best-effort. Ignore all errors. logger.warning('Failed to get the contents of host_forwarder_log.') def _LogMapFailureDiagnostics(device): _DumpHostLog() # The device forwarder daemon logs to the logcat, so print the end of that. try: logger.info('Last 50 lines of logcat:') for logcat_line in device.adb.Logcat(dump=True)[-50:]: logger.info(' %s', logcat_line) except (device_errors.CommandFailedError, device_errors.DeviceUnreachableError): # Grabbing the device forwarder log is also best-effort
. 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 ' 'instances.') class _FileLock(object): """With statement-aware implementation of a file lock. File locks are needed for cross-process synchronization when the multiprocessing Python module is used. """ def __init__(self, path): self._fd = -1 self._path = path def __enter__(self): self._fd = os.open(self._path, os.O_RDONLY | os.O_CREAT) if self._fd < 0: raise Exception('Could not open file %s for reading' % self._path) fcntl.flock(self._fd, fcntl.LOCK_EX) def __exit__(self, _exception_type, _exception_value, traceback): fcntl.flock(self._fd, fcntl.LOCK_UN) os.close(self._fd) class HostForwarderError(base_error.BaseError): """Exception for failures involving host_forwarder.""" def __init__(self, message): super(HostForwarderError, self).__init__(message) class Forwarder(object): """Thread-safe class to manage port forwards from the device to the host.""" _DEVICE_FORWARDER_FOLDER = (file_system.TEST_EXECUTABLE_DIR + '/forwarder/') _DEVICE_FORWARDER_PATH = ( file_system.TEST_EXECUTABLE_DIR + '/forwarder/device_forwarder') _LOCK_PATH = '/tmp/chrome.forwarder.lock' # Defined in host_forwarder_main.cc _HOST_FORWARDER_LOG = '/tmp/host_forwarder_log' _TIMEOUT = 60 # seconds _instance = None @staticmethod def Map(port_pairs, device, tool=None): """Runs the forwarder. Args: port_pairs: A list of tuples (device_port, host_port) to forward. Note that you can specify 0 as a device_port, in which case a port will by dynamically assigned on the device. You can get the number of the assigned port using the DevicePortForHostPort method. device: A DeviceUtils instance. tool: Tool class to use to get wrapper, if necessary, for executing the forwarder (see valgrind_tools.py). Raises: Exception on failure to forward the port. """ if not tool: tool = base_tool.BaseTool() with _FileLock(Forwarder._LOCK_PATH): instance = Forwarder._GetInstanceLocked(tool) instance._InitDeviceLocked(device, tool) device_serial = str(device) map_arg_lists = [[ '--adb=' + adb_wrapper.AdbWrapper.GetAdbPath(), '--serial-id=' + device_serial, '--map', str(device_port), str(host_port) ] for device_port, host_port in port_pairs] logger.info('Forwarding using commands: %s', map_arg_lists) for map_arg_list in map_arg_lists: try: map_cmd = [instance._host_forwarder_path] + map_arg_list (exit_code, output) = cmd_helper.GetCmdStatusAndOutputWithTimeout( map_cmd, Forwarder._TIMEOUT) except cmd_helper.TimeoutError as e: raise HostForwarderError( '`%s` timed out:\n%s' % (' '.join(map_cmd), e.output)) except OSError as e: if e.errno == 2: raise HostForwarderError('Unable to start host forwarder. ' 'Make sure you have built host_forwarder.') else: raise if exit_code != 0: try: instance._KillDeviceLocked(device, tool) except (device_errors.CommandFailedError, device_errors.DeviceUnreachableError): # We don't want the failure to kill the device forwarder to # supersede the original failure to map. logger.warning( 'Failed to kill the device forwarder after map failure: %s', str(e)) _LogMapFailureDiagnostics(device) formatted_output = ('\n'.join(output) if isinstance(output, list) else output) raise HostForwarderError( '`%s` exited with %d:\n%s' % (' '.join(map_cmd), exit_code, formatted_output)) tokens = output.split(':') if len(tokens) != 2: raise HostForwarderError('Unexpected host forwarder output "%s", ' 'expected "device_port:host_port"' % output) device_port = int(tokens[0]) host_port = int(tokens[1]) serial_with_port = (device_serial, device_port) instance._device_to_host_port_map[serial_with_port] = host_port instance._host_to_device_port_map[host_port] = serial_with_port logger.info('Forwarding device port: %d to host port: %d.', device_port, host_port) @staticmethod def UnmapDevicePort(device_port, device): """Unmaps a previously forwarded device port. Args: device: A DeviceUtils instance. device_port: A previously forwarded port (through Map()). """ with _FileLock(Forwarder._LOCK_PATH): Forwarder._UnmapDevicePortLocked(device_port, device) @staticmethod def UnmapAllDevicePorts(device): """Unmaps all the previously forwarded ports for the provided device. Args: device: A DeviceUtils instance. port_pairs: A list of tuples (device_port, host_port) to unmap. """ with _FileLock(Forwarder._LOCK_PATH): instance = Forwarder._GetInstanceLocked(None) unmap_all_cmd = [ instance._host_forwarder_path, '--adb=%s' % adb_wrapper.AdbWrapper.GetAdbPath(), '--serial-id=%s' % device.serial, '--unmap-all' ] try: exit_code, output = cmd_helper.GetCmdStatusAndOutputWithTimeout( unmap_all_cmd, Forwarder._TIMEOUT) except cmd_helper.TimeoutError as e: raise HostForwarderError( '`%s` timed out:\n%s' % (' '.joi
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.time() - begin)
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/. # ######################################################################################################################## # registerPrettyPrinters() ##########################################################################################
############################## 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), 'auth_srid' : 4326, 'srtext' : 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]', 'srtext14' : 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]', 'proj4' : '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ', 'spheroid' : 'WGS 84', 'name' : 'WGS 84', 'geographic' : True, 'projected' : False, 'spatialite' : True, 'ellipsoid' : (6378137.0, 6356752.3, 298.257223563), # From proj's "cs2cs -le" and Wikipedia (semi-minor only) 'eprec' : (1, 1, 9), }, {'srid' : 32140, 'auth_name' : ('EPSG', False), 'auth_srid' : 32140, 'srtext' : 'PROJCS["NAD83 / Texas South Central",GEOGCS["NAD83",DATUM["North_American_Datum_1983",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4269"]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",30.28333333333333],PARAMETER["standard_parallel_2",28.38333333333333],PARAMETER["latitude_of_origin",27.83333333333333],PARAMETER["central_meridian",-99],PARAMETER["false_easting",600000],PARAMETER["false_northing",4000000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32140"]]', 'srtext14': 'PROJCS["NAD83 / Texas South Central",GEOGCS["NAD83",DATUM["North_American_Datum_1983",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4269"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",30.28333333333333],PARAMETER["standard_parallel_2",28.38333333333333],PARAMETER["latitude_of_origin",27.83333333333333],PARAMETER["central_meridian",-99],PARAMETER["false_easting",600000],PARAMETER["false_northing",4000000],AUTHORITY["EPSG","32140"],AXIS["X",EAST],AXIS["Y",NORTH]]', 'proj4' : '+proj=lcc +lat_1=30.28333333333333 +lat_2=28.38333333333333 +lat_0=27.83333333333333 +lon_0=-99 +x_0=600000 +y_0=4000000 +ellps=GRS80 +datum=NAD83 +units=m +no_defs ', 'spheroid' : 'GRS 1980', 'name' : 'NAD83 / Texas South Central', 'geographic' : False, 'projected' : True, 'spatialite' : False, 'ellipsoid' : (6378137.0, 6356752.31414, 298.257222101), # From proj's "cs2cs -le" and Wikipedia (semi-minor only) 'eprec' : (1, 5, 10), }, ) @unittest.skipUnless(HAS_GDAL and HAS_SPATIALREFSYS, "SpatialRefSysTest needs gdal support and a spatial database") class SpatialRefSysTest(unittest.TestCase): @no_mysql def test01_retrieve(self): "Testing retrieval of SpatialRefSys model objects." for sd in test_srs: srs = SpatialRefSys.objects.get(srid=sd['srid']) self.assertEqual(sd['srid'], srs.srid) # Some of the authority names are borked on Oracle, e.g., SRID=32140. # also, Oracle Spatial seems to add extraneous info to fields, hence the # the testing with the 'startswith' flag. auth_name, oracle_flag = sd['auth_name'] if postgis or (oracle and oracle_flag): self.assertEqual(True, srs.auth_name.startswith(auth_name)) self.assertEqual(sd['auth_srid'], srs.auth_srid) # No proj.4 and different srtext on oracle backends :( if postgis: if connection.ops.spatial_version >= (1, 4, 0): srtext = sd['srtext14'] else: srtext = sd['srtext'] self.assertEqual(srtext, srs.wkt) self.assertEqual(sd['proj4'], srs.proj4text) @no_mysql def test02_osr(self): "Testing getting OSR objects from SpatialRefSys model objects." from django.contrib.gis.gdal import GDAL_VERSION for sd in test_srs: sr = SpatialRefSys.objects.get(srid=sd['srid']) self.assertEqual(True, sr.spheroid.startswith(sd['spheroid'])) self.assertEqual(sd['geographic'], sr.geographic) self.assertEqual(sd['projected'], sr.projected) if not (spatialite and not sd['spatialite']): # Can't get 'NAD83 / Texas South Central' from PROJ.4 string # on SpatiaLite self.assertEqual(True, sr.name.startswith(sd['name'])) # Testing the SpatialReference object directly. if postgis or spatialite: srs = sr.srs if GDAL_VERSION <= (1, 8): self.assertEqual(sd['proj4'], srs.proj4) # No `srtext` field in the `spatial_ref_sys` table in SpatiaLite if not spatialite: if connection.ops.spatial_version >= (1, 4, 0): srtext = sd['srtext14'] else: srtext = sd['srtext'] self.assertEqual(srtext, srs.wkt) @no_mysql def test03_ellipsoid(self):
"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']) ellps2 = srs.ellipsoid for i in range(3): param1 = ellps1[i] param2 = ellps2[i] self.assertAlmostEqual(
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 version 2 of the License, or (at your option) # any later version. # # EventGhost 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 EventGhost. If not, see <http://www.gnu.org/licenses/>. import wx # Local imports import eg cl
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 ): """ :Parameters: `value` : int The initial port to select (0 = COM1:). The first available port will be selected if the given port does not exist or no value is given. """ ports = eg.SerialThread.GetAllPorts() self.ports = ports choices = [("COM%d" % (portnum + 1)) for portnum in ports] wx.Choice.__init__( self, parent, id, pos, size, choices, style, validator, name ) try: portPos = ports.index(value) except ValueError: portPos = 0 self.SetSelection(portPos) def GetValue(self): """ Return the currently selected serial port. :rtype: int :returns: The serial port as an integer (0 = COM1:) """ try: port = self.ports[self.GetSelection()] except: port = 0 return port
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 = FREE_PLATFORMS() expected = ( ('free-firefoxos', _('Firefox OS')), ('free-desktop', _('Firefox for Desktop')), ('free-android-mobile', _('Firefox Mobile')), ('free-android-tablet', _('Firefox Tablet')), ) eq_(platforms, expected) def test_paid_platforms_default(self): platforms = PAID_PLATFORMS() expected = ( ('paid-firefoxos', _('Firefox OS')), ) eq_(plat
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_col = len(columns) item_list = get_items(filters) aii_account_map = get_aii_accounts() if item_list: item_tax, tax_accounts = get_tax_accounts(item_list, columns) data = [] for d in item_list: purchase_receipt = None if d.purchase_receipt: purchase_receipt = d.purchase_receipt elif d.po_detail: purchase_receipt = ", ".join(frappe.db.sql_list("""select distinct parent from `tabPurchase Receipt Item` where docstatus=1 and prevdoc_detail_docname=%s""", d.po_detail)) expense_account = d.expense_account or aii_account_map.get(d.company) row = [d.item_code, d.item_name, d.item_group, d.parent, d.posting_date, d.supplier, d.supplier_name, d.credit_to, d.project_name, d.company, d.purchase_order, purchase_receipt, expense_account, d.qty, d.base_net_rate, d.base_net_amount] for tax in tax_accounts: row.append(item_tax.get(d.parent, {}).get(d.item_code, {}).get(tax, 0)) total_tax = sum(row[last_col:]) row += [total_tax, d.base_net_amount + total_tax] data.append(row) return columns, data def get_columns(): return [_("Item Code") + ":Link/Item:120", _("Item Name") + "::120", _("Item Group") + ":Link/Item Group:100", _("Invoice") + ":Link/Purchase Invoice:120", _("Posting Date") + ":Date:80", _("Supplier") + ":Link/Supplier:120", "Supplier Name::120", "Payable Account:Link/Account:120", _("Project") + ":Link/Project:80", _("Company") + ":Link/Company:100", _("Purchase Order") + ":Link/Purchase Order:100", _("Purchase Receipt") + ":Link/Purchase Receipt:100", _("Expense Account") + ":Link/Account:140", _("Qty") + ":Float:120", _("Rate") + ":Currency:120", _("Amount") + ":Currency:120"] def get_conditions(filters): conditions = "" for opts in (("company", " and company=%(company)s"), ("supplier", " and pi.supplier = %(supplier)s"), ("item_code", " and pi_item.item_code = %(item_code)s"), ("from_date", " and pi.posting_date>=%(from_date)s"), ("to_date", " and pi.posting_date<=%(to_date)s")): if filters.get(opts[0]): conditions += opts[1] return conditions def get_items(filters): conditions = get_conditions(filters) match_conditions = frappe.build_match_conditions("Purchase Invoice") return frappe.db.sql("""select pi_item.parent, pi.posting_date, pi.credit_to, pi.company, pi.supplier, pi.remarks, pi.base_net_total, pi_item.item_code, pi_item.item_name, pi_item.item_group, pi_item.project_name, pi_item.purchase_order, pi_item.purchase_receipt, pi_item.po_detail, pi_item.expense_account, pi_item.qty, pi_item.base_net_rate, pi_item.base_net_amount, pi.supplier_name from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` pi_item where pi.name = pi_item.parent and pi.docstatus = 1 %s %s order by pi.posting_date desc, pi_item.item_code desc""" % (conditions, match_conditions), filters, as_dict=1) def get_aii_accounts(): return dict(frappe.db.sql("select name, stock_received_but_not_billed from tabCompany")) def get_tax_accounts(item_list, columns): import json item_tax = {} tax_accounts = [] invoice_wise_items = {} for d in item_list: invoice_wise_items.setdefault(d.parent, []).append(d) tax_details = frappe.db.sql("""select parent, account_head, item_wise_tax_detail, charge_type, base_tax_amount_after_discount_amount from `tabPurchase Taxes and Charges` where parenttype = 'Purchase Invoice' and docstatus = 1 and (account_head is not null and account_head != '') and category in ('Total', 'Valuation and Total') and parent in (%s)""" % ', '.join(['%s']*len(invoice_wise_items)), tuple(invoice_wise_items.keys())) for parent, account_head, item_wise_tax_detail, charge_type, tax_amount in tax_details: if account_head not in tax_accounts: tax_accounts.append(account_head) if item_wise_tax_detail: try: item_wise_tax_detail = json.loads(item_wise_tax_detail) for item, tax_amount in item_wise_tax_detail.items(): item_tax.setdefault(parent, {}).setdefault(item, {})[account_head] = \ flt(tax_amount[1]) if isinstance(tax_amount, list) else flt(tax_amount) except ValueError: continue elif charge_type == "Actual" and tax_amount: for d in invoice_wise_items.get(parent, []):
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, tom@idsia.ch' 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, given its covariance matrix. Returns a list of the diagonal blocks. """ if invSigma == None: invSigma = inv(sigma) if factorSigma == None: factorSigma = cholesky(sigma) dim = sigma.shape[0] fim = [invSigma] for k in range(dim): D = invSigma[k:, k:].copy() D[0, 0] += factorSigma[k, k] ** -2 fim.append(D) return fim def calcInvFisher(sigma, invSigma=None, factorSigma=None): """ Efficiently compute the exact inverse of the FIM of a Gaussian. Returns a list of the diagonal blocks. """ if invSigma == None: invSigma = inv(sigma) if factorSigma == None: factorSigma = cholesky(sigma) dim = sigma.shape[0] invF = [mat(1 / (invSigma[-1, -1] + factorSigma[-1, -1] ** -2))] invD = 1 / invSigma[-1, -1] for k in reversed(range(dim - 1)): v = invSigma[k + 1:, k]
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() return invF
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 example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi # ''' ## License The MIT License (MIT) GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi. Copyright (C) 2015 Dexter Industries Permission is hereby granted, free of charge, to any person obtaining a copy of th
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, subject to the following conditions: The above copyright notice an
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 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import time import grovepi # Connect the Grove Slide Potentiometer to analog port A0 # OUT,LED,VCC,GND slide = 0 # pin 1 (yellow wire) # The device has an onboard LED accessible as pin 2 on port A0 # OUT,LED,VCC,GND led = 1 # pin 2 (white wire) grovepi.pinMode(slide,"INPUT") grovepi.pinMode(led,"OUTPUT") time.sleep(1) while True: try: # Read sensor value from potentiometer sensor_value = grovepi.analogRead(slide) # Illuminate onboard LED if sensor_value > 500: grovepi.digitalWrite(led,1) else: grovepi.digitalWrite(led,0) print("sensor_value =", sensor_value) except IOError: print ("Error")
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 was expected." pass class SuspiciousOperation(Exception): "The user did something suspicious" pass class PermissionDenied(Exception): "The user did not have permission to do that" pass class ViewDoesNotExist(Exception): "The requested view does not exist" pass class MiddlewareNotUsed(Exception): "This middleware is not used in this server configuration" pass class ImproperlyConfigured(Exception): "Django is somehow improperly configured" pass class FieldError(Exception): """Some kind of problem with a model field.""" pass NON_FIELD_ERRORS = '__all__' class ValidationError(Exception): """An error while validating data.""" def __init__(self, message, code=None, params=None): import operator from django.utils.encoding import force_unicode """ ValidationError can be passed any object that can be printed (usually a string), a list of objects or a dictionary. """ if isinstance(message, dict): self.message_dict = message # Reduce each list of messages into a single list. message = reduce(operator.add, message.values()) if isinstance(message, list): self.messages = [force_unicode(msg) for msg in message] else: self.code = code self.params = params message = force_unicode(message) self.messages = [message] def __str__(self): # This is needed because, without a __str__(), printing an exception # instance would result in this: # AttributeError: ValidationError instance has no attribute 'args' # See http://www.python.org/doc/current/tut/node10.html#handling if hasattr(self, 'message_dict'): return repr(self.message_dict) return repr(self.messages) def __repr__(self): if hasattr(self, 'message_dict'): return 'ValidationError(%s)' % repr(self.message_dict) return 'ValidationError(%s)' % repr(self.messages) def update_error_dict(self, error_dict): if hasa
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/imagenet/train_imagenet.py class PreprocessedDataset(chainer.dataset.DatasetMixin): def __init__(self, metadata_filename, hparams): self._hparams = hparams # Load metadata: self._datadir = os.path.dirname(metadata_filename) # with open(metadata_filename) as f: with open(metadata_filename, encoding="utf-8_sig") as f: self._metadata = [line.strip().split('|') for line in f] hours = sum((int(x[2]) for x in self._metadata)) * \ hparams.frame_shift_ms / (3600 * 1000) log('Loaded metadata for %d examples (%.2f hours)' % (len(self._metadata), hours)) # Load CMUDict: If enabled, this will randomly substitute some words in the training data with # their ARPABet equivalents, which will allow you to also pass ARPABet to the model for # synthesis (useful for proper nouns, etc.) if hparams.use_cmudict: cmudict_path = os.path.join(self._datadir, 'cmudict-0.7b') if not os.path.isfile(cmudict_path): raise Exception('If use_cmudict=True, you must download ' + 'http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict-0.7b to %s' % cmudict_path) self._cmudict = cmudict.CMUDict(cmudict_path, keep_ambiguous=False) log('Loaded CMUDict with %d unambiguous entries' % len(self._cmudict)) else: self._cmudict = None def _get_next_example(self, offset): '''Loads a single example (input, mel_target, linear_target, cost) from disk''' meta = self._metadata[offset] text = meta[3] if self._cmudict and random.random() < _p_cmudict: text = ' '.join([self._maybe_get_arpabet(word) for word in text.split(' ')]) input_data = np.asarray(textinput.to_sequence(text), dtype=np.int32) linear_target = np.load(os.path.join(self._datadir, meta[0])) mel_target = np.load(os.path.join(self._datadir, meta[1])) return (input_data, mel_target, linear_target, len(linear_target)) # curriculum learning
? 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]) input_lengths = np.asarray([len(x[0]) for x in batch], dtype=
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) for x in inputs)) return np.stack([_pad_input(x, max_len) for x in inputs]) def _prepare_targets(targets, alignment): max_len = max((len(t) for t in targets)) + 1 return np.stack([_pad_target(t, _round_up(max_len, alignment)) for t in targets]) def _pad_input(x, length): return np.pad(x, (0, length - x.shape[0]), mode='constant', constant_values=_pad) def _pad_target(t, length): return np.pad(t, [(0, length - t.shape[0]), (0, 0)], mode='constant', constant_values=_pad) def _round_up(x, multiple): remainder = x % multiple return x if remainder == 0 else x + multiple - remainder # implimentation of DatasetMixin? def __len__(self): return len(self._metadata) # implimentation of DatasetMixin def get_example(self, i): input, mel, lin, _ = self._get_next_example(i) return input, (mel, lin)
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 forward_func(apps, schema_editor): Annotation = apps.get_model("annotations", "Annotation") db_alias = schema_editor.connection.alias # Set vector NULL where not_in_image for annotation in Annotation.objects.using(db_alias).all(): if annotation.not_in_image: annotation.vector = None annotation.save() def backward_func(
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 annotation.vector is None: annotation.vector = '' annotation.not_in_image = True annotation.save() operations = [ migrations.AlterField( model_name='annotation', name='vector', field=django.contrib.postgres.fields.jsonb.JSONField(null=True), ), migrations.RunPython(forward_func, backward_func, atomic=True), migrations.RemoveField( model_name='annotation', name='not_in_image', ), ]
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.frontend.server import french from bob_emploi.frontend.server import i18n from bob_emploi.frontend.server import jobs from bob_emploi.frontend.server import mongo from bob_emploi.frontend.server import scoring from bob_emploi.frontend.server.mail import campaign # pylint: disable=unused-import # Import all plugins: they register themselves when imported. from bob_emploi.frontend.server.mail import deletion from bob_emploi.frontend.server.mail import holiday from bob_emploi.frontend.server.mail import imt from bob_emploi.frontend.server.mail import improve_cv from bob_emploi.frontend.server.mail import jobbing from bob_emploi.frontend.server.mail import prepare_your_application from bob_emploi.frontend.server.mail import network from bob_emploi.frontend.server.mail import nps from bob_emploi.frontend.server.mail import switch from bob_emploi.frontend.server.mail import training # pylint: enable=unused-import _ONE_YEAR_AGO = datetime.datetime.now().replace(microsecond=0) - datetime.timedelta(365) _SIX_MONTHS_AGO = datetime.datetime.now().replace(microsecond=0) - datetime.timedelta(180) _ONE_MONTH_AGO = datetime.datetime.now().replace(microsecond=0) - datetime.timedelta(30) _EXPERIENCE_AS_TEXT = { project_pb2.JUNIOR: 'quelques temps', project_pb2.INTERMEDIARY: 'plus de 2 ans', project_pb2.SENIOR: 'plus de 6 ans', project_pb2.EXPERT: 'plus de 10 ans', } def _get_spontaneous_vars( user: user_pb2.User, *, now: datetime.datetime, database: mongo.NoPiiMongoDatabase, **unused_kwargs: Any) -> Dict[str, str]: """Computes vars for a given user for the spontaneous email. Returns a dict with all vars required for the template. """ project = user.projects[0] job_search_length = campaign.job_search_started_months_ago(project, now) if job_search_length < 0: raise campaign.DoNotSend('No info on user search duration') rome_id = project.target_job.job_group.rome_id if not rome_id: raise campaign.DoNotSend('User has no target job yet') job_group_info = jobs.get_group_proto(database, rome_id) if not job_group_info: raise scoring.NotEnoughDataException( 'Requires job group info to check if spontaneous application is a good channel.', fields={'projects.0.targetJob.jobGroup.romeId'}) application_modes = job_group_info.application_modes if not application_modes: raise scoring.NotEnoughDataException( 'Requires application modes to check if spontaneous application is a good channel.', fields={f'data.job_group_info.{rome_id}.application_modes'}) def _should_use_spontaneous(modes: job_pb2.RecruitingModesDistribution) -> bool: return any( mode.mode == job_pb2.SPONTANEOUS_APPLICATION and mode.percentage > 20 for mode in modes.modes) if not any(_should_use_spontaneous(modes) for modes in application_modes.values()): raise campaign.DoNotSend("Spontaneous isn't bigger than 20% of interesting channels.") contact_mode = job_group_info.preferred_application_medium if not contact_mode: raise scoring.NotEnoughDataException( 'Contact mode is required to push people to apply spontaneously', fields={f'data.job_group_info.{rome_id}.preferred_application_medium'}) in_a_workplace = job_group_info.in_a_workplace if not in_a_workplace and contact_mode != job_pb2.APPLY_BY_EMAIL: raise scoring.NotEnoughDataException( 'To apply in person, the %inAWorkplace template is required', fields={f'data.job_group_info.{rome_id}.in_a_workplace'}) like_your_workplace = job_group_info.like_your_workplace if in_a_workplace and not like_your_workplace: raise scoring.NotEnoughDataException( 'The template %likeYourWorkplace is required', fields={f'data.job_group_info.{rome_id}.like_your_workplace'}) to_the_workplace = job_group_info.to_the_workplace if not to_the_workplace: to_the_workplace = "à l'entreprise" some_companies = job_group_info.place_plural if not some_companies: some_companies = 'des entreprises' what_i_love_about = job_group_info.what_i_love_about if user.profile.gender == user_pb2.FEMININE: what_i_love_about_feminine = job_group_info.what_i_love_about_feminine if what_i_love_about_feminine: what_i_love_about = what_i_love_about_feminine if not what_i_love_about and contact_mode == job_pb2.APPLY_BY_EMAIL: raise scoring.NotEnoughDataException( 'An example about "What I love about" a company is required', fields={f'data.job_group_info.{rome_id}.what_i_love_about'}) why_specific_company = job_group_info.why_specific_company if not why_specific_company: raise scoring.NotEnoughDataException( 'An example about "Why this specific company" is required', fields={f'data.job_group_info.{rome_id}.why_specific_company'}) at_various_companies = job_group_info.at_various_companies if project.weekly_applications_estimate == project_pb2.SOME: weekly_applications_count = '5' elif project.weekly_applications_estimate > project_pb2.SOME: weekly_applications_count = '15' else: weekly_applications_count = '' if project.weekly_applications_estimate: weekly_applications_option = project_pb2.NumberOfferEstimateOption.Name( project.weekly_applications_estimate) else: weekly_applications_option = '' return dict(campaign.get_default_coaching_email_vars(user), **{ 'applicationComplexity': job_pb2.ApplicationProcessComplexity.Name(job_group_info.application_complexity), 'atVariousCompanies': at_various_companies, 'contactMode': job_pb2.ApplicationMedium.Name(contact_mode).replace('APPLY_', ''), 'deepLinkLBB': f'https://labonneboite.pole-emploi.fr/entreprises/commune/{project.city.city_id}/rome/' f'{project.target_job.job_group.rome_id}?utm_medium=web&utm_source=bob&' 'utm_campaign=bob-email', 'emailInUrl': parse.quote(user.profile.email), 'experienceAsText': _EXPERI
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, 'weeklyApplicationsOption': weekly_applications_option, 'whatILoveAbout': what_i_love_about, 'whySpecificCompany': why_specific_company, }) def _get_self_development_vars( user: user_pb2.User, *, now: datetime.datetime, **unused_kwargs: Any) \ -> Dict[str, str]: """Computes vars for a given user for the self-development email. Returns a dict with all vars required for the template. """ project = user.projects[0] job_search_length = campaign.job_search_started_months_ago(project, now) if job_search_length < 0: raise campaign.DoNotSend('No info on user search duration.') if job_search_length > 12: raise campaign.DoNotSend(f'User has been searching for too long ({job_search_length:.2f}).') genderized_job_name = french.lower_first_letter(french.genderize_job( project.target_job, user.profile.gender)) age = datetime.date.today().year - user.profile.year_of_birth max_young = 30 min_old = 50 return dict(campaign.get_default_coaching_email_vars(user), **{ 'hasEnoughExperience': campaign.as_templ
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 quantity_wrapped, quantity_unwrapped from ..tools import dynamic_quantity_wrapped, dynamic_converted_quantity_unwrapped """ Cryomagnetics model 4G Device """ class Channel(AbstractSubdevice): """ Interface for a channel on the Model4G """ allowed_switch_heater = set(['on','off']) allowed_heater_wait_mode = set(['on','off']) allowed_sweep = set(['up','zero','down', 'pause']) allowed_sync = set(['start','stop']) allowed_energysave_mode = set([0,1,2,3,4]) allowed_units = set(['kG','A']) def _setup(self): AbstractSubdevice._setup(self) # Resources. read_only = ['magnet_current','power_supply_current'] for name in read_only: self.resources[name] = Resource(self, name) read_write = ['persistent_switch_heater', 'high_limit','low_limit','sweep', 'rate_0','rate_1','rate_2','rate_3','rate_4', 'virt_sync_currents', 'virt_imag', 'virt_iout', 'virt_imag_sweep_to','virt_iout_sweep_to','virt_energysave_mode', 'virt_heater_wait_mode' ,'virt_sweep_sleep', 'units'] for name in read_write: self.resources[name] = Resource(self, name, name) # Resources with their units controlled by self._units. self.dynamic_unit_resources = ['virt_imag_sweep_to','virt_iout_sweep_to','virt_imag','virt_iout','magnet_current', 'power_supply_current','high_limit','low_limit' ] for name in self.dynamic_unit_resources: self.resources[name].units = self._units self.resources['virt_sweep_sleep'].units = 's' for x in range(5): self.resources['rate_{0}'.format(x)].units = 'A.s-1' self.resources['virt_heater_wait_mode'].allowed_values = self.allowed_heater_wait_mode self.resources['virt_energysave_mode'].allowed_values = self.allowed_energysave_mode self.resources['virt_energysave_mode'].converter = int self.resources['persistent_switch_heater'].allowed_values = self.allowed_switch_heater self.resources['sweep'].allowed_values = self.allowed_sweep self.resources['virt_sync_currents'].allowed_values = self.allowed_sync self.resources['units'].allowed_values = self.allowed_units def __init__(self, device, channel, *args, **kwargs): self.channel = channel # internal attributes used for virtual features not present in actual device. self._units = 'kG' # default units. self._energysave_mode = 0 self._iout_target = None self._imag_target = None self._heater_wait_mode = 'on' self._sweep_sleep = 1. AbstractSubdevice.__init__(self, device, *args, **kwargs) def _connected(self): # Initializations requiring GPIB. self.units = self._units self._iout_target = self.power_supply_current.original_value self._imag_tar
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. current_sweep = self.sweep elif current_sweep == 'Sweeping to zero': while current_sweep != 'Pause' and self.power_supply_current != Quantity(0,self._units): sleep(0.1) current_sweep = self.sweep elif current_sweep == 'Sweeping down': while current_sweep != 'Pause' and self.power_supply_current != self.low_limit: sleep(0.1) current_sweep = self.sweep if i == 0 and self.virt_sweep_sleep.value != 0: sleep(self.virt_sweep_sleep.value) # we sleep, then check once more to ensure the sweep has stabilized. class _set_channel(object): """ A decorator which prefixes a method with a setting of the channel. Note: Usually, this decorator should be wrapped underneath the @Synchronized() method """ @staticmethod def __call__(f): @wraps(f) def decorated(self, *args, **kwargs): # Set channel here. if self.device.active_channel_store is not self.channel: self.device.active_channel = self.channel return f(self, *args, **kwargs) return decorated # Low-level Direct Controls. #################################################################################### @property @Synchronized() @dynamic_quantity_wrapped('_units') @_set_channel() def high_limit(self): """ The upper limit on the magnetic current """ response = self.device.ask('ulim?') stripped_response = Quantity.from_string(response)[0] return stripped_response @high_limit.setter @Synchronized() @dynamic_converted_quantity_unwrapped('_units') @_set_channel() def high_limit(self,value): self.device.write('ulim {0}'.format(value)) @property @Synchronized() @dynamic_quantity_wrapped('_units') @_set_channel() def low_limit(self): """ The lower limit on the magnetic current """ response = self.device.ask('llim?') stripped_response = Quantity.from_string(response)[0] return stripped_response @low_limit.setter @Synchronized() @dynamic_converted_quantity_unwrapped('_units') @_set_channel() def low_limit(self,value): self.device.write('llim {0}'.format(value)) @property @Synchronized() @dynamic_quantity_wrapped('_units') @_set_channel() def magnet_current(self): """ This is the persistent magnet current setting """ response = self.device.ask('imag?') stripped_response = Quantity.from_string(response)[0] return stripped_response @property @Synchronized() @_set_channel() def persistent_switch_heater(self): """ The persistent switch heater """ response = float(self.device.ask('pshtr?')) # when getting from the device immediately after a set, the power supply returns a 2 if it has not fully # changed while response == 2: sleep(0.5) response = float(self.device.ask('pshtr?')) response_dict = {0:'off', 1:'on'} return response_dict[response] @persistent_switch_heater.setter @Synchronized() @_set_channel() def persistent_switch_heater(self,value): if value not in self.allowed_switch_heater: raise ValueError('Invalid heater switch value: {0}'.format(value)) # don't allow the heater switch to go on if currents not synced if self.virt_sync_currents != 'synced' and value == 'on': raise ValueError('Currents are not synced in channel {0}.'.format(self.channel)) self.device.write('pshtr {0}'.format(value)) # Give the heaters time to warm up, if desired. if self.virt_heater_wait_mode == 'on': sleep(1) @pr
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 interface, for autocompletion field. class UnelectedWinnerForm(forms.ModelForm):
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 try: from thrift.protocol import fastbinary except: fastbinary = None class Token: """ Attributes: - word - tag - lemma """ thrift_spec = ( None, # 0 (1, TType.STRING, 'word', None, None, ), # 1 (2, TType.STRING, 'tag', None, None, ), # 2 (3, TType.STRING, 'lemma', None, None, ), # 3 ) def __init__(self, word=None, tag=None, lemma=None,): self.word = word self.tag = tag self.lemma = lemma def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryP
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 == TType.STRING: self.tag = iprot.readString() else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.lemma = iprot.readString() else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('Token') if self.word is not None: oprot.writeFieldBegin('word', TType.STRING, 1) oprot.writeString(self.word) oprot.writeFieldEnd() if self.tag is not None: oprot.writeFieldBegin('tag', TType.STRING, 2) oprot.writeString(self.tag) oprot.writeFieldEnd() if self.lemma is not None: oprot.writeFieldBegin('lemma', TType.STRING, 3) oprot.writeString(self.lemma) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __hash__(self): value = 17 value = (value * 31) ^ hash(self.word) value = (value * 31) ^ hash(self.tag) value = (value * 31) ^ hash(self.lemma) return value def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other)
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 <laaksonen.heikki.j@gmail.com> # # 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 Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 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/>. """storage: Storage management for content.""" from snippy.cause import Cause from snippy.config.config import Config from snippy.logger import Logger from snippy.storage.database import Database class Storage(object): """Storage management for content.""" def __init__(self): self._logger = Logger.get_logger(__name__) self._database = Database() self._database.init() def create(self, collection): """Create new content. Args: collection (Collection): Content container to be stored into database. """ if Cause.is_ok(): self._logger.debug('store content') collection = self._database.insert(collection) else: self._logger.debug('content not stored becuase of errors: {}'.format(Cause.http_status)) return collection def search(self, scat=(), sall=(), stag=(), sgrp=(), search_filter=None, uuid=None, digest=None, identity=None, data=None): # noqa pylint: disable=too-many-arguments """Search content. Args: scat (tuple): Search category keyword list. sall (tuple): Search all keyword list. stag (tuple): Search tag keyword list. sgrp (tuple): Search group keyword list. search_filter (str): Regexp filter to limit search results. uuid (str): Search specific uuid or part of it. digest (str): Search specific digest or part of it. identity (str): Search specific digest or UUID or part of them. data (str): Search specific content data or part of it. Returns: Collection: Search result in Collection of content. """ self._logger.debug('search content') collection = self._database.select(scat, sall, stag, sgrp, search_filter, uuid, digest, identity, data) return collection def uniques(self, field, scat, sall, stag, sgrp): """Get unique values for given field. Args: field (str): Content field which unique values are read. Returns: tuple: List of unique values for give field. """ self._logger.debug('search unique values for field: ', field) values = self._database.select_distinct(field, scat, sall, stag, sgrp) return values def update(self, digest, resource): """Update resource specified by digest. Args: digest (str): Content digest that is udpated. resource (Resource): A single Resource() container that contains updates. """ self._logger.debug('update content') resource.updated = Config.utcnow() collection = self._database.update(digest, resource) return collection def delete(self, digest): """Delete content. Args: digest (str): Content digest that is deleted. """ self._logger.debug('delete content') self._database.delete(digest) def export_content(self, scat=()): """Export content. Args: scat (tuple): Search category keyword list. """ self._logger.debug('export content') collection = self._database.select_all(scat) return collection def import_content(self, collection): """Import content. Args: collection (Collection): Content container to be im
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) : shutil.rmtree(self.testDir) os.mkdir(self.testDir) ref = os.path.join(self.testDir, "reference") cmp = os.path.join(self.testDir, "compare") out = os.path.join(self.testDir, "output") os.mkdir(ref) os.mkdir(cmp) os.mkdir(out) script = os.path.join(self.testDir, "script.sh") self.db = DiffBuilder(ref, cmp, out, script) def tearDown(self) : if os.path.exists(self.testDir) : shutil.rmtree(self.testDir) def genFile(self, iDir, iFilename, iContent): f = open(os.path.join(iDir, iFilename), "w") f.write(iContent) f.close() def genRandomContentFile(self, iDir, iFilename): self.genFile(iDir, iFilename, "%032x" % random.getrandbits(128)) def genIdenticalFiles(self, iDir1, iDir2, iFilename): self.genFile(iDir1, iFilename, "IDENTICAL CONTENT") self.genFile(iDir2, iFilename, "IDENTICAL CONTENT") def genDifferentContentFiles(self, iDir1, iDir2, iFilename): self.genRandomContentFile(iDir1, iFilename) self.genRandomContentFile(iDir2, iFilename) def test_GenerateDiff(self): # Premier cas : les deux fichiers sont identiques dans les deux répertoires self.genIdenticalFiles(self.db.ref, self.db.cmp, "identiques") # Second cas : les deux fichiers ont le même nom mais sont différents self.genDifferentContentFiles(self.db.ref, self.db.cmp, "differents") # Troisième cas : le fichier est dans la référence mais pas dans le compare self.genRandomContentFile(self.db.ref, "onlyref") # Quatrième cas : le fichier est dans le compare mais pas dans la référence self.genRandomContentFile(self.db.cmp, "onlycmp") # On recopie tout ça dans un sous-répertoire pour être sûr que la récursion se passe bien shutil.copytree(self.db.ref, os.path.join(self.db.ref, "subdir")) shutil.copytree(self.db.cmp, os.path.join(self.db.cmp, "subdir")) # Et même qu'on le recopie encore dans le sous-répertoire pour être bien sûr shutil.copytree(os.path.join(self.db.ref, "subdir"), os.path.join(self.db.ref, "subdir", "anothersubdir")) shutil.copytree(os.path.join(self.db.cmp, "subdir"), os.path.join(self.db.cmp, "subdir", "anothersubdir")) self.db.generateDiff() # Vérifications self.assertTrue(os.path.exists(os.path.join(self.db.out, "differents"))) self.assertTrue(os.path.exists(os.path.join(self.db.out, "onlycmp"))) self.assertTrue(os.path.e
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 scriptFile] scriptFile.close() self.assertTrue("rm subdir/anothersubdir/onlyref" in scriptLines) self.assertTrue
("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 <jeffrey.finkelstein@gmail.com> and contributors. :license: GNU AGPLv3+ or BSD """ from nose.tools import assert_raises from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy.orm.exc import NoResultFound from flask.ext.restless.search import create_query from flask.ext.restless.search import search from flask.ext.restless.search import SearchParameters from .helpers import TestSupportPrefilled class TestQueryCreation(TestSupportPrefilled): """Unit tests for the :func:`flask_restless.search.create_query` function.
""" 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. """ d = {'filters': [{'name': 'name', 'val': u'%y%', 'op': 'like'}]} s = SearchParameters.from_dictionary(d) query_d = create_query(self.session, self.Person, d) query_s = create_query(self.session, self.Person, s) assert query_d.all() == query_s.all() def test_basic_query(self): """Tests for basic query correctness.""" d = {'filters': [{'name': 'name', 'val': u'%y%', 'op': 'like'}]} query = create_query(self.session, self.Person, d) assert query.count() == 3 # Mary, Lucy and Katy d = {'filters': [{'name': 'name', 'val': u'Lincoln', 'op': 'equals'}]} query = create_query(self.session, self.Person, d) assert query.count() == 1 assert query.one().name == 'Lincoln' d = {'filters': [{'name': 'name', 'val': u'Bogus', 'op': 'equals'}]} query = create_query(self.session, self.Person, d) assert query.count() == 0 d = {'order_by': [{'field': 'age', 'direction': 'asc'}]} query = create_query(self.session, self.Person, d) ages = [p.age for p in query] assert ages == [7, 19, 23, 25, 28] d = {'order_by': [{'field': 'other', 'direction': 'asc'}], 'group_by': [{'field': 'other'}]} query = create_query(self.session, self.Person, d) data = [p.other for p in query] assert data == [10.0, 19.0, 20.0, 22.0] d = {'filters': [{'name': 'age', 'val': [7, 28], 'op': 'in'}]} query = create_query(self.session, self.Person, d) ages = [p.age for p in query] assert ages == [7, 28] def test_query_related_field(self): """Test for making a query with respect to a related field.""" # add a computer to person 1 computer = self.Computer(name=u'turing', vendor=u'Dell') p1 = self.session.query(self.Person).filter_by(id=1).first() p1.computers.append(computer) self.session.commit() d = {'filters': [{'name': 'computers__name', 'val': u'turing', 'op': 'any'}]} query = create_query(self.session, self.Person, d) assert query.count() == 1 assert query.one().computers[0].name == 'turing' d = {'filters': [{'name': 'age', 'op': 'lte', 'field': 'other'}], 'order_by': [{'field': 'other'}]} query = create_query(self.session, self.Person, d) assert query.count() == 2 results = query.all() assert results[0].other == 10 assert results[1].other == 19 def test_order_by_relation_field_ascending(self): # Given computer_for_mary = self.Computer(name=u'1st', vendor=u'vendor') mary = self.session.query(self.Person).filter_by(name=u'Mary').first() mary.computers.append(computer_for_mary) computer_for_lucy = self.Computer(name=u'2nd', vendor=u'vendor') lucy = self.session.query(self.Person).filter_by(name=u'Lucy').first() lucy.computers.append(computer_for_lucy) self.session.commit() # When d = {'order_by': [{'field': 'owner__name', 'direction': 'asc'}]} query = create_query(self.session, self.Computer, d) # Then assert query.count() == 2 results = query.all() assert results[0].owner.name == u'Lucy' assert results[1].owner.name == u'Mary' def test_order_by_relation_field_descending(self): # Given computer_for_mary = self.Computer(name=u'1st', vendor=u'vendor') mary = self.session.query(self.Person).filter_by(name=u'Mary').first() mary.computers.append(computer_for_mary) computer_for_lucy = self.Computer(name=u'2nd', vendor=u'vendor') lucy = self.session.query(self.Person).filter_by(name=u'Lucy').first() lucy.computers.append(computer_for_lucy) self.session.commit() # When d = {'order_by': [{'field': 'owner__name', 'direction': 'desc'}]} query = create_query(self.session, self.Computer, d) # Then assert query.count() == 2 results = query.all() assert results[0].owner.name == u'Mary' assert results[1].owner.name == u'Lucy' def test_order_by_and_filter_on_the_same_relation(self): # Given computer_for_mary = self.Computer(name=u'1st', vendor=u'vendor') mary = self.session.query(self.Person).filter_by(name=u'Mary').first() mary.computers.append(computer_for_mary) computer_for_lucy = self.Computer(name=u'2nd', vendor=u'vendor') lucy = self.session.query(self.Person).filter_by(name=u'Lucy').first() lucy.computers.append(computer_for_lucy) self.session.commit() # When d = { 'filters': [ { 'name': 'owner', 'op': 'has', 'val': { 'name': 'name', 'op': 'like', 'val': '%y' } } ], 'order_by': [{'field': 'owner__name', 'direction': 'asc'}] } query = create_query(self.session, self.Computer, d) # Then assert query.count() == 2 results = query.all() assert results[0].owner.name == u'Lucy' assert results[1].owner.name == u'Mary' def test_order_by_two_different_fields_of_the_same_relation(self): # Given computer_for_mary = self.Computer(name=u'1st', vendor=u'vendor') mary = self.session.query(self.Person).filter_by(name=u'Mary').first() mary.computers.append(computer_for_mary) computer_for_lucy = self.Computer(name=u'2nd', vendor=u'vendor') lucy = self.session.query(self.Person).filter_by(name=u'Lucy').first() lucy.computers.append(computer_for_lucy) self.session.commit() # When d = { 'order_by': [ {'field': 'owner__age', 'direction': 'asc'}, {'field': 'owner__name', 'direction': 'asc'}, ] } query = create_query(self.session, self.Computer, d) # Then assert query.count() == 2 results = query.all() assert results[0].owner.name == u'Mary' assert results[1].owner.name == u'Lucy' class TestOperators(TestSupportPrefilled): """Tests for each of the query operators defined in :data:`flask_restless.search.OPERATORS`. """ def test_operators(self): """Tests for each of the individual operators in :data:`flask_restless.search.OPERATORS`. """ for op in '==', 'eq', 'equals', 'equal_to': d = dict(filters=[dict(name='name', op=op, val=u'Lincoln')]) result = search(self.session, self.Person, d) assert result.count() == 1 assert result[0].name == u'Lincoln' for op in '!=', 'ne', 'neq', 'not_equal_to'
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 Foundation, either version 3 of the License, or (at your option) any later version. 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 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 import pprint import re impor
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: start date :n : how many groups we want to get :group_type : daily, weekly, monthly """ current_date = start_date if group_type == 'monthly': current_year = start_date.year current_month = start_date.month for i in range(n+1): current_month-=1 if current_month == 0: current_month = 12 current_year -= 1 first_date = datetime.datetime(current_year,current_month,1) elif group_type == 'weekly': first_date=start_date-datetime.timedelta(days = start_date.weekday()+(n+1)*7) elif group_type == 'daily': first_date = start_date-datetime.timedelta(days = n+1) first_date = datetime.datetime(first_date.year,first_date.month,first_date.day,0,0,0) return first_date def group_snapshots_by_date(snapshots): roles = { 'daily' : lambda dt : dt.strftime("%Y-%m-%d"), 'weekly' : lambda dt: dt.strftime("%Y-%W"), 'monthly' : lambda dt: dt.strftime("%Y-%m") } grouped_snapshots = {} current_snapshots = {} current_keys = {} for role in roles: grouped_snapshots[role] = {} current_snapshots[role] = [] for snapshot in reversed(sorted(snapshots,key = lambda x:x.committer_date)): dt = datetime.datetime.fromtimestamp(snapshot.committer_date_ts).date() for role,formatter in roles.items(): key = formatter(dt) if not role in current_keys: current_keys[role] = key current_snapshots[role].append(snapshot) if key != current_keys[role]: grouped_snapshots[role][current_keys[role]] = current_snapshots[role] current_snapshots[role] = [snapshot] current_keys[role] = key return grouped_snapshots class Repository(object): def __init__(self,path): self._path = path self.devnull = open(os.devnull,"w") self.stderr = '' self.stdout = '' self.returncode = None @property def path(self): return self._path @path.setter def set_path(self,path): self._path = path def _call(self,args,kwargs,capture_stderr = True,timeout = None): if not 'cwd' in kwargs: kwargs['cwd'] = self.path if timeout: #We write command output to temporary files, so that we are able to read it #even if we terminate the command abruptly. with tempfile.TemporaryFile() as stdout,tempfile.TemporaryFile() as stderr: if capture_stderr: stderr = stdout p = subprocess.Popen(*args,stdout = stdout,stderr = stderr,preexec_fn=os.setsid,**kwargs) def read_output(): stdout.flush() stderr.flush() stdout.seek(0) self.stdout = stdout.read() stderr.seek(0) self.stderr = stderr.read() start_time = time.time() while time.time() - start_time < timeout: if p.poll() != None: break time.sleep(0.001) timeout_occured = False if p.poll() == None: timeout_occured = True stdout.flush() stderr.flush() p.terminate() time.sleep(0.1) if p.poll() == None: p.kill() read_output() if timeout_occured: self.stderr+="\n[process timed out after %d seconds]" % int(timeout) self.returncode = p.returncode return p.returncode,self.stdout else: if capture_stderr: stderr = subprocess.STDOUT else: stderr = subprocess.PIPE p = subprocess.Popen(*args,stdout = subprocess.PIPE,stderr = stderr,**kwargs) stdout,stderr = p.communicate() return p.returncode,stdout def call(self,*args,**kwargs): if 'timeout' in kwargs: timeout = kwargs['timeout'] del kwargs['timeout'] return self._call(args,kwargs,timeout = timeout) else: return self._call(args,kwargs) def check_output(self,*args,**kwargs): returncode,stdout = self._call(args,kwargs,capture_stderr = False) if returncode != 0: raise subprocess.CalledProcessError(returncode,args[0],stdout) return stdout def add_remote(self,name,url): return_code,stdout = self.call(["git","remote","add",name,url]) return return_code def remove_remote(self,name): return_code,stdout = self.call(["git","remote","remove",name]) return return_code def get_remotes(self): return [x.strip() for x in self.check_output(["git","remote"],cwd = self.path).decode("utf-8",'ignore').split("\n") if x.strip()] def init(self): return_code,stdout = self.call(["git","init"]) return return_code def pull(self,remote = "origin",branch = "master"): return_code,stdout = self.call(["git","pull",remote,branch]) return return_code def _get_ssh_wrapper(self): wrapper = os.path.abspath(__file__+"/..")+"/ssh" return wrapper def _get_ssh_config(self,identity_file): return """Host * StrictHostKeyChecking no IdentityFile "%s" IdentitiesOnly yes """ % identity_file def fetch(self,remote = "origin",ssh_identity_file = None,git_config = None,git_credentials = None): if not re.match(r"^[\w\d]+$",remote): raise ValueError("Invalid remote: %s" % remote) try: directory = tempfile.mkdtemp() env = {'HOME' : directory} if ssh_identity_file: #To Do: Security audit logger.debug("Fetching with SSH key") env.update({'CONFIG_FILE' : directory+"/ssh_config", 'GIT_SSH' : self._get_ssh_wrapper()}) with open(directory+"/ssh_config","w") as ssh_config_file: ssh_config_file.write(self._get_ssh_config(ssh_identity_file)) if git_config: env.update({'GIT_CONFIG_NOSYSTEM' : '1'}) with open(directory+"/.gitconfig","w") as git_config_file: git_config_file.write(git_config) if git_credentials: with open(directory+"/.git-credentials","w") as git_credentials_file: git_credentials_file.write(git_credentials) return_code,stdout = self.call(["git","fetch",remote],env = env,timeout = 120) finally: shutil.rmtree(direct
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 the given word. # The possible words which may be used are taken from words.txt, and, if plugins.log has a lo
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 = Counter(wordList.fromLog(VOCAB_CHANNEL, 'plugins/log/database')) nicks = set(wordList.nicksFromLog(VOCAB_CHANNEL, 'plugins/log/database')) words |= set(w for w in logged if logged[w] > 99) - nicks # Include nonnicks logged > 99 times. anagrams = anagram.Finder(words) words &= set(w for w in logged if logged[w] > 1) # Exclude words logged < 2 times. except Exception as e: anagrams = anagram.Finder(words) traceback.print_exc(e) finally: del logged, nicks games = {} def chmsg(event, server): chan, nick, msg = event['channel'], event['nicka'], event['msg'] def respond(msg): server.send_msg(chan, wrap(msg, server)) if chan in games: jumble = games[chan] else: jumble = games[chan] = Jumble() return jumble.said(server, msg, nick, respond) def wrap(msg, server): max = server.MAX_SIZE - 100 end = ' (...)' if len(msg) > max: return msg[0:max-len(end)] + end else: return msg def define(server, word): if 'plugins.define.define' not in server.mod.modules: return None define = server.mod.modules['plugins.define.define'] try: return define.instance.define(word) except IOError: pass except define.dictionary.ProtocolError: pass class Jumble(object): __slots__ = 'word', 'solutions', 'min', 'max' def __init__(self): self.min = self.max = 0 self.word = None def said(self, server, msg, nick, respond): match = re.match(r'!jumble(\s+\d+)?(\s+\d+)?\s*$', msg, re.I) if match: return self.call(server, respond, *match.groups()) match = re.match(r'!jumble\s+end\s*$', msg, re.I) if match: return self.end(server, respond, *match.groups()) match = re.match(r'!jumble\s.', msg, re.I) if match: return self.help(server, respond, *match.groups()) match = re.match(r'!unjumble\s+([a-z]+)\s*$', msg, re.I) if match: return self.unjumble(server, respond, nick, *match.groups()) match = re.match(r'\s*([a-z]+)\s*$', msg, re.I) if match: return self.guess(server, respond, nick, *match.groups()) def call(self, server, respond, min, max): if min != None: self.min = int(min) if max != None: self.max = int(max) self.end(server, respond) self.start(server, respond) def start(self, server, respond): sub = set(w for w in words if self.min <= len(w) and (self.max == 0 or len(w) <= self.max)) while len(sub): word = random.sample(sub, 1)[0] solutions = anagrams(word) if math.factorial(len(word)) != len(solutions): chars = list(word) while ''.join(chars) in solutions: random.shuffle(chars) self.word, self.solutions = ''.join(chars), solutions return respond(self.word) else: sub.remove(word) # Every permutation of this word is in the dictionary. else: return respond("Failed to generate a word.") # There are no suitable words. def guess(self, server, respond, nick, word): if not self.word: return word = word.upper() if word in self.solutions: defn = define(server, word) if defn: respond("%s wins with %s (%s)" % (nick, word, defn)) else: respond("%s wins with %s." % (nick, word)) self.start(server, respond) def end(self, server, respond): if not self.word: return self.word = None if len(self.solutions) == 1: defn = define(server, tuple(self.solutions)[0]) if defn: return respond('Nobody wins. Solutions: %s (%s)' % (', '.join(self.solutions), defn)) return respond('Nobody wins. Solutions: %s.' % ', '.join(self.solutions)) def unjumble(self, server, respond, nick, word): words = anagrams(word) if len(words): return respond(', '.join(words)) return respond('No results.') def help(self, server, respond): respond('Available commands:' ' \002!jumble [min [max]]\002,' ' \002!jumble end\002,' ' \002!jumble help\002,' ' \002!unjumble <word>\002.')
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 ( assert_allclose, assert_, assert_array_almost_equal, assert_equal, assert_array_almost_equal_nulp) from scipy._lib._numpy_compat import suppress_warnings from scipy.sparse import csc_matrix, SparseEfficiencyWarning from scipy.sparse.construct import eye as speye from scipy.sparse.linalg.matfuncs import (expm, _expm, ProductOperator, MatrixPowerOperator, _onenorm_matrix_power_nnm) from scipy.linalg import logm from scipy.special import factorial, binom import scipy.sparse import scipy.sparse.linalg def _burkardt_13_power(n, p): """ A helper function for testing matrix functions. Parameters ---------- n : integer greater than 1 Order of the square matrix to be returned. p : non-negative integer Power of the matrix. Returns ------- out
: 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_power_nnm(): np.random.seed(1234) for n in range(1, 5): for p in range(5): M = np.random.random((n, n)) Mp = np.linalg.matrix_power(M, p) observed = _onenorm_matrix_power_nnm(M, p) expected = np.linalg.norm(Mp, 1) assert_allclose(observed, expected) class TestExpM(object): def test_zero_ndarray(self): a = array([[0.,0],[0,0]]) assert_array_almost_equal(expm(a),[[1,0],[0,1]]) def test_zero_sparse(self): a = csc_matrix([[0.,0],[0,0]]) assert_array_almost_equal(expm(a).toarray(),[[1,0],[0,1]]) def test_zero_matrix(self): a = np.matrix([[0.,0],[0,0]]) assert_array_almost_equal(expm(a),[[1,0],[0,1]]) def test_misc_types(self): A = expm(np.array([[1]])) assert_allclose(expm(((1,),)), A) assert_allclose(expm([[1]]), A) assert_allclose(expm(np.matrix([[1]])), A) assert_allclose(expm(np.array([[1]])), A) assert_allclose(expm(csc_matrix([[1]])).A, A) B = expm(np.array([[1j]])) assert_allclose(expm(((1j,),)), B) assert_allclose(expm([[1j]]), B) assert_allclose(expm(np.matrix([[1j]])), B) assert_allclose(expm(csc_matrix([[1j]])).A, B) def test_bidiagonal_sparse(self): A = csc_matrix([ [1, 3, 0], [0, 1, 5], [0, 0, 2]], dtype=float) e1 = math.exp(1) e2 = math.exp(2) expected = np.array([ [e1, 3*e1, 15*(e2 - 2*e1)], [0, e1, 5*(e2 - e1)], [0, 0, e2]], dtype=float) observed = expm(A).toarray() assert_array_almost_equal(observed, expected) def test_padecases_dtype_float(self): for dtype in [np.float32, np.float64]: for scale in [1e-2, 1e-1, 5e-1, 1, 10]: A = scale * eye(3, dtype=dtype) observed = expm(A) expected = exp(scale) * eye(3, dtype=dtype) assert_array_almost_equal_nulp(observed, expected, nulp=100) def test_padecases_dtype_complex(self): for dtype in [np.complex64, np.complex128]: for scale in [1e-2, 1e-1, 5e-1, 1, 10]: A = scale * eye(3, dtype=dtype) observed = expm(A) expected = exp(scale) * eye(3, dtype=dtype) assert_array_almost_equal_nulp(observed, expected, nulp=100) def test_padecases_dtype_sparse_float(self): # float32 and complex64 lead to errors in spsolve/UMFpack dtype = np.float64 for scale in [1e-2, 1e-1, 5e-1, 1, 10]: a = scale * speye(3, 3, dtype=dtype, format='csc') e = exp(scale) * eye(3, dtype=dtype) with suppress_warnings() as sup: sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure of a csc_matrix is expensive.") exact_onenorm = _expm(a, use_exact_onenorm=True).toarray() inexact_onenorm = _expm(a, use_exact_onenorm=False).toarray() assert_array_almost_equal_nulp(exact_onenorm, e, nulp=100) assert_array_almost_equal_nulp(inexact_onenorm, e, nulp=100) def test_padecases_dtype_sparse_complex(self): # float32 and complex64 lead to errors in spsolve/UMFpack dtype = np.complex128 for scale in [1e-2, 1e-1, 5e-1, 1, 10]: a = scale * speye(3, 3, dtype=dtype, format='csc') e = exp(scale) * eye(3, dtype=dtype) with suppress_warnings() as sup: sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure of a csc_matrix is expensive.") assert_array_almost_equal_nulp(expm(a).toarray(), e, nulp=100) def test_logm_consistency(self): random.seed(1234) for dtype in [np.float64, np.complex128]: for n in range(1, 10): for scale in [1e-4, 1e-3, 1e-2, 1e-1, 1, 1e1, 1e2]: # make logm(A) be of a given scale A = (eye(n) + random.rand(n, n) * scale).astype(dtype) if np.iscomplexobj(A): A = A + 1j * random.rand(n, n) * scale assert_array_almost_equal(expm(logm(A)), A) def test_integer_matrix(self): Q = np.array([ [-3, 1, 1, 1], [1, -3, 1, 1], [1, 1, -3, 1], [1, 1, 1, -3]]) assert_allclose(expm(Q), expm(1.0 * Q)) def test_integer_matrix_2(self): # Check for integer overflows Q = np.array([[-500, 500, 0, 0], [0, -550, 360, 190], [0, 630, -630, 0], [0, 0, 0, 0]], dtype=np.int16) assert_allclose(expm(Q), expm(1.0 * Q)) Q = csc_matrix(Q) assert_allclose(expm(Q).A, expm(1.0 * Q).A) def test_triangularity_perturbation(self): # Experiment (1) of # Awad H. Al-Mohy and Nicholas J. Higham (2012) # Improved Inverse Scaling and Squaring Algorithms # for the Matrix Logarithm. A = np.array([ [3.2346e-1, 3e4, 3e4, 3e4], [0, 3.0089e-1, 3e4, 3e4], [0, 0, 3.221e-1, 3e4], [0, 0, 0, 3.0744e-1]], dtype=float) A_logm = np.array([ [-1.12867982029050462e+00, 9.61418377142025565e+04, -4.52485573953179264e+09, 2.92496941103871812e+14], [0.00000000000000000e+00, -1.20101052953082288e+00, 9.63469687211303099e+04, -4.68104828911105442e+09], [0.00000000000000000e+00, 0.00000000000000000e+00, -1.13289322264498393e+00, 9.53249183094775653e+04], [0.00000000000000000e+00, 0.00000000000000000e+00, 0.00000000000000000e+00, -1.17947533272554850e+00]], dtype=float) assert_allclose(expm(A_logm), A, rtol=1e-4) # Perturb the upper triangular matrix by tiny amounts, # so that it becomes technically not upper triangular. random.seed(1234) tiny = 1e-17 A_logm_perturbed = A_logm.copy() A_logm_perturbed[1, 0] = tiny with suppress_warnings() as sup: sup.filter(RuntimeWarning, "Ill-conditioned.*") A_expm_logm_perturbed = expm(A_logm_perturbed) rtol = 1e-4 atol = 100 * tiny assert_(not np.allclose(A_expm_logm_perturbed,
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 UserError class hr_payslip_line(osv.osv): ''' Payslip Line ''' _inherit = 'hr.payslip.line' def _get_partner_id(self, cr, uid, payslip_line, credit_account, context=None): """ Get partner_id of slip line to use in account_move_line """ # use partner of salary rule or fallback on employee's address partner_id = payslip_line.salary_rule_id.register_id.partner_id.id or \ payslip_line.slip_id.employee_id.address_home_id.id if credit_account: if payslip_line.salary_rule_id.register_id.partner_id or \ payslip_line.salary_rule_id.account_credit.internal_type in ('receivable', 'payable'): return partner_id else: if payslip_line.salary_rule_id.register_id.partner_id or \ payslip_line.salary_rule_id.account_debit.internal_type in ('receivable', 'payable'): return partner_id return False class hr_payslip(osv.osv): ''' Pay Slip ''' _inherit = 'hr.payslip' _description = 'Pay Slip' _columns = { 'date': fields.date('Date Account', states={'draft': [('readonly', False)]}, readonly=True, help="Keep empty to use the period of the validation(Payslip) date."), 'journal_id': fields.many2one('account.journal', 'Salary Journal',states={'draft': [('readonly', False)]}, readonly=True, required=True), 'move_id': fields.many2one('account.move', 'Accounting Entry', readonly=True, copy=False), } def _get_default_journal(self, cr, uid, context=None): journal_obj = self.pool.get('account.journal') res = journal_obj.search(cr, uid, [('type', '=', 'general')]) if res: return res[0] return False _defaults = { 'journal_id': _get_default_journal, } def create(self, cr, uid, vals, context=None): if context is None: context = {} if 'journal_id' in context: vals.update({'journal_id': context.get('journal_id')}) return super(hr_payslip, self).create(cr, uid, vals, context=context) def onchange_contract_id(self, cr, uid, ids, date_from, date_to, employee_id=False, contract_id=False, context=None): contract_obj = self.pool.get('hr.contract') res = super(hr_payslip, self).onchange_contract_id(cr, uid, ids, date_from=date_from, date_to=date_to, employee_id=employee_id, contract_id=contract_id, context=context) journal_id = contract_id and contract_obj.browse(cr, uid, contract_id, context=context).journal_id.id or False res['value'].update({'journal_id': journal_id}) return res def cancel_sheet(self, cr, uid, ids, context=None): move_pool = self.pool.get('account.move') move_ids = [] move_to_cancel = [] for slip in self.browse(cr, uid, ids, context=context): if slip.move_id: move_ids.append(slip.move_id.id) if slip.move_id.state == 'posted': move_to_cancel.append(slip.move_id.id) move_pool.button_cancel(cr, uid, move_to_cancel, context=context) move_pool.unlink(cr, uid, move_ids, context=context) return super(hr_payslip, self).cancel_sheet(cr, uid, ids, context=context) def process_sheet(self, cr, uid, ids, context=None): move_pool = self.pool.get('account.move') hr_payslip_li
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 name = _('Payslip of %s') % (slip.employee_id.name) move = { 'narration': name, 'ref': slip.number, 'journal_id': slip.journal_id.id, 'date': date, } for line in slip.details_by_salary_rule_category: amt = slip.credit_note and -line.total or line.total if float_is_zero(amt, precision_digits=precision): continue debit_account_id = line.salary_rule_id.account_debit.id credit_account_id = line.salary_rule_id.account_credit.id if debit_account_id: debit_line = (0, 0, { 'name': line.name, 'partner_id': hr_payslip_line_pool._get_partner_id(cr, uid, line, credit_account=False, context=context), 'account_id': debit_account_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': amt > 0.0 and amt or 0.0, 'credit': amt < 0.0 and -amt or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id and line.salary_rule_id.analytic_account_id.id or False, 'tax_line_id': line.salary_rule_id.account_tax_id and line.salary_rule_id.account_tax_id.id or False, }) line_ids.append(debit_line) debit_sum += debit_line[2]['debit'] - debit_line[2]['credit'] if credit_account_id: credit_line = (0, 0, { 'name': line.name, 'partner_id': hr_payslip_line_pool._get_partner_id(cr, uid, line, credit_account=True, context=context), 'account_id': credit_account_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': amt < 0.0 and -amt or 0.0, 'credit': amt > 0.0 and amt or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id and line.salary_rule_id.analytic_account_id.id or False, 'tax_line_id': line.salary_rule_id.account_tax_id and line.salary_rule_id.account_tax_id.id or False, }) line_ids.append(credit_line) credit_sum += credit_line[2]['credit'] - credit_line[2]['debit'] if float_compare(credit_sum, debit_sum, precision_digits=precision) == -1: acc_id = slip.journal_id.default_credit_account_id.id if not acc_id: raise UserError(_('The Expense Journal "%s" has not properly configured the Credit Account!') % (slip.journal_id.name)) adjust_credit = (0, 0, { 'name': _('Adjustment Entry'), 'date': timenow, 'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': 0.0, 'credit': debit_sum - credit_sum, }) line_ids.append(adjust_credit) elif float_compare(debit_sum, credit_sum, precision_digits=precision) == -1: acc_id = slip.journal_id.default_debit_account_id.id if not acc_id: raise UserError(_('The Expense Journal "%s" has not properly configured the Debit Account!') % (slip.journal_id.name)) adjust_debit = (0, 0, { 'name': _('Adjustment Entry'), 'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': credit_sum - debit_sum, 'credit': 0.0, }) line_ids.append(adjust_debit) move.updat
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 class Command(BaseCommand): help = 'Closes the specified poll for voting' option_list = BaseCommand.option_list + (make_option('--path', action='store', dest='basepath', default=None, help='The Path to the sql dir'),) def handle(self, *args, **options): #delete everything delitems = [Theme,Issue,Layer, PointLayer, Points] for delitem in delitems: delobjs = delitem.objects.all() for delobj in delobjs: print "deleting", delobj delobj.delete() BASE_DIR = options.get("basepath", None) if not BASE_DIR: print "Please provide the path to your SQL dir\nSuch as --path C:\\opengeo\\webapps\\DiplomacyExplorer2\\sql\\" sys.exit(1) pointscsvfile = "Points.csv" layerscsvfile = "Layers.csv" themescsvfile = "Themes.csv" issuescsvfile = "Issues.csv" pointsobj = [] #load points, we are going ot get the point layers from the point.csv file #this will be the following format #pointlayername;header;topic;map;country;title;story;lat;lon;locationname with open(BASE_DIR + pointscsvfile, 'rb') as f: headers = [] tempreader = csv.reader(f, delimiter=',') for row in tempreader: if len(headers) == 0: headers = row else: pointsobj.append(dict(zip(headers, row))) g = geocoders.GoogleV3() #create pointlayer for pointobj in pointsobj: temppointlayer, created = PointLayer.objects.get_or_create(layername=pointobj['pointlayername']) print temppointlayer #build the point temppoint, created = Points.objects.get_or_create(Title=pointobj['title'],pointlayer=temppointlayer) if (pointobj['lon'] != "" and pointobj['lat'] != ""): try: temppoint.geometry = [float(pointobj['lon']),float(pointobj['lat'])] except Exception, e: print e elif (pointobj['locationname'] != ""): place, (lat,lon) = g.geocode(pointobj['locationname']) print "geocoded", pointobj['locationname'], "to", lat,lon print temppoint temppoint.geometry = [lon, lat] else: print "Could not find the location for ", pointobj['pointlayername'] temppoint.delete() if temppoint: temppoint.Header = pointobj['header'] temppoint.Topic = pointobj['topic'] temppoint.Map = pointobj['map'] temppoint.Country = pointobj['country'] temppoint.Story = pointobj['story'] temppoint.save() layersobj = [] themesobj = [] issuesobj = [] #need to do this order themes, issues and layers with open(BASE_DIR + layerscsvfile, 'rb') as f: headers = [] tempreader = csv.reader(f, delimiter=';') for row in tempreader: if len(headers) == 0: headers = row else: layersobj.append(dict(zip(headers, row))) with open(BASE_DIR + themescsvfile, 'rb') as f: headers = [] tempreader = csv.reader(f, delimiter=',') for row in tempreader: if len(headers) == 0: headers = row else: themesobj.append(dict(zip(headers, row))) with open(BASE_DIR + issuescsvfile, 'rb') as f: headers = [] tempreader = csv.reader(f, delimiter=';') for row in tempreader: if len(headers) == 0: headers = row else: issuesobj.append(dict(zip(headers, row))) #get the temes #get the themes counter = 1 for themerow in themesobj: print "working on theme ", themerow['ThemeID'] #Name,Description,KeyID,ThemeID,ThemeDrop currenttheme, created = Theme.objects.get_or_create(keyid=themerow['ThemeID']) print currenttheme, created currenttheme.title = themerow['Name'] currenttheme.description = themerow['Description'] currenttheme.keyid = themerow['ThemeID'] currenttheme.order = counter counter +=1 currenttheme.save() for issuerow in issuesobj: #Name,Description,KeyID,ThemeID,ID try: themeobj = Theme.objects.get(keyid__exact=issuerow['ThemeID']) except: print "could not find themeobj for ", issuerow['KeyID'] else: currentissue, created = Issue.objects.get_or_create(keyid=issuerow['KeyID'], theme=themeobj) print currentissue, created currentissue.categoryName = issuerow['Name'] currentissue.categoryDescription = issuerow['Description'] currentissue.keyid = issuerow['KeyID'] currentissue.save() for layerrow in layersobj: #Name,Description,KeyID,Labels,IssueID,jsonStyle,PtsLayer,Attribution try: issueobj = Issue.objects.get(keyid__exact=layerrow['IssueID']) except: print "could not find issueobj for ", layerrow['IssueID'], "and layer name", layerrow['KeyID'] else: currentlayer,created = Layer.objects.get_or_create(keyid=layerrow['KeyID'], issue=issueobj) currentlayer.subject = layerrow['Name'] currentlayer.description = layerrow['Description'] currentlayer.keyid = layerrow['KeyID'] currentlayer.labels = layerrow['Labels'] currentlayer.jsonStyle = layerrow['jsonStyle'] try: temppointlayer = PointLayer.objects.get(layername__exact=layerrow['KeyID']) currentlayer.ptsLayer = temppointlayer except: pass currentlayer.attribution = layerrow['Attribution'] currentlayer.isTimeSupported = True if str(layerrow['isTimeSupported']) == "TRUE" else False if layerrow['isTimeSupported'] == "TRUE
": currentlayer.timeSeriesInfo = layerrow['timeSeriesInfo'] else: currentlayer.timeSeriesInfo = {} currentlayer.save() #now let's test print "*********we now have the following" themes = Theme.objects.all() print "we have ", len(themes), "Themes" for theme in themes:
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: print "\t\t\tIt has", layer.subject pointlayer = layer.ptsLayer if pointlayer: print "\t\t\t\tIt has ", pointlayer.layername points = pointlayer.points_set.all() print "\t\t\t\t", pointlayer.layername, "has", len(points)
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 from sqlalchemy import literal from sqlalchemy import literal_column from sqlalchemy import MetaData from sqlalchemy import or_ from sqlalchemy import outerjoin from sqlalchemy import schema from sqlalchemy import select from sqlalchemy import Sequence from sqlalchemy import sql from sqlalchemy import String from sqlalchemy import testing from sqlalchemy import text from sqlalchemy import type_coerce from sqlalchemy import TypeDecorator from sqlalchemy import union from sqlalchemy.dialects.oracle import base as oracle from sqlalchemy.dialects.oracle import cx_oracle from sqlalchemy.engine import default from sqlalchemy.sql import column from sqlalchemy.sql import ddl from sqlalchemy.sql import quoted_name from sqlalchemy.sql import table from sqlalchemy.sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL from sqlalchemy.testing import assert_raises_message from sqlalchemy.testing import AssertsCompiledSQL from sqlalchemy.testing import eq_ from sqlalchemy.testing import fixtures from sqlalchemy.testing.assertions import eq_ignore_whitespace from sqlalchemy.testing.schema import Column from sqlalchemy.testing.schema import Table class CompileTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = "oracle" def test_true_false(self): self.assert_compile(sql.false(), "0") self.assert_compile(sql.true(), "1") def test_owner(self): meta = MetaData() parent = Table( "parent", meta, Column("id", Integer, primary_key=True), Column("name", String(50)), schema="ed", ) child = Table( "child", meta, Column("id", Integer, primary_key=True), Column("parent_id", Integer, ForeignKey("ed.parent.id")), schema="ed", ) self.assert_compile( parent.join(child), "ed.parent JOIN ed.child ON ed.parent.id = " "ed.child.parent_id", ) def test_subquery(self): t = table("sometable", column("col1"), column("col2")) s = select(t).subquery() s = select(s.c.col1, s.c.col2) self.assert_compile( s, "SELECT anon_1.col1, anon_1.col2 FROM (SELECT " "sometable.col1 AS col1, sometable.col2 " "AS col2 FROM sometable) anon_1", ) def test_bindparam_quote(self): """test that bound parameters take on quoting for reserved words, column names quote flag enabled.""" # note: this is only in cx_oracle at the moment. not sure # what other hypothetical oracle dialects might need self.assert_compile(bindparam("option"), ':"option"') self.assert_compile(bindparam("plain"), ":plain") t = Table("s", MetaData(), Column("plain", Integer, quote=True)) self.assert_compile( t.insert().values(plain=5), 'INSERT INTO s ("plain") VALUES (:"plain")', ) self.assert_compile( t.update().values(plain=5), 'UPDATE s SET "plain"=:"plain"' ) def test_bindparam_quote_works_on_expanding(self): self.assert_compile( bindparam("uid", expanding=True), "([POSTCOMPILE_uid])", dialect=cx_oracle.dialect(), ) def test_cte(self): part = table( "part", column("part"), column("sub_part"), column("quantity") ) included_parts = ( select(part.c.sub_part, part.c.part, part.c.quantity) .where(part.c.part == "p1") .cte(name="included_parts", recursive=True) .suffix_with( "search depth first by part set ord1", "cycle part set y_cycle to 1 default 0", dialect="oracle", ) ) incl_alias = included_parts.alias("pr1") parts_alias = part.alias("p") included_parts = included_parts.union_all( select( parts_alias.c.sub_part, parts_alias.c.part, parts_alias.c.quantity, ).where(parts_alias.c.part == incl_alias.c.su
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 = :part_1 " "UNION ALL SELECT p.sub_part AS sub_part, p.part AS part, " "p.quantity AS quantity FROM part p, included_parts pr1 " "WHERE p.part = pr1.sub_part) " "search depth first by part set ord1 cycle part set " "y_cycle to 1 default 0 " "SELECT included_parts.sub_part, sum(included_parts.quantity) " "AS total_quantity FROM included_parts " "GROUP BY included_parts.sub_part", ) def test_limit_one(self): t = table("sometable", column("col1"), column("col2")) s = select(t) c = s.compile(dialect=oracle.OracleDialect()) assert t.c.col1 in set(c._create_result_map()["col1"][1]) s = select(t).limit(10).offset(20) self.assert_compile( s, "SELECT anon_1.col1, anon_1.col2 FROM " "(SELECT anon_2.col1 AS col1, " "anon_2.col2 AS col2, ROWNUM AS ora_rn FROM (SELECT " "sometable.col1 AS col1, sometable.col2 AS " "col2 FROM sometable) anon_2 WHERE ROWNUM <= " "[POSTCOMPILE_param_1] + [POSTCOMPILE_param_2]) anon_1 " "WHERE ora_rn > " "[POSTCOMPILE_param_2]", checkparams={"param_1": 10, "param_2": 20}, ) c = s.compile(dialect=oracle.OracleDialect()) eq_(len(c._result_columns), 2) assert t.c.col1 in set(c._create_result_map()["col1"][1]) def test_limit_one_literal_binds(self): """test for #6863. the bug does not appear to have affected Oracle's case. """ t = table("sometable", column("col1"), column("col2")) s = select(t).limit(10).offset(20) c = s.compile( dialect=oracle.OracleDialect(), compile_kwargs={"literal_binds": True}, ) eq_ignore_whitespace( str(c), "SELECT anon_1.col1, anon_1.col2 FROM " "(SELECT anon_2.col1 AS col1, anon_2.col2 AS col2, " "ROWNUM AS ora_rn FROM (SELECT sometable.col1 AS col1, " "sometable.col2 AS col2 FROM sometable) anon_2 " "WHERE ROWNUM <= 10 + 20) anon_1 WHERE ora_rn > 20", ) def test_limit_one_firstrows(self): t = table("sometable", column("col1"), column("col2")) s = select(t) s = select(t).limit(10).offset(20) self.assert_compile( s, "SELECT anon_1.col1, anon_1.col2 FROM " "(SELECT /*+ FIRST_ROWS([POSTCOMPILE_param_1]) */ " "anon_2.col1 AS col1, " "anon_2.col2 AS col2, ROWNUM AS ora_rn FROM (SELECT " "sometable.col1 AS col1, sometable.col2 AS " "col2 FROM sometable) anon_2 WHERE ROWNUM <= " "[POSTCOMPILE_param_1] + [POSTCOMPILE_param_2]) anon_1 " "WHERE ora_rn > " "[POSTCOMPILE_param_2]", checkparams={"param_1": 10, "param_2": 20}, dialect=oracle.OracleDialect(optimize_limits=True), ) def test_limit_two(self): t = table("sometable", column("col1"), column("col2")) s = select(t).limit(10).offset(20).subquery() s2 = select(s.c.col1, s.c.col2) self.assert_compile( s2, "SELEC
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() self.mock_natural_user_wallet() self.register_mock([ { 'method': responses.POST, 'url': settings.MANGOPAY_API_SANDBOX_URL+settings.MANGOPAY_CLIENT_ID+'/wallets/116
9420/bankingaliases/iban', 'body': { "OwnerName": "Victor", "IBAN": "LU32062DZDP2JLJU9RP3", "BIC": "MPAYFRP1EMI", "CreditedUserId":"25337926", "Country":"LU", "Tag": "null", "CreationDate":1494384060, "Active": True, "Type":"IBAN",
"Id":"25337928", "WalletId":"1169420" }, 'status': 200 }, { 'method': responses.GET, 'url': settings.MANGOPAY_API_SANDBOX_URL+settings.MANGOPAY_CLIENT_ID+'/bankingaliases/25337928', 'body': { "OwnerName": "Victor", "IBAN": "LU32062DZDP2JLJU9RP3", "BIC": "MPAYFRP1EMI", "CreditedUserId":"25337926", "Country":"LU", "Tag": "null", "CreationDate":1494384060, "Active": True, "Type":"IBAN", "Id":"25337928", "WalletId":"1169420" }, 'status': 200 }, { 'method': responses.GET, 'url': settings.MANGOPAY_API_SANDBOX_URL+settings.MANGOPAY_CLIENT_ID+'/wallets/1169420/bankingaliases', 'body': [ { "OwnerName": "Victor", "IBAN": "LU32062DZDP2JLJU9RP3", "BIC": "MPAYFRP1EMI", "CreditedUserId":"25337926", "Country":"LU", "Tag": "null", "CreationDate":1494384060, "Active": True, "Type":"IBAN", "Id":"25337928", "WalletId":"1169420" } ], 'status': 200 }]) bankingAlias = BankingAliasIBAN( wallet = self.natural_user_wallet, credited_user = self.natural_user, owner_name = self.natural_user.first_name, country ='LU' ) bankingAlias.save() self.assertEqual(bankingAlias.country, 'LU') self.assertEqual(bankingAlias.iban, 'LU32062DZDP2JLJU9RP3') walletBankingAliases = BankingAlias( wallet = self.natural_user_wallet ) allBankingAliases = walletBankingAliases.all() self.assertEqual(allBankingAliases[0].id, bankingAlias.id) self.assertEqual(allBankingAliases[0].wallet_id, bankingAlias.wallet_id)
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', field=models.BooleanField(d
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=0; list4=0; nlist=0; integerM=0; integerN=0; # checkboxes checkboxValues=0; checkbox1=0; checkbox2=0; checkbox3=0; checkbox4=0; checkbox5=0; checkbox6=0; checkbox7=0; checkbox8=0; checkbox9=0; # order checkboxes orderboxValues=0; orderbox1=0; orderbox2=0; orderbox3=0; orderbox4=0; orderbox5=0; orderbox6=0; orderbox7=0; orderbox8=0; orderbox9=0; orderbox10=0; # buttons btn1=0; btn2=0; # tune names horTuneName=''; verTuneName=''; rfFreqName=''; harNumName=''; def __init__(self, parent, tune, order, rangeValues=[2,3,3,4,3,2],checkboxValues=[True,True,True,True,True,False,False,False,False], orderboxValues=[True,True,True,False,False,False,False,False,False,False]): self.window=wx.App(); # variables self.tune = tune; self.parent = parent; self.rangeValues=rangeValues; self.checkboxValues=checkboxValues; self.orderboxValues=orderboxValues; # init frame frame = wx.Frame(None, -1, 'Settings', style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER); self.frame = frame; # init panel self.panel = wx.Panel(self.frame, -1); #construct everything self.initialize(); self.frame.Show(True); self.frame.SetSize(self.size); self.frame.Centre(); self.panel.SetSizer(self.sizer); # close window self.frame.Bind(wx.EVT_CLOSE, self.onClose); self.window.MainLoop() def initialize(self): # init sizer self.sizer = wx.GridBagSizer(10, 5); # adding live mode box box0 = wx.StaticBox(self.panel, label="Live Mode options"); boxsizer0 = wx.StaticBoxSizer(box0, wx.VERTICAL); hbox1 = wx.BoxSizer(wx.HORIZONTAL); txt1 = wx.StaticText(self.panel, label="Horizontal freq:"); hbox1.Add(txt1,flag=wx.ALIGN_CENTER,border=5); hbox1.Add((5,-1)); pvNames = self.parent.getpvNames(); self.horTuneName = wx.TextCtrl(self.panel, size=(120, -1)); self.horTuneName.SetValue(pvNames[0]); hbox1.Add(self.horTuneName,border=5); hbox1.Add((10,-1)); txt2 = wx.StaticText(self.panel, label="Vertical freq:"); hbox1.Add(txt2,flag=wx.ALIGN_CENTER,border=5); hbox1.Add((5,-1)); self.verTuneName = wx.TextCtrl(self.panel, size=(120, -1)); self.verTuneName.SetValue(pvNames[1]); hbox1.Add(self.verTuneName,border=5); hbox1.Add((5,-1)); boxsizer0.Add(hbox1,border=5); hbox2 = wx.BoxSizer(wx.HORIZONTAL); txt1 = wx.StaticText(self.panel, label='RF Freq: '); hbox2.Add(txt1, flag=wx.ALIGN_CENTER,border=5); hbox2.Add((5,-1)); self.rfFreqName = wx.TextCtrl(self.panel, size=(120, -1)); self.rfFreqName.SetValue(pvNames[2]); hbox2.Add(self.rfFreqName,border=5); hbox2.Add((10,-1)); txt2 = wx.StaticText(self.panel, label="Harmonic #:"); hbox2.Add(txt2,flag=wx.ALIGN_CENTER,border=5); hbox2.Add((5,-1)); self.harNumName = wx.TextCtrl(self.panel, size=(120, -1)); self.harNumName.SetValue(pvNames[3]); hbox2.Add(self.harNumName,border=5); hbox2.Add((5,-1)); boxsizer0.Add(hbox2,border=5); self.sizer.Add(boxsizer0,pos=(0,1),span=(3,6),flag=wx.ALIGN_CENTER|wx.CENTER,border=5); # Adding graphical options box box1 = wx.StaticBox(self.panel, label="Graphical options"); boxsizer1 = wx.StaticBoxSizer(box1, wx.VERTICAL); self.checkbox1 = wx.CheckBox(self.panel, label="Horizontal resonances"); boxsizer1.Add(self.checkbox1, flag=wx.LEFT|wx.TOP,border=5); if self.checkboxValues[0]: self.checkbox1.Set3StateValue(wx.CHK_CHECKED); self.checkbox2 = wx.CheckBox(self.panel, label='Vertical resonances'); boxsizer1.Add(self.checkbox2, flag=wx.LEFT,border=5); if self.checkboxValues[1]: self.checkbox2.Set3StateValue(wx.CHK_CHECKED); self.checkbox3 = wx.CheckBox(self.panel, label='Summing resonances'); boxsizer1.Add(self.checkbox3, flag=wx.LEFT,border=5); if self.checkboxValues[2]: self.checkbox3.Set3StateValue(wx.CHK_CHECKED); self.checkbox4 = wx.CheckBox(self.panel, label='DIfference resonances'); boxsizer1.Add(self.checkbox4, flag=wx.LEFT|wx.BOTTOM,border=5); if self.checkboxValues[3]: self.checkbox4.Set3StateValue(wx.CHK_CHECKED); self.sizer.Add(boxsizer1, pos=(3,1), span=(1,3),flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.RIGHT,border=10); # Adding color scheme box box2 = wx.StaticBox(self.panel, label="Color scheme"); boxsizer2 = wx.StaticBoxSizer(box2, wx.VERTICAL); self.checkbox5 = wx.CheckBox(self.panel, label='Random'); boxsizer2.Add(self.checkbox5, flag=wx.LEFT|wx.TOP,border=5); if self.checkboxValues[4]: self.checkbox5.Set3StateValue(wx.CHK_CHECKED); self.checkbox6 = wx.CheckBox(self.panel, label='Black'); boxsizer2.Add(self.checkbox6, flag=wx.LEFT,border=5); if self.checkboxValues[5]: self.checkbox6.Set3StateValue(wx.CHK_CHECKED); self.checkbox7 = wx.CheckBox(self.panel, label='By order'); boxsizer2.Add(self.checkbox7, flag=wx.LEFT|wx.BOTTOM,border=5); if self.checkboxValues[6]: self.checkbox7.Set3StateValue(wx.CHK_CHECKED); self.sizer.Add(boxsizer2, pos=(3,4), span=(1,2), flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.RIGHT,border=10); # Adding order box box3 = wx.StaticBox(self.panel, label="Order",style=wx.CENTER); boxsizer3 = wx.StaticBoxSizer(box3, wx.HORIZONTAL); hbox = wx.BoxSizer(wx.HORIZONTAL); self.orderbox1 = wx.CheckBox(self.panel, label='1'); hbox.Add(self.orderbox1,flag=wx.LEFT); hbox.Add((5,-1)); if self.orderboxValues[0]: self.orderbox1.Set3StateValue(wx.CHK_CHECKED); self.orderbox2 = wx.CheckBox(self.panel, label='2'); hbox.Add(self.orderbox2,flag=wx.LEFT); hbox.Add((5,-1)); if self.orderboxValues[1]: self.orderbox2.Set3StateValue(wx.CHK_CHECKED); self.orderbox3 = wx.CheckBox(self.panel, label='3'); hbox.Add(self.orderbox3,flag=wx.LEFT); hbox.Add((5,-1)); if self.orderboxValues[2]: self.orderbox3.Set3StateValue(wx
.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)); if self.orderboxValues[5]: self.orderbox6.Set3StateValue(wx.CHK_CHECKED); self.orderbox7 = wx.CheckBox(self.panel, label='7'); hbox.Add(self.orderbox7,flag=wx.LEFT); hbox.Add((5,-1)); if self.orderboxValues[6]: self.orderbox7.Set3StateValue(wx.CHK_CHECKED); self.orderbox8 = wx.CheckBox(self.panel, label='8'); hbox.Add(self.orderbox8,flag=wx.LEFT); hbox.Add((5,-1)); if self.orderboxValues[7]: self.orderbox8.Set3StateValue(wx.CHK_CHECKED); self.orderbox9 = wx.CheckBox(self.panel, label='9'); hbox.Add(self.orderbox9,flag=wx.LEFT); hbox.Add
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 poly in getBlock(wedge_poly, vertex_list): if poly.poly_type == "lot": properties += divide(poly) else: properties.append(poly) return properties if __name__ == "__main__": import sys from procedural_city_generation.polygons.parent_path import parent_path sys.path.append(parent_path(depth=3)) import matplotlib.pyplot as plt import construct_polygons as cp polys, vertices = cp.main() lots = getLots(polys, vertices) print("%s lots found" %(len(lots))) for p in lots: p.selfplot() plt.show()
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 ActionCheckButton from designer.uix.contextual import ContextSubMenu class DesignerActionPrevious(ActionPrevious): pass class DesignerActionSubMenu(ContextSubMenu, ActionButton): pass class DesignerActionProfileCheck(ActionCheckButton): '''DesignerActionSubMenuCheck a :class `~designer.uix.actioncheckbutton.ActionCheckButton` It's used to create radio buttons to action menu ''' config_key = StringProperty('') '''Dict key to the profile config_parser :data:`config_key` is a :class:`~kivy.properties.StringProperty`, default to ''. ''' def __init__(self, **kwargs): super(DesignerActionProfileCheck, self).__init__(**kwargs) self.minimum_width = 200
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.StringProperty` and defaults to 'Button' ''' desc = StringProperty('') '''text which is displayed as description to DesignerActionButton. :data:`desc` is a :class:`~kivy.properties.StringProperty` and defaults to '' ''' cont_menu = ObjectProperty(None) def __init__(self, **kwargs): super(DesignerActionButton, self).__init__(**kwargs) self.minimum_width = 200 def on_press(self, *args): ''' Event to hide the ContextualMenu when a ActionButton is pressed ''' self.cont_menu.dismiss()
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_data_dir_exists(self, path_isdir_mock): path_isdir_mock.side_effect = always_true workspace = Workspace("db", "oracle") ret = workspace.workspace_data_dir_exists() self.assertEqual(True, ret) @patch('os.path.isdir') def test_workspace_data_dir_exists_should_return_false_when_data_dir_not_exists(self, path_isdir_mock): path_isdir_mock.side_effect = always_false workspace = Workspace("db", "oracle") ret = workspace.workspace_data_dir_exists() self.assertEqual(False, ret) @patch('os.path.exists') def test_workspace_config_exists_should_return_true_when_config_exists(self, path_exists_mock): path_exists_mock.side_effect = always_true workspace = Workspace("db", "oracle") ret = workspace.workspace_config_exists() self.assertEqual(True, ret) @patch('os.path.exists') def test_workspace_config_exists_should_return_false_when_config_not_exists(self, path_exists_mock): path_exists_mock.side_effect = always_false workspace = Workspace("db", "oracle") ret = workspace.workspace_config_exists() self.assertEqual(False, ret) @patch('os.path.exists') @patch('os.path.isdir') def test_validate_should_return_true_when_data_dir_and_config_exists(self, path_exists_mock, path_isdir_mock): path_exists_mock.side_effect = always_true path_isdir_mock.side_effect =
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_exists_mock.side_effect = always_false path_isdir_mock.side_effect = always_false
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 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. # # Author: Sajjad "JJ" Arshad (sajjadium) from os.path import join import json import os import random import shlex import string import subprocess import sys import time import base64 ADB_PORT = int(random.random() * 60000 + 5000) EMULATOR_PORT = ADB_PORT + 1 EXPLOIT_TIME_SECS = 30 APK_FILE = "/challenge/app.apk" FLAG_FILE = "/challenge/flag" HOME = "/home/user" ENV = {} ENV.update(os.environ) ENV.update({ "ANDROID_ADB_SERVER_PORT": "{}".format(ADB_PORT), "ANDROID_SERIAL": "emulator-{}".format(EMULATOR_PORT), "ANDROID_SDK_ROOT": "/opt/android/sdk", "ANDROID_SDK_HOME": HOME, "ANDROID_PREFS_ROOT": HOME, "ANDROID_EMULATOR_HOME": HOME + "/.android", "ANDROID_AVD_HOME": HOME + "/.android/avd", "JAVA_HOME": "/usr/lib/jvm/java-11-openjdk-amd64", "PATH": "/opt/android/sdk/cmdline-tools/latest/bin:/opt/android/sdk/emulator:/opt/android/sdk/platform-tools:/bin:/usr/bin:" + os.environ.get("PATH", "") }) def print_to_user(message): print(message) sys.stdout.flush() def setup_emulator(): subprocess.call( "avdmanager" + " create avd" + " --name 'pixel_4_xl_api_30'" + " --abi 'google_apis/x86_64'" + " --package 'system-images;android-30;google_apis;x86_64'" + " --device pixel_4_xl" + " --force" + " > /dev/null 2> /dev/null", env=ENV, close_fds=True, shell=True) return subprocess.Popen( "emulator" + " -avd pixel_4_xl_api_30" + " -n
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): return subprocess.run( "adb {} 2> /dev/null".format(" ".join(args)), env=ENV, shell=True, close_fds=True, capture_output=capture_output).stdout def adb_install(apk): adb(["install", "-r", apk]) def adb_activity(activity): adb(["shell", "am", "start", "-W", "-n", activity]) def adb_logs(): logs = adb(["logcat", "-d", "-s", "TriDroid"], True) for log in logs.decode("utf-8").strip().split("\n"): print_to_user(log) def adb_broadcast(action, extras=None): args = ["shell", "am", "broadcast", "-a", action] if extras: for key in extras: args += ["-e", key, extras[key]] adb(args) print_to_user(""" Welcome to TriDroid, the Triangle of Android: /\\ DEX / \\ Web (Java & Kotlin) / \\ (HTML & JS) / \\ /________\\ Native (C & C++) """) print_to_user("Preparing TriDroid. This may take a while ...\n") emulator = setup_emulator() adb(["wait-for-device"]) adb_install(APK_FILE) adb_activity("com.google.ctf.pwn.tridroid/.MainActivity") with open(FLAG_FILE, "r") as f: adb_broadcast("com.google.ctf.pwn.tridroid.SET_FLAG", extras = { "data": base64.b64encode(f.read().encode()).decode() }) print_to_user("Please enter your name encoded in base64:") name = sys.stdin.readline().strip() adb_broadcast("com.google.ctf.pwn.tridroid.SET_NAME", extras = { "data": name }) print_to_user("Thank you! Check out the logs. This may take a while ...\n") time.sleep(EXPLOIT_TIME_SECS) adb_logs() emulator.kill()
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 <lazycat.manatee@gmail.com> # Maintainer: Wang Yong <lazycat.manatee@gmail.com> # Reza Faiz A <ylpmiskrad@gmail.com> # Remixed : Reza Faiz A <ylpmiskrad@gmail.com> # # 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 # any later version. # # 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 this program. If not, see <http://www.gnu.org/licenses/>. from appItem import * from constant import * from draw import * from lang import __, getDefaultLanguage from theme import * import appView import glib import gtk import pango import utils class UpdateItem(DownloadItem): '''Application item.''' MAX_CHARS = 50 VERSION_MAX_CHARS = 30 APP_LEFT_PADDING_X = 5 STAR_PADDING_X = 2 NORMAL_PADDING_X = 2 VOTE_PADDING_X = 3 VOTE_PADDING_Y = 1 VERSION_LABEL_WIDTH = 120 SIZE_LABEL_WIDTH = 60 def __init__(self, appInfo, switchStatus, downloadQueue, entryDetailCallback, sendVoteCallback, index, getSelectIndex, setSelectIndex, selectPkgCallback, unselectPkgCallback, getSelectStatusCallback, addIgnorePkgCallback): '''Init for application item.''' DownloadItem.__init__(self, appInfo, switchStatus, downloadQueue) self.appInfo = appInfo self.entryDetailCallback = entryDetailCallback self.sendVoteCallback = sendVoteCallback self.selectPkgCallback = selectPkgCallback self.unselectPkgCallback = unselectPkgCallback self.getSelectStatusCallback = getSelectStatusCallback self.addIgnorePkgCallback = addIgnorePkgCallback self.checkButton = None self.index = index self.setSelectIndex = setSelectIndex # Widget that status will change. self.upgradingProgressbar = None self.upgradingFeedbackLabel = None # Init. self.itemBox = gtk.HBox() self.itemEventBox = gtk.EventBox() self.itemEventBox.connect("button-press-event", self.clickItem) self.itemEventBox.add(self.itemBox) drawListItem(self.itemEventBox, index, getSelectIndex) self.itemFrame
= 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.toggleSelectStatus()) checkButtonSetBackground( self.checkButton, False, False, "cell/select.png", "cell/selected.png", ) self.checkAlign = gtk.Alignment() self.checkAlign.set(0.5, 0.5, 0.0, 0.0) self.checkAlign.set_padding(checkPaddingY, checkPaddingY, checkPaddingLeft, checkPaddingRight) self.checkAlign.add(self.checkButton) self.itemBox.pack_start(self.checkAlign, False, False) self.appBasicView = AppBasicView(self.appInfo, 300 + APP_BASIC_WIDTH_ADJUST, self.itemBox, self.entryDetailView) self.itemBox.pack_start(self.appBasicView.align, True, True) self.appAdditionBox = gtk.HBox() self.appAdditionAlign = gtk.Alignment() self.appAdditionAlign.set(1.0, 0.5, 0.0, 0.0) self.appAdditionAlign.add(self.appAdditionBox) self.itemBox.pack_start(self.appAdditionAlign, False, False) self.initAdditionStatus() self.itemFrame.show_all() def toggleSelectStatus(self): '''Toggle select status.''' selectStatus = self.checkButton.get_active() pkgName = utils.getPkgName(self.appInfo.pkg) if selectStatus: self.selectPkgCallback(pkgName) else: self.unselectPkgCallback(pkgName) def entryDetailView(self): '''Entry detail view.''' self.entryDetailCallback(PAGE_UPGRADE, self.appInfo) def clickItem(self, widget, event): '''Click item.''' if utils.isDoubleClick(event): self.entryDetailView() else: self.setSelectIndex(self.index) def initAdditionStatus(self): '''Add addition status.''' status = self.appInfo.status if status == APP_STATE_UPGRADE: self.initNormalStatus() elif status == APP_STATE_DOWNLOADING: self.initDownloadingStatus(self.appAdditionBox) elif status == APP_STATE_DOWNLOAD_PAUSE: self.initDownloadPauseStatus(self.appAdditionBox) elif status == APP_STATE_UPGRADING: self.initUpgradingStatus() self.itemFrame.show_all() def initNormalStatus(self): '''Init normal status.''' pkg = self.appInfo.pkg # Clean right box first. utils.containerRemoveAll(self.appAdditionBox) # Add application vote information. self.appVoteView = VoteView( self.appInfo, PAGE_UPGRADE, self.sendVoteCallback) self.appAdditionBox.pack_start(self.appVoteView.eventbox, False, False) # Add application size. size = utils.getPkgSize(pkg) appSizeLabel = DynamicSimpleLabel( self.appAdditionBox, utils.formatFileSize(size), appTheme.getDynamicColor("appSize"), LABEL_FONT_SIZE, ) appSize = appSizeLabel.getLabel() appSize.set_size_request(self.SIZE_LABEL_WIDTH, -1) appSize.set_alignment(1.0, 0.5) self.appAdditionBox.pack_start(appSize, False, False, self.APP_RIGHT_PADDING_X) # Add ignore button. (ignoreLabel, ignoreEventBox) = setDefaultClickableDynamicLabel( __("Don't Notify"), "appIgnore", ) self.appAdditionBox.pack_start(ignoreEventBox, False, False) ignoreEventBox.connect("button-press-event", lambda w, e: self.addIgnorePkgCallback(utils.getPkgName(pkg))) # Add action button. (actionButtonBox, actionButtonAlign) = createActionButton() self.appAdditionBox.pack_start(actionButtonAlign, False, False) (appButton, appButtonAlign) = newActionButton( "update", 0.5, 0.5, "cell", False, __("Action Update"), BUTTON_FONT_SIZE_SMALL, "buttonFont") appButton.connect("button-release-event", lambda widget, event: self.switchToDownloading()) actionButtonBox.pack_start(appButtonAlign) def updateVoteView(self, starLevel, commentNum): '''Update vote view.''' if self.appInfo.status == APP_STATE_UPGRADE and self.appVoteView != None: self.appVoteView.updateVote(starLevel, commentNum) self.appBasicView.updateCommentNum(commentNum) class UpdateView(appView.AppView): '''Application view.''' def __init__(self, repoCache, switchStatus, downloadQueue, entryDetailCallback, sendVoteCallback, fetchVoteCallback, addIgnorePkgCallback): '''Init for application view.''' appNum = repoCache.getUpgradableNum() appView.AppView.__init__(self, appNum, PAGE_UPGRADE) # Init. self.repoCache = repoCache self.getListFunc = self.repoCache.getUpgradableAppList self.switchStatus = swi
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 functions as deprecated. It will result in a warning being emitted when the function is used. :param func: :return: new_func """ def new_func(*args, **kwargs): warnings.warn("Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning) return func(*args, **kwargs) new_func.__name__ = func.__name__ new_func.__doc__ = func.__doc__ ne
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 better. class DerivedTestCase2(TestCase): # pylint: disable=test-inherits-tests def test_two(self): pass # No big deal, the base class isn't a test. class TestHelpers(unittest.TestCase): __test__ = False def test_one(self): pass class TestsWithHelpers(TestHelpers): __test__ = True def test_two(self): pass # Bad: this base class is a test. class TestHelpers2(unittest.TestCase): __test__ = True
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__ = "henne@dcsec.uni-hannover.de" __copyright__ = "(c) 1997-2003 C. Taylor, 2010-2011, DCSec, Leibniz Universitaet Hannover, Germany" __license__ = """ The Python code is based on Javascript code of Charles L. Taylor from http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html The author allowed us to reuse his code. Original license: The documents, images, and other materials on the Chuck Taylor Web site are copyright (c) 1997-2003 by C. Taylor, unless otherwise noted. Visitors are permitted to download the materials located on the Chuck Taylor Web site to their own systems, on a temporary basis, for the purpose of viewing them or, in the case of software applications, using them in accordance with their intended purpose. Republishing or redistribution of any of the materials located on the Chuck Taylor Web site requires permission from C. Taylor. MoSP has been granted t
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 given longitude.""" return floor((lon + 180.0) / 6) + 1 def rad_to_deg(rad): """Converts radians to degrees.""" return (rad / pi * 180.0) def deg_to_rad(deg): """Converts degrees to radians.""" return (deg / 180.0 * pi) def UTMCentralMeridian(zone): """Calculates the central meridian for the given UTM-zone.""" return deg_to_rad(-183.0 + (zone * 6.0)) def ArcLengthOfMeridian(phi): """Computes the ellipsoidal distance from the equator to a point at a given latitude. Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J., GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994.""" # Precalculate n n = (sm_a - sm_b) / (sm_a + sm_b) # Precalculate alpha alpha = (((sm_a + sm_b) / 2.0) * (1.0 + (n**2.0 / 4.0) + (n**4.0 / 64.0))) # Precalculate beta beta = ((-3.0 * n / 2.0) + (9.0 * n**3.0 / 16.0) + (-3.0 * n**5.0 / 32.0)) # Precalculate gamma gamma = ((15.0 * n**2.0 / 16.0) + (-15.0 * n**4.0 / 32.0)) # Precalculate delta delta = ((-35.0 * n**3.0 / 48.0) + (105.0 * n**5.0 / 256.0)) # Precalculate epsilon epsilon = (315.0 * n**4.0 / 512.0) # Now calculate the sum of the series and return result = (alpha * (phi + (beta * sin(2.0 * phi)) + (gamma * sin(4.0 * phi)) + (delta * sin(6.0 * phi)) + (epsilon * sin(8.0 * phi)))) return result def MapLatLonToXY(phi, lambd, lambd0, xy): """Converts a latitude/longitude pair to x and y coordinates in the Transverse Mercator projection. Note that Transverse Mercator is not the same as UTM a scale factor is required to convert between them. Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J., GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994.""" # Precalculate ep2 ep2 = (sm_a**2.0 - sm_b**2.0) / sm_b**2.0 # Precalculate nu2 nu2 = ep2 * cos(phi)**2.0 # Precalculate N N = sm_a**2.0 / (sm_b * sqrt(1 + nu2)) # Precalculate t t = tan(phi) t2 = t**2.0 # Precalculate l l = lambd - lambd0 # Precalculate coefficients for l**n in the equations below # so a normal human being can read the expressions for easting # and northing # -- l**1 and l**2 have coefficients of 1.0 l3coef = 1.0 - t2 + nu2 l4coef = 5.0 - t2 + 9 * nu2 + 4.0 * (nu2**2.0) l5coef = 5.0 - 18.0 * t2 + (t2**2.0) + 14.0 * nu2 - 58.0 * t2 * nu2 l6coef = 61.0 - 58.0 * t2 + (t2**2.0) + 270.0 * nu2 - 330.0 * t2 * nu2 l7coef = 61.0 - 479.0 * t2 + 179.0 * (t2**2.0) - (t2**3.0) l8coef = 1385.0 - 3111.0 * t2 + 543.0 * (t2**2.0) - (t2**3.0) # Calculate easting (x) xy[0] = (N * cos(phi) * l + (N / 6.0 * cos(phi)**3.0 * l3coef * l**3.0) + (N / 120.0 * cos(phi)**5.0 * l5coef * l**5.0) + (N / 5040.0 * cos(phi)**7.0 * l7coef * l**7.0)) # Calculate northing (y) xy[1] = (ArcLengthOfMeridian(phi) + (t / 2.0 * N * cos(phi)**2.0 * l**2.0) + (t / 24.0 * N * cos(phi)**4.0 * l4coef * l**4.0) + (t / 720.0 * N * cos(phi)**6.0 * l6coef * l**6.0) + (t / 40320.0 * N * cos(phi)**8.0 * l8coef * l**8.0)) return def latlong_to_utm(lon, lat, zone = None): """Converts a latitude/longitude pair to x and y coordinates in the Universal Transverse Mercator projection.""" if zone is None: zone = long_to_zone(lon) xy = [0, 0] MapLatLonToXY(deg_to_rad(lat), deg_to_rad(lon), UTMCentralMeridian(zone), xy) xy[0] = xy[0] * UTMScaleFactor + 500000.0 xy[1] = xy[1] * UTMScaleFactor if xy[1] < 0.0: xy[1] = xy[1] + 10000000.0 return [round(coord, 2) for coord in xy] def FootpointLatitude(y): """Computes the footpoint latitude for use in converting transverse Mercator coordinates to ellipsoidal coordinates. Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J., GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994.""" # Precalculate n (Eq. 10.18) n = (sm_a - sm_b) / (sm_a + sm_b) # Precalculate alpha_ (Eq. 10.22) # (Same as alpha in Eq. 10.17) alpha_ = (((sm_a + sm_b) / 2.0) * (1 + (n**2.0 / 4) + (n**4.0 / 64))) # Precalculate y_ (Eq. 10.23) y_ = y / alpha_ # Precalculate beta_ (Eq. 10.22) beta_ = ((3.0 * n / 2.0) + (-27.0 * n**3.0 / 32.0) + (269.0 * n**5.0 / 512.0)) # Precalculate gamma_ (Eq. 10.22) gamma_ = ((21.0 * n**2.0 / 16.0) + (-55.0 * n**4.0 / 32.0)) # Precalculate delta_ (Eq. 10.22) delta_ = ((151.0 * n**3.0 / 96.0) + (-417.0 * n**5.0 / 128.0)) # Precalculate epsilon_ (Eq. 10.22) epsilon_ = ((1097.0 * n**4.0 / 512.0)) # Now calculate the sum of the series (Eq. 10.21) result = (y_ + (beta_ * sin(2.0 * y_)) + (gamma_ * sin(4.0 * y_)) + (delta_ * sin(6.0 * y_)) + (epsilon_ * sin(8.0 * y_))) return result def MapXYToLatLon(x, y, lambda0): """Converts x and y coordinates in the Transverse Mercator projection to a latitude/longitude pair. Note that Transverse Mercator is not the same as UTM a scale factor is required to convert between them. Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J., GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994. Remarks: The local variables Nf, nuf2, tf, and tf2 serve the same purpose as N, nu2, t, and t2 in MapLatLonToXY, but they are computed with respect sto the footpoint latitude phif. x1frac, x2frac, x2poly, x3poly, etc. are to enhance readability and to optimize computations.""" philambda = [] # Get the value of phif, the footpoint latitude. phif = FootpointLatitude(y) # Precalculate ep2 ep2 = ((sm_a**2.0 - sm_b**2.0) / sm_b**2.0) # Precalculate cos (phif) cf = cos(phif) # Precalculate nuf2 nuf2 = ep2 * cf**2.0 # Precalculate Nf and initialize Nfpow Nf = sm_a**2.0 / (sm_b * sqrt(1 + nuf2)) Nfpow = Nf # Precalculate tf tf = tan(phif) tf2 = tf**2 tf4 = tf2**2 # Precalculate fractional coefficients for x**n in the equations # below to simplify the expressions for latitude and longitude. x1frac = 1.0 / (Nfpow * cf) Nfpow *= Nf # now equals Nf**2) x2frac = tf / (2.0 * Nfpow) Nfpow *= Nf # now eq
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 row in reader: query_id = row[0].strip() if _is_python_list(row[1]): # doc ids value = map(lambda str: int(str.strip("'")), row[1].lstrip('[').rstrip(']').split(',')) elif _is_python_string(row[1]): # just a string value = row[1].strip() else: raise RuntimeError("Csv file at '{0}' does not fit expected structure for parsing".format(path_to_file)) data[query_id] = value return(data) def write_t
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_close_sq_brackets == no_of_open_sq_brackets and (no_of_open_sq_brackets != 0): return(True) else: return(False) def _is_python_string(str_representation): if _is_python_list(str_representation): return(False) else: return(True)
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 owlmixin.owlenum import OwlEnum, OwlObjectEnum from owlmixin.transformers import ( DictTransformer, JsonTransformer, YamlTransformer, ValueTransformer, traverse_dict, TOption, ) T = TypeVar("T", bound="OwlMixin") def _is_generic(type_): return hasattr(type_, "__origin__") def assert_extra(cls_properties, arg_dict, cls): extra_keys: set = set(arg_dict.keys()) - {n for n, t in cls_properties} if extra_keys: raise UnknownPropertiesError(cls=cls, props=sorted(extra_keys)) def assert_none(value, type_, cls, name): if value is None: raise RequiredError(cls=cls, prop=name, type_=type_) def assert_types(value, types: tuple, cls, name): if not isinstance(value, types): raise InvalidTypeError(cls=cls, prop=name, value=value, expected=types, actual=type(value)) def traverse( type_, name, value, cls, force_snake_case: bool, force_cast: bool, restrict: bool ) -> Any: # pylint: disable=too-many-return-statements,too-many-branches,too-many-arguments if isinstance(type_, str): type_ = sys.modules[cls.__module__].__dict__.get(type_) if hasattr(type_, "__forward_arg__"): # `_ForwardRef` (3.6) or `ForwardRef` (>= 3.7) includes __forward_arg__ # PEP 563 -- Postponed Evaluation of Annotations type_ = sys.modules[cls.__module__].__dict__.get(type_.__forward_arg__) if not _is_generic(type_): assert_none(value, type_, cls, name) if type_ is any: return value if type_ is Any: return value if isinstance(value, type_): return value if issubclass(type_, OwlMixin): assert_types(value, (type_, dict), cls, name) return type_.from_dict( value, force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict ) if issubclass(type_, ValueTransformer): return type_.from_value(value) if force_cast: return type_(value) assert_types(value, (type_,), cls, name) return value o_type = type_.__origin__ g_type = type_.__args__ if o_type == TList: assert_none(value, type_, cls, name) assert_types(value, (list,), cls, name) return TList( [ traverse(g_type[0], f"{name}.{i}", v, cls, force_snake_case, force_cast, restrict) for i, v in enumerate(value) ] ) if o_type == TIterator: assert_none(value, type_, cls, name) assert_types(value, (Iterable,), cls, name) return TIterator( traverse(g_type[0], f"{name}.{i}", v, cls, force_snake_case, force_cast, restrict) for i, v in enumerate(value) ) if o_type == TDict: assert_none(value, type_, cls, name) assert_types(value, (dict,), cls, name) return TDict( { k: traverse( g_type[0], f"{name}.{k}", v, cls, force_snake_case, force_cast, restrict ) for k, v in value.items() } ) if o_type == TOption: v = value.get() if isinstance(value, TOption) else value # TODO: Fot `from_csvf`... need to more simple!! if (isinstance(v, str) and v) or (n
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, name, bases, class_dict): ret_cls = type.__new__(cls, name, bases, class_dict) ret_cls.__methods_dict__ = dict(inspect.getmembers(ret_cls, inspe
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: """From dict to instance :param d: Dict :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if True :return: Instance Usage: >>> from owlmixin.samples import Human, Food, Japanese >>> human: Human = Human.from_dict({ ... "id": 1, ... "name": "Tom", ... "favorites": [ ... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) >>> human.id 1 >>> human.name 'Tom' >>> human.favorites[0].name 'Apple' >>> human.favorites[0].names_by_lang.get()["de"] 'Apfel' You can use default value >>> taro: Japanese = Japanese.from_dict({ ... "name": 'taro' ... }) # doctest: +NORMALIZE_WHITESPACE >>> taro.name 'taro' >>> taro.language 'japanese' If you don't set `force_snake=False` explicitly, keys are transformed to snake case as following. >>> human: Human = Human.from_dict({ ... "--id": 1, ... "<name>": "Tom", ... "favorites": [ ... {"name": "Apple", "namesByLang": {"en": "Apple"}} ... ] ... }) >>> human.id 1 >>> human.name 'Tom' >>> human.favorites[0].names_by_lang.get()["en"] 'Apple' You can allow extra parameters (like ``hogehoge``) if you set `restrict=False`. >>> apple: Food = Food.from_dict({ ... "name": "Apple", ... "hogehoge": "ooooooooooooooooooooo", ... }, restrict=False) >>> apple.to_dict() {'name': 'Apple'} You can prohibit extra parameters (like ``hogehoge``) if you set `restrict=True` (which is default). >>> human = Human.from_dict({ ... "id": 1, ... "name": "Tom", ... "hogehoge1": "ooooooooooooooooooooo", ... "hogehoge2": ["aaaaaaaaaaaaaaaaaa", "iiiiiiiiiiiiiiiii"], ... "favorites": [ ... {"name": "Apple", "namesByLang": {"en": "Apple", "de": "Apfel"}}, ... {"name": "Orange"} ... ] ... }) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... owlmixin.errors.UnknownPropertiesError: . ∧,,_∧ ,___________________ ⊂ ( ・ω・ )つ- < Unknown properties error /// /::/ `------------------- |::|/⊂ヽノ|::|」 / ̄ ̄旦 ̄ ̄ ̄/| ______/ | | |------ー----ー|/ <BLANKLINE> `owlmixin.samples.Human` has unknown properties ['hogehoge1', 'hogehoge2']!! <BLANKLINE> * If you want to allow unknown properties, set `restrict=False` * If you want to disallow unknown properties, add `hogehoge1` and `hogehoge2` to owlmixin.samples.Human <BLANKLINE> If you specify wrong type... >>> human: Human = Human.from_dict({ ... "id": 1, ... "name": "ichiro", ... "favorites": ["apple", "orange"] ... }) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ...
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 <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from functools import partial from PyQt5.Qt import ( QAbstractListModel, Qt, QKeySequence, QListView, QVBoxLayout, QLabel, QHBoxLayout, QWidget, QApplication, QStyledItemDelegate, QStyle, QIcon, QTextDocument, QRectF, QFrame, QSize, QFont, QKeyEvent, QRadioButton, QPushButton, QToolButton ) from calibre.gui2 import error_dialog from calibre.utils.config import XMLConfig from calibre.utils.icu import sort_key DEFAULTS = Qt.UserRole DESCRIPTION = Qt.UserRole + 1 CUSTOM = Qt.UserRole + 2 KEY = Qt.UserRole + 3 class Customize(QFrame): def __init__(self, index, dup_check, parent=None): QFrame.__init__(self, parent) self.setFrameShape(self.StyledPanel) self.setFrameShadow(self.Raised) self.setFocusPolicy(Qt.StrongFocus) self.setAutoFillBackground(True) self.l = l = QVBoxLayout(self) self.header = la = QLabel(self) la.setWordWrap(True) l.addWidget(la) self.default_shortcuts = QRadioButton(_("&Default"), self) self.custom = QRadioButton(_("&Custom"), self) self.custom.toggled.connect(self.custom_toggled) l.addWidget(self.default_shortcuts) l.addWidget(self.custom) for which in 1, 2: la = QLabel(_("&Shortcut:") if which == 1 else _("&Alternate shortcut:")) setattr(self, 'label%d' % which, la) h = QHBoxLayout() l.addLayout(h) h.setContentsMargins(25, -1, -1, -1) h.addWidget(la) b = QPushButton(_("Click to change"), self) la.setBuddy(b) b.clicked.connect(partial(self.capture_clicked, which=which)) b.installEventFilter(self) setattr(self, 'button%d' % which, b) h.addWidget(b) c = QToolButton(self) c.setIcon(QIcon(I('clear_left.png'))) c.setToolTip(_('Clear')) h.addWidget(c) c.clicked.connect(partial(self.clear_clicked, which=which)) setattr(self, 'clear%d' % which, c) self.data_model = index.model() self.capture = 0 self.key = None self.shorcut1 = self.shortcut2 = None self.dup_check = dup_check self.custom_toggled(False) def eventFilter(self, obj, event): if self.capture == 0 or obj not in (self.button1, self.button2): return QFrame.eventFilter(self, obj, event) t = event.type() if t == event.ShortcutOverride: event.accept() return True if t == event.KeyPress: self.key_press_event(event, 1 if obj is self.button1 else 2) return True return QFrame.eventFilter(self, obj, event) def clear_button(self, which): b = getattr(self, 'button%d' % which) s = getattr(self, 'shortcut%d' % which, None) b.setText(_('None') if s is None else s.toString(QKeySequence.NativeText)) b.setFont(QFont()) def clear_clicked(self, which=0): setattr(self, 'shortcut%d'%which, None) self.clear_button(which) def custom_toggled(self, checked): for w in ('1', '2'): for o in ('label', 'button', 'clear'): getattr(self, o+w).setEnabled(checked) def capture_clicked(self, which=1): self.capture = which for w in 1, 2: self.clear_button(w) button = getattr(self, 'button%d'%which) button.setText(_('Press a key...')) button.setFocus(Qt.OtherFocusReason) font = QFont() font.setBold(True) button.setFont(font) def key_press_event(self, ev, which=0): code = ev.key() if self.capture == 0 or code in (0, Qt.Key_unknown, Qt.Key_Shift, Qt.Key_Control, Qt.Key_Alt, Qt.Key_Meta, Qt.Key_AltGr, Qt.Key_CapsLock, Qt.Key_NumLock, Qt.Key_ScrollLock): return QWidget.keyPressEvent(self, ev) sequence = QKeySequence(code|(int(ev.modifiers())&~Qt.KeypadModifier)) setattr(self, 'shortcut%d'%which, sequence) self.clear_button(which) self.capture = 0 dup_desc = self.dup_check(sequence, self.key) if dup_desc is not None: error_dialog(self, _('Already assigned'), unicode(sequence.toString(QKeySequence.NativeText)) + ' ' + _('already assigned to') + ' ' + dup_desc, show=True) self.clear_clicked(which=which) class Delegate(QStyledItemDelegate): def __init__(self, parent=None): QStyledItemDelegate.__init__(self, parent) self.editing_indices = {} self.closeEditor.connect(self.editing_done) def to_doc(self, index): doc = QTextDocument() doc.setHtml(index.data()) return doc def editing_done(self, editor, hint): remove = None for row, w in self.editing_indices.items(): remove = (row, w.data_model.index(row)) if remove is not None: self.editing_indices.pop(remove[0]) self.sizeHintChanged.emit(remove[1]) def sizeHint(self, option, index): if index.row() in self.editing_indices: return QSize(200, 200) ans = self.to_doc(index).size().toSize() ans.setHeight(ans.height()+10) return ans def paint(self, painter, option, index): painter.save() painter.setClipRect(QRectF(option.rect)) if hasattr(QStyle, 'CE_ItemViewItem'): QApplication.style().drawControl(QStyle.CE_ItemViewItem, option, painter) elif option.state & QStyle.State_Selected: painter.fillRect(option.rect, option.palette.highlight()) painter.translate(option.rect.topLeft()) self.to_doc(index).drawContents(painter) painter.restore() def createEditor(self,
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([unicode(x.toString(x.NativeText)) for x in defs]) editor.key = unicode(index
.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: editor.custom.setChecked(True) for x in (0, 1): button = getattr(editor, 'button%d'%(x+1)) if len(custom) > x: seq = QKeySequence(custom[x]) button.setText(seq.toString(seq.NativeText)) setattr(editor, 'shortcut%d'%(x+1), seq) def setModelData(self, editor, model, index): self.closeEditor.emit(editor, self.NoHint) custom = [] if editor.custom.isChecked(): for x in ('1', '2'): sc = getattr(editor, 'shortcut'+x, None) if sc is not None: custom.append(sc) model.set_data(index, custom) def updateEditorGeometry(self, editor, option, index): editor.setGeometry(option.rect) class Shortcuts(QAbstractListModel): TEMPLATE = u''' <p><b>{0}</b><br> {2}: <code>{1}</code></p> ''' def __init__(self, shortcuts, config_file_base_name, parent=None): QAbstractListModel.__init__(self, parent) self.descriptions = {} for k, v in shortcuts.items(): self.descriptions[k] = v[-1] self.keys = {} for k, v in shortcuts.items(): self.keys[k] = v[0] self.order = list(shortcuts) self.order.sort(key=lambda x : sort_key(self.descriptions[x])) self.sequences = {}
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( name='party', options={'verbose_name_plural': 'Parties'}, ), migrations.AlterModelOptions( name='riding', options={'ordering': ('province', 'name_en')}, ), migrations.RenameField( model_name='party', old_name='name', new_name='name_en', ), migrations.RenameField( model_name='party', old_name='short_name', new_name='short_name_en', ),
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( model_name='party', name='short_name_fr', field=models.CharFi
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 <hello@jtolds.com> # # 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, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and 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 THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # """ Pants http://www.pants-lang.org/ Parser module """ __author__ = "JT Olds" __author_email__ = "hello@jtolds.com" __all__ = ["parse"] import types as ast from common.errors import ParserError from common.errors import assert_source DEBUG_LEVEL = 0 class Parser(object): NON_ID_CHARS = set([" ", "\n", "\r", "\t", ";", ",", "(", ")", "[", "]", "{", "}", "|", "'", '"', ".", ":", "@", "#"]) ESCAPES = { '"': '"', "n": "\n", "t": "\t", "r": "\r", "\n": "", "\\": "\\", "'": "'", "a": "\a", "b": "\b", "f": "\f", "v": "\v" } INTEGER_BASES = { "b": 2, "o": 8, "d": 12, "x": 16 } SAFE_DIGITS = { 2: set("01"), 8: set("01234567"), 10: set("0123456789"), 12: set("0123456789abAB"), 16: set("0123456789abcdefABCDEF") } __slots__ = ["source", "pos", "line", "col", "_term_memoization", "current_char"] def __init__(self, io): if hasattr(io, "read"): self.source = io.read() else: self.source = io self.pos = 0 self.line = 1 self.col = 1 self._term_memoization = {} self.current_char = self.source[:1] def advance(self, distance=1): for _ in xrange(distance): assert not self.eof() if self.current_char == "\n": self.line += 1 self.col = 1 else: self.col += 1 self.pos += 1 if self.pos >= len(self.source): self.current_char = None else: self.current_char = self.source[self.pos] def checkpoint(self): return (self.pos, self.col, self.line) def restore(self, checkpoint): self.pos, self.col, self.line = checkpoint if self.pos >= len(self.source): self.current_char = None else: self.current_char = self.source[self.pos] def source_ref(self, checkpoint): return checkpoint[2], checkpoint[1] def assert_source(self, message, line=None, col=None): if line is None: line = self.line if col is None: col = self.col assert_source(ParserError, message, line, col) def eof(self, lookahead=0): assert lookahead >= 0 return self.pos + lookahead >= len(self.source) def char(self, lookahead=0, required=False): if self.pos + lookahead >= len(self.source) or self.pos + lookahead < 0: if not required: return None assert lookahead >= 0 self.assert_source("end of input unexpected") return self.source[self.pos + lookahead] def parse_string_escape(self): if self.current_char != "\\": return None self.advance() if Parser.ESCAPES.has_key(self.char(required=True)): return Parser.ESCAPES[self.char] elif self.current_char in Parser.SAFE_DIGITS[10]: integer, base, log = self.parse_integer() assert integer is not None if integer >= 256: self.assert_source("byte escape sequence represents more than one byte") return chr(integer) elif self.current_char in ("U", "u", "N"): self.assert_source("TODO: unicode escape sequences unimplemented") else: self.assert_source("unknown escape sequence") def parse_string(self): checkpoint = self.checkpoint() bytestring = False if self.current_char == 'b': bytestring = True self.advance() if self.current_char != '"': self.restore(checkpoint) return None opening_quote_count = 1 self.advance() if self.char(required=True) == '"' and self.char(lookahead=1) != '"': self.advance() return ast.String(bytestring, "", *self.source_ref(checkpoint)) while self.char(required=True) == '"': opening_quote_count += 1 self.advance() value = [] while True: found_ending = True for i in xrange(opening_quote_count): if self.char(required=True, lookahead=i) != '"': found_ending = False break if found_ending: break val_to_append = self.cu
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, "".join(value), *self.source_ref(checkpoint)) def skip_comment(self): if self.current_char != "#": return
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 self.current_char in " \t\r" or self.current_char in other_skips: self.advance() return True return False def skip_all_whitespace(self, other_skips=[]): any_skipped = False while self.skip_whitespace(other_skips): any_skipped = True return any_skipped def parse_subexpression(self): if self.current_char != "(": return None checkpoint = self.checkpoint() self.advance() self.skip_all_whitespace("\n;") expressions = self.parse_expression_list(False) if self.current_char != ")": self.assert_source("unexpected input at end of subexpression") if not expressions: self.assert_source("expression list expected in subexpression") self.advance() return ast.Subexpression(expressions, *self.source_ref(checkpoint)) def parse_function(self): if self.current_char != "{": return None checkpoint = self.checkpoint() self.advance() self.skip_all_whitespace("\n") if self.current_char == "}": self.restore(checkpoint) return None # empty dictionary maybe_a_dict = True left_args = [] right_args = [] if self.current_char == "|": maybe_a_dict = False self.advance() self.skip_all_whitespace("\n") right_args = self.parse_in_arg_list() if self.current_char == ";": self.advance() self.skip_all_whitespace("\n") left_args = right_args right_args = self.parse_in_arg_list() if self.current_char != "|": self.assert_source("unexpected input for argument list") self.advance() self.check_left_in_args(left_args) self.check_right_in_args(right_args) self.skip_all_whitespace("\n;") expressions = self.parse_expression_list(True) if self.current_char != "}": if maybe_a_dict: self.restore(checkpoint) return None self.assert_source("unexpected input at close of function") self.advance() return ast.Function(expressions, left_args, right_args, *self.source_ref(checkpoint)) def parse_keyword_out_arg(self): if (self.current_char != ":" or self.char(lookahead=1) != ":" or self.char(lookahead=2) != "("): return None
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 BLED112Adapter class TestBLED112AdapterPassive(unittest.TestCase): """ Test to make sure that the BLED112Adapter is working correctly """ def setUp(self): self.old_serial = serial.Serial serial.Serial = util.dummy_serial.Serial self.adapter = MockBLED112(3) self.dev1 = SimpleVirtualDevice(100, 'TestCN') self.dev1_ble = MockBLEDevice("00:11:22:33:44:55", self.dev1) self.adapter.add_devic
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): """Test that we initialize correctly and the bled112 comes up scanning """ assert self.bled.scanning def _on_scan_callback(self, ad_id, info, expiry): self.num_scanned_devices += 1 self.scanned_devices.append(info) self._scanned_devices_seen.set() def _on_disconnect_callback(self, *args, **kwargs): pass def test_scanning(self): self._scanned_devices_seen.wait(timeout=1.0) assert self.num_scanned_devices == 1 assert 'voltage' not in self.scanned_devices[0]
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 = '{0}{1}\n'.format(result, eval('{0}.__doc
__'.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__, version = toolkit_library.__version__, url = 'https://github.com/tylerlong/toolkit_library', license = '
BSD', author = toolkit_library.__author__, author_email = 'tyler4long@gmail.com', description = 'Toolkit Library, full of useful toolkits', long_description = readme, packages = ['toolkit_library', ], platforms = 'any', classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
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, jmcnamara@cpan.org # import xlsxwriter workbook = xlsxwriter.Workbook('chart_scatter.xlsx') worksheet = workbook.add_worksheet() bold = workbook.add_format({'bold': 1}) # Add the worksheet data that the charts will refer to. headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [10, 40, 50, 20, 10, 50], [30, 60, 70, 50, 40, 30], ] worksheet.write_row('A1', headings, bold) worksheet.write_column('A2', data[0]) worksheet.write_column('B2', data[1]) worksheet.write_column('C2', data[2]) ####################################################################### # # Create a new scatter chart. # chart1 = workbook.add_chart({'type': 'scatter'}) # Configure the first series. chart1.add_series({ 'name': '=Sheet1!$B$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!$B$2:$B$7', }) # Configure second series. Note use of alternative syntax to define ranges. chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2], }) # Add a chart title and some axis labels. chart1.set_title ({'name': 'Results of sample analysis'}) chart1.set_x_axis({'name': 'Test number'}) chart1.set_y_axis({'name': 'Sample length (mm)'}) # Set an Excel chart style. chart1.set_style(11) # Insert the chart into the worksheet (with an offset). worksheet.insert_chart('D2', chart1, {'x_offset': 25, 'y_offset': 10}) ####################################################################### # # Create a scatter chart sub-type with straight lines and markers. # chart2 = workbook.add_chart({'type': 'scatter', 'subtype': 'straight_with_markers'}) # Configure the first series. chart2.add_series({ 'name': '=Sheet1!$B$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!$B$2:$B$7', }) # Configure second series. chart2.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. chart2.set_title ({'name': 'Straight line with markers'}) chart2.set_x_axis({'name': 'Test number'}) chart2.set_y_axis({'name': 'Sample length (mm)'}) # Set an Excel chart style. chart2.set_style(12) # Insert the chart into the worksheet (with an offset). worksheet.insert_chart('D18', chart2, {'x_offset': 25, 'y_offset': 10}) ####################################################################### # # Create a scatter chart sub-type with straight lines and no markers. # chart3 = workbook.add_chart({'type': 'scatter', 'subtype': 'straight'}) # Configure the first series. chart3.add_ser
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_y_axis({'name': 'Sample length (mm)'}) # Set an Excel chart style. chart3.set_style(13) # Insert the chart into the worksheet (with an offset). worksheet.insert_chart('D34', chart3, {'x_offset': 25, 'y_offset': 10}) ####################################################################### # # Create a scatter chart sub-type with smooth lines and markers. # chart4 = workbook.add_chart({'type': 'scatter', 'subtype': 'smooth_with_markers'}) # Configure the first series. chart4.add_series({ 'name': '=Sheet1!$B$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!$B$2:$B$7', }) # Configure second series. chart4.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. chart4.set_title ({'name': 'Smooth line with markers'}) chart4.set_x_axis({'name': 'Test number'}) chart4.set_y_axis({'name': 'Sample length (mm)'}) # Set an Excel chart style. chart4.set_style(14) # Insert the chart into the worksheet (with an offset). worksheet.insert_chart('D51', chart4, {'x_offset': 25, 'y_offset': 10}) ####################################################################### # # Create a scatter chart sub-type with smooth lines and no markers. # chart5 = workbook.add_chart({'type': 'scatter', 'subtype': 'smooth'}) # Configure the first series. chart5.add_series({ 'name': '=Sheet1!$B$1', 'categories': '=Sheet1!$A$2:$A$7', 'values': '=Sheet1!$B$2:$B$7', }) # Configure second series. chart5.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. chart5.set_title ({'name': 'Smooth line'}) chart5.set_x_axis({'name': 'Test number'}) chart5.set_y_axis({'name': 'Sample length (mm)'}) # Set an Excel chart style. chart5.set_style(15) # Insert the chart into the worksheet (with an offset). worksheet.insert_chart('D66', chart5, {'x_offset': 25, 'y_offset': 10}) workbook.close()
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 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. import eventlet from oslo_log import log from neutron.i18n import _LI from neutron import server from neutron import service LOG = log.getLogger(__name__) def _eventlet_wsgi_server(): pool = eventlet.GreenPool() neutron_api = service.serve_wsgi(service.NeutronApiService) api_thread = pool.spawn(neutron_api.wait) try: neutron_rpc = service.serve_rpc() except NotImplementedError: LOG.info(_LI("RPC was already started in parent process by " "plugin.")) else: rpc_thread = pool.spawn(neutron_rpc.wait) plugin_w
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/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. # =============================================================================== # =============enthought library imports======================= import os from datetime import datetime, timedelta from threading import Lock import six from sqlalchemy import create_engine, distinct, MetaData from sqlalchemy.exc import ( SQLAlchemyError, InvalidRequestError, StatementError, DBAPIError, OperationalError, ) from sqlalchemy.orm import sessionmaker from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound from traits.api import ( Password, Bool, Str, on_trait_change, Any, Property, cached_property, Int, ) from pychron.database.core.base_orm import AlembicVersionTable from pychron.database.core.query import compile_query from pychron.loggable import Loggable from pychron.regex import IPREGEX def obscure_host(h): if IPREGEX.match(h): h = "x.x.x.{}".format(h.split(".")[-1]) return h def binfunc(ds, hours): ds = [dx.timestamp for dx in ds] p1 = ds[0] delta_seconds = hours * 3600 td = timedelta(seconds=delta_seconds * 0.25) for i, di in enumerate(ds): i = max(0, i - 1) dd = ds[i] if (di - dd).total_seconds() > delta_seconds: yield p1 - td, dd + td p1 = di yield p1 - td, di + td class SessionCTX(object): def __init__(self, parent, use_parent_session=True): self._use_parent_session = use_parent_session self._parent = parent self._session = None self._psession = None def __enter__(self): if self._use_parent_session: self._parent.create_session() return self._parent.session else: self._psession = self._parent.session self._session = self._parent.session_factory() self._parent.session = self._session return self._session def __exit__(self, exc_type, exc_val, exc_tb): if self._session: self._session.close() else: self._parent.close_session() if self._psession: self._parent.session = self._psession self._psession = None class MockQuery: def join(self, *args, **kw): return self def filter(self, *args, **kw): # type: (object, object) -> object return self def all(self, *args, **kw): return [] def order_by(self, *args, **kw): return self class MockSession: def query(self, *args, **kw): return MockQuery() # def __getattr__(self, item): # return class DatabaseAdapter(Loggable): """ The DatabaseAdapter is a base class for interacting with a SQLAlchemy database. Two main subclasses are used by pychron, IsotopeAdapter and MassSpecDatabaseAdapter. This class provides attributes for describing the database url, i.e host, user, password etc, and methods for connecting and opening database sessions. It also provides some helper functions used extensively by the subclasses, e.g. ``_add_item``, ``_retrieve_items`` """ session = None sess_stack = 0 reraise = False connected = Bool(False) kind = Str prev_kind = Str username = Str host = Str password = Password timeout = Int session_factory = None application = Any test_func = "get_versions" version_func = "get_versions" autoflush = True autocommit = False commit_on_add = True # name used when writing to database # save_username = Str connection_parameters_changed = Bool url = Property(depends_on="connection_parameters_changed") datasource_url = Property(depends_on="connection_parameters_changed") path = Str echo = False verbose_retrieve_query = False verbose = True connection_error = Str _session_lock = None modified = False _trying_to_add = Fal
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 MetaData object """ # if self.kind == 'sqlite': metadata.create_all(self.session.bind) # def session_ctx(self, sess=None, commit=True, rollback=Tru
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 def session_ctx(self, use_parent_session=True): with self._session_lock: return SessionCTX(self, use_parent_session) def create_session(self, force=False): if self.connect(test=False): if self.session_factory: if force: self.debug("force create new session {}".format(id(self))) if self.session: self.session.close() self.session = self.session_factory() self._session_cnt = 1 else: if not self.session: # self.debug('create new session {}'.format(id(self))) self.session = self.session_factory() self._session_cnt += 1 else: self.warning("no session factory") else: self.session = MockSession() def close_session(self): if self.session and not isinstance(self.session, MockSession): self.session.flush() self._session_cnt -= 1 if not self._session_cnt: self.debug("close session {}".format(id(self))) self.session.close() self.session = None @property def enabled(self): return self.kind in ["mysql", "sqlite", "postgresql", "mssql"] @property def save_username(self): from pychron.globals import globalv return globalv.username @on_trait_change("username,host,password,name,kind,path") def reset_connection(self): """ Trip the ``connection_parameters_changed`` flag. Next ``connect`` call with use the new values """ self.connection_parameters_changed = True self.session_factory = None self.session = None # @caller def connect( self, test=True, force=False, warn=True, version_warn=True, attribute_warn=False ): """ Connect to the database :param test: Test the connection by running ``test_func`` :param force: Test connection even if connection parameters haven't changed :param warn: Warn if the connection test fails :param version_warn: Warn if database/pychron versions don't match :return: True if connected else False :rtype: bool """ self.connection_error = "" if force: self.debug("forcing database connection") if self.connection_parameters_changed: self._test_connection_enabled = True force = True if not self.connected or force: # self.connected = True if self.kind == 'sqlite' else False self.connected = False pool_recycle = 600
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 shellcode_length = len(shellcode)
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 import Field from rest_framework_mongoengine.fields import DictField def manager_repr(value): model = value._document return '%s.objects' % (model.__name__,) def mongo_field_repr(value): # mimic django models.Field.__repr__ path = '%s.%s' % (value.__class__.__module__, value.__class__.__name__) name = getattr(value, 'name', None) if name is not None: return '<%s: %s>' % (path, name) return '<%s>' % path def mongo_doc_repr(value): # mimic django models.Model.__repr__ try: u = six.text_type(value) except (UnicodeEncodeError, UnicodeDecodeError): u = '[Bad Unicode data]' return force_str('<%s: %s>' % (value.__class__.__name__, u)) uni_lit_re = re.compile("u'(.*?)'") def smart_repr(value): if isinstance(value, QuerySet): return manager_repr(value) if isinstance(value, BaseField): return mongo_field_repr(value) if isinstance(value, BaseDocument): return mongo_field_repr(value) if isinstance(value, Field): return field_repr(value) value = unicode_repr(value) # Representations like u'help text' # should simply be presented as 'help text' value = uni_lit_re.sub("'\\1'", value) # Representations like # <django.core.validators.RegexValidator object at 0x1047af050> # Should be presented as # <django.core.validators.RegexValidator object> value = re.sub(' at 0x[0-9a-f]{4,32}>', '>', value) return value def field_repr(field, force_many=False): kwargs = field._kwargs if force_many: kwargs = kwargs.copy() kwargs['many'] = True kwargs.pop('child', None) if kwargs.get('label', None) is None: kwargs.pop('label', None) if kwargs.get('help_text', None) is None: kwargs.pop('help_text', None) arg_string = ', '.join([smart_repr(val) for val in field._args]) kwarg_string = ', '.join([ '%s=%s' % (key, smart_repr(val)) for key, val in sorted(kwargs.items()) ]) if arg_string and kwarg_string: arg_string += ', ' if force_many: class_name = force_many.__class__.__name__ else: class_name = field.__class__.__name__ return "%s(%s%s)" % (class_name, arg_string, kwarg_string) def serializer_repr(serializer, indent, force_many=None): ret = field_repr(serializer, force_many) + ':' indent_str = ' ' * indent if force_many: fields = force_many.fields else: fields = serializer.fields for field_name, field in fields.items(): ret += '\n' + indent_str + field_name + ' = ' if hasattr(field, 'fields'): ret += serializer_repr(field, indent + 1) elif hasattr(field, 'child') and not isinstance(field, DictField): ret += list_repr(field, indent + 1) elif hasattr(field, 'child') and isinstance(field, DictField): ret += dict_repr(field, indent) else: ret += field_repr(field) if serializer.validators: ret += '\n' + indent_str + 'class Meta:' ret += '\n' + indent_str + ' validators = ' + smart_repr(serializer.validators) if len(fields) == 0: ret += "\npass" return ret def list_repr(serializer, indent): child = serializer.child if hasattr(child, 'fields'): return serializer_repr(serializer, indent, force_many=child) return field_repr(serializer) def dict_repr(serializer, indent): ret = field_repr(serializer) child = serializer.child if hasattr(child, 'fields'): ret = field_repr(serializer) + ":" ser_repr = serializer_repr(child, indent + 1) ret += "\n" + ser_repr.split("\n", 1)[1] # chop the name of seiralizer off return ret
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) any later version. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ Invenio utilities to run SQL queries. The main API functions are: - run_sql() - run_sql_many() - run_sql_with_limit() but see the others as well. """ __revision__ = "$Id$" # dbquery clients can import these from here: # pylint: disable=W0611 from MySQLdb import Warning, Error, InterfaceError, DataError, \ DatabaseError, OperationalError, IntegrityError, \ InternalError, NotSupportedError, \ ProgrammingError import gc import os import string import time import re from thread import get_ident from flask import current_app from werkzeug.utils import cached_property from invenio.base.globals import cfg from invenio.utils.datastructures import LazyDict from invenio.utils.serializers import serialize_via_marshal, \ deserialize_via_marshal class DBConnect(object): def __call__(self, *args, **kwargs): return self._connect(*args, **kwargs) @cached_property def _connect(self): if cfg['CFG_MISCUTIL_SQL_USE_SQLALCHEMY']: try: import sqlalchemy.pool as pool import MySQLdb as mysqldb mysqldb = pool.manage(mysqldb, use_threadlocal=True) connect = mysqldb.connect except ImportError: cfg['CFG_MISCUTIL_SQL_USE_SQLALCHEMY'] = False from MySQLdb import connect else: from MySQLdb import connect return connect def unlock_all(app): for dbhost in _DB_CONN.keys(): for db in _DB_CONN[dbhost].values(): try: cur = db.cur() cur.execute("UNLOCK TABLES") except: pass return app def _db_conn(): current_app.teardown_appcontext_funcs.append(unlock_all) out = {} out[cfg['CFG_DATABASE_HOST']] = {} out[cfg['CFG_DATABASE_SLAVE']] = {} return out connect = DBConnect() _DB_CONN = LazyDict(_db_conn) class InvenioDbQueryWildcardLimitError(Exception): """Exception raised when query limit reached.""" def __init__(self, res): """Initialization.""" self.res = res def _db_login(dbhost=None, relogin=0): """Login to the database.""" ## Note: we are using "use_unicode=False", because we want to ## receive strings from MySQL as Python UTF-8 binary string ## objects, not as Python Unicode string objects, as of yet. ## Note: "charset='utf8'" is needed for recent MySQLdb versions ## (such as 1.2.1_p2 and above). For older MySQLdb versions such ## as 1.2.0, an explicit "init_command='SET NAMES utf8'" parameter ## would constitute an equivalent. But we are not bothering with ## older MySQLdb versions here, since we are recommending to ## upgrade to more recent versions anyway. if dbhost is None: dbhost = cfg['CFG_DATABASE_HOST'] if cfg['CFG_MISCUTIL_SQL_USE_SQLALCHEMY']: return connect(host=dbhost, port=int(cfg['CFG_DATABASE_PORT']), db=cfg['CFG_DATABASE_NAME'], user=cfg['CFG_DATABASE_USER'], passwd=cfg['CFG_DATABASE_PASS'], use_unicode=False, charset='utf8') else: thread_ident = (os.getpid(), get_ident()) if relogin: connection = _DB_CONN[dbhost][thread_ident] = connect(host=dbhost, port=int(cfg['CFG_DATABASE_PORT']), db=cfg['CFG_DATABASE_NAME'], user=cfg['CFG_DATABASE_USER'], passwd=cfg['CFG_DATABASE_PASS'],
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, port=int(cfg['CFG_DATABASE_PORT']), db=cfg['CFG_DATABASE_NAME'],
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): """Close a connection.""" if dbhost is None: dbhost = cfg['CFG_DATABASE_HOST'] try: del _DB_CONN[dbhost][(os.getpid(), get_ident())] except KeyError: pass def close_connection(dbhost=None): """ Enforce the closing of a connection Highly relevant in multi-processing and multi-threaded modules """ if dbhost is None: dbhost = cfg['CFG_DATABASE_HOST'] try: db = _DB_CONN[dbhost][(os.getpid(), get_ident())] cur = db.cursor() cur.execute("UNLOCK TABLES") db.close() del _DB_CONN[dbhost][(os.getpid(), get_ident())] except KeyError: pass def run_sql(sql, param=None, n=0, with_desc=False, with_dict=False, run_on_slave=False): """Run SQL on the server with PARAM and return result. @param param: tuple of string params to insert in the query (see notes below) @param n: number of tuples in result (0 for unbounded) @param with_desc: if True, will return a DB API 7-tuple describing columns in query. @param with_dict: if True, will return a list of dictionaries composed of column-value pairs @return: If SELECT, SHOW, DESCRIBE statements, return tuples of data, followed by description if parameter with_desc is provided. If SELECT and with_dict=True, return a list of dictionaries composed of column-value pairs, followed by description if parameter with_desc is provided. If INSERT, return last row id. Otherwise return SQL result as provided by database. @note: When the site is closed for maintenance (as governed by the config variable CFG_ACCESS_CONTROL_LEVEL_SITE), do not attempt to run any SQL queries but return empty list immediately. Useful to be able to have the website up while MySQL database is down for maintenance, hot copies, table repairs, etc. @note: In case of problems, exceptions are returned according to the Python DB API 2.0. The client code can import them from this file and catch them. """ if cfg['CFG_ACCESS_CONTROL_LEVEL_SITE'] == 3: # do not connect to the database as the site is closed for maintenance: return [] if param: param = tuple(param) dbhost = cfg['CFG_DATABASE_HOST'] if run_on_slave and cfg['CFG_DATABASE_SLAVE']: dbhost = cfg['CFG_DATABASE_SLAVE'] if 'sql-logger' in cfg.get('CFG_DEVEL_TOOLS', []): log_sql_query(dbhost, sql, param) try: db = _db_login(dbhost) cur = db.cursor() gc.disable() rc = cur.execute(sql, param) gc.enable() except (OperationalError, InterfaceError): # unexpected disconnect, bad malloc error, etc # FIXME: now reconnect is always forced, we may perhaps want to ping() first? try: db = _db_login(dbhost, relogin=1) cur = db.cursor() gc.disable() rc =
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', '%s rows deleted': '%s rangées effacées', '%s rows updated': '%s rangées mises à jour', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', 'Actualizar': 'Actualizar', 'Admin': 'Admin', 'Alumno Regular': 'Alumno Regular', 'Alumnos': 'Alumnos', 'Analista de Sistemas': 'Analista de Sistemas', 'Análisis Clínicos': 'Análisis Clínicos', 'appadmin is disabled because insecure channel': 'appadmin is disabled because insecure channel', 'Authentication': 'Authentication', 'Auxiliar en enfermeria': 'Auxiliar en enfermeria', 'Available databases and tables': 'Available databases and tables', 'Body': 'Body', 'cache': 'cache', 'CAMPUS WEB': 'CAMPUS WEB', 'Cancel': 'Cancel', 'Cannot be empty': 'Cannot be empty', 'Cardiología': 'Cardiología', 'Carreras': 'Carreras', 'Cartelera': 'Cartelera', 'change password': 'change password', 'Check to delete': 'Check to delete', 'click here for online examples': 'cliquez ici pour voir des exemples enligne', 'click here for the administrative interface': "cliquez ici pour allerà l'interface d'administration", 'Client IP': 'Client IP', 'Constancias': 'Constancias', 'Consultar': 'Consultar', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'Current request', 'Current response': 'Current response', 'Current session': 'Current session', 'customize me!': 'customize me!', 'data uploaded': 'données téléchargées', 'Database': 'Database', 'database': 'database', 'database %s select': 'database %s select', 'Date': 'Date', 'db': 'db', 'DB Model': 'DB Model', 'Delete:': 'Delete:', 'Description': 'Description', 'design': 'design', 'Docentes': 'Docentes', 'done!': 'fait!', 'E-mail': 'E-mail', 'Edit': 'Edit', 'Edit current record': 'Edit current record', 'edit profile': 'edit profile', 'Edit This App': 'Edit This App', 'Enfermería': 'Enfermería', 'export as csv file': 'export as csv file', 'Extensión Terciaria': 'Extensión Terciaria', 'Fecha': 'Fecha', 'First name': 'First name', 'FLISOL 2010': 'FLISOL 2010', 'Format': 'Format', 'Graduados': 'Graduados', 'Group ID': 'Group ID', 'Hello World': 'Bonjour Monde', 'Historia': 'Historia', 'History': 'History', 'Id': 'Id', 'Import/Export': 'Import/Export', 'Index': 'Index', 'Ingresar': 'Ingresar', 'Iniciar': 'Iniciar', 'Inserción Laboral': 'Inserción Laboral', 'Insersión Laboral': 'Insersión Laboral', 'insert new': 'insert new', 'insert new %s': 'insert new %s', 'Institucional': 'Institucional', 'Instrumentación': 'Instrumentación', 'Internal State': 'Internal State', 'Invalid email': 'Invalid email', 'Invalid Query': 'Requête Invalide', 'invalid request': 'requête invalide', 'Laboratorio': 'Laboratorio', 'Language': 'Language', 'Last name': 'Last name', 'Layout': 'Layout', 'login': 'login', 'Login': 'Login', 'logout': 'logout', 'lost password': 'lost password', 'Lost Password': 'Lost Password', 'Main Menu': 'Main Menu', 'Manual de usuario': 'Manual de usuario', 'Materias Aprobadas': 'Materias Aprobadas', 'Menu Model': 'Menu Model', 'Name': 'Name', 'New Record': 'New Record', 'new record inserted': 'nouvelle archive insérée', 'next 100 rows': 'next 100 rows', 'No databases in this application': 'No databases in this application', 'or import from csv file': 'or import from csv file', 'Origin': 'Origin', 'Page format converted!': 'Page format converted!', 'Page History': 'Page History', 'Page Not Found': 'Page Not Found', 'Page Not Found!': 'Page Not Found!', 'Page Preview': 'Page Preview', 'Page saved': 'Page saved', 'Palabras del Director': 'Palabras del Director', 'Password': 'Password', 'Plantel Docente': 'Plantel Docente', 'Por que elegirnos': 'Por que elegirnos', 'Powered by': 'Powered by', 'Preview':
'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', 'Registration key': 'Registration key', 'Reincorporacion': 'Reincorporacion', 'Reset Password key': 'Reset Pas
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': 'table', 'Table name': 'Table name', 'Tecnicatura en redes informaticas': 'Tecnicatura en redes informaticas', 'texto base': 'texto base', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.', 'Timestamp': 'Timestamp', 'Title': 'Title', 'Titulo en Tramite': 'Titulo en Tramite', 'Tramites': 'Tramites', 'unable to parse csv file': "incapable d'analyser le fichier cvs", 'Update:': 'Update:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.', 'User': 'User', 'User ID': 'User ID', 'View': 'View', 'Viewing page version: %s': 'Viewing page version: %s', 'Welcome to web2py': 'Bienvenue sur web2py', }
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, isdefined, InputMultiPath, OutputMultiPath) class fiberstatsInputSpec(CommandLineInputSpec): fiber_file = File(desc="DTI Fiber File", exists=True, argstr="--fiber_file %s") verbose = traits.Bool(desc="produce verbose output", argstr="--verbose ") class fiberstatsOutputSpec(TraitedSpec): pass class fiberstats(SEMLikeCommandLine): """title: FiberStats (DTIProcess) category: Diffusion.Tractography.CommandLineOnly description: Obsolete tool - Not used anymore version: 1.1.0 documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation
/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 Engineering) provided conversions to make DTIProcess compatible with Slicer execution, and simplified the stand-alone build requirements by removing the dependancies on boost and a fortran compiler. """ input_spec = fiberstatsInputSpec output_spec = fiberstatsOutputSpec _cmd = " fiberstats " _outputs_filenames = {} _redirect_x = False
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, etc. Link is the primitive structure for the model definitions. It supports management of parameter variables and *persistent values* that should be incorporated to serialization. Parameters are variables registered via the :meth:`add_param` method, or given to the initializer method. Persistent values are arrays, scalars, or any other serializable values registered via the :meth:`add_persistent` method. .. note:: Whereas arbitrary serializable objects can be registered as persistent values, it is strongly recommended to just register values that should be treated as results of learning. A typical example of persistent values is ones computed during training and required for testing, e.g. running statistics for batch normalization. Parameters and persistent values are referred by their names. They can be accessed as attributes of the names. Link class itself manages the lists of names of parameters and persistent values to distinguish parameters and persistent values from other attributes. Link can be composed into more complex models. This composition feature is supported by child classes like :class:`Chain` and :class:`ChainList`. One can create a chain by combining one or more links. See the documents for these classes for details. As noted above, Link supports the serialization protocol of the :class:`~chainer.Serializer` class. **Note that only parameters and persistent values are saved and loaded.** Other attributes are considered as a part of user program (i.e. a part of network definition). In order to construct a link from saved file, other attributes must be identically reconstructed by user codes. .. admonition:: Example This is a simple example of custom link definition. Chainer itself also provides many links defined under the :mod:`~chainer.links` module. They might serve as examples, too. Consider we want to define a simple primitive link that implements a fully-connected layer based on the :func:`~functions.linear` function. Note that this function takes input units, a weight variable, and a bias variable as arguments. Then, the fully-connected layer can be defined as follows:: import chainer import chainer.functions as F import numpy as np class LinearLayer(chainer.Link): def __init__(self, n_in, n_out): # Parameters are initialized as a numpy array of given shape. super(LinearLayer, self).__init__( W=(n_out, n_in), b=(n_out,), ) self.W.data[...] = np.random.randn(n_out, n_in) self.b.data.fill(0) def __call__(self, x): return F.linear(x, self.W, self.b) This example shows that a user can define arbitrary parameters and use them in any methods. Links typically implement the ``__call__`` operator. Args: params: Shapes of initial parameters. The keywords are used as their names. The names are also set to the parameter variables. Attributes: name (str): Name of this link, given by the parent chain (if exists). """ def __init__(self, **params): self._params = [] self._persistent = [] self._cpu = True self.name = None for name, shape in six.iteritems(params): self.add_param(name, shape) @property def xp(self): """Array module for this link. Depending on which of CPU/GPU this link is on, this property returns :mod:`numpy` or :mod:`cupy`. """ return numpy if self._cpu else cuda.cupy def add_param(self, name, shape, dtype=numpy.float32): """Registers a parameter to the link. The registered parameter is saved and loaded on serialization and deserialization, and involved in the optimization. The data and
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.full(shape, numpy.nan, dtype=dtype) grad = data.copy() var = variable.Variable(data, volatile='auto', name=name) var.grad = grad self._params.append(name) d[name] = var def add_persistent(self, name, value): """Registers a persistent value to the link. The resitered value is saved and loaded on serialization and deserialization. The value is set to an attribute of the link. Args: name (str): Name of the persistent value. This name is also used for the attribute name. value: Value to be registered. """ d = self.__dict__ if name in d: raise AttributeError( 'cannot register a new persistent value %s: attribute exists' % name) self._persistent.append(name) d[name] = value def copy(self): """Copies the link hierearchy to new one. The whole hierarchy rooted by this link is copied. The copy is basically shallow, except that the parameter variables are also shallowly copied. It means that the parameter variables of copied one are different from ones of original link, while they share the data and gradient arrays. The name of the link is reset on the copy, since the copied instance does not belong to the original parent chain (even if exists). Returns: Link: Copied link object. """ ret = copy.copy(self) ret._params = list(self._params) ret._persistent = list(self._persistent) ret.name = None d = ret.__dict__ for name in ret._params: d[name] = copy.copy(d[name]) return ret def to_cpu(self): """Copies parameter variables and persistent values to CPU. This method does not handle non-registered attributes. If some of such attributes must be copied to CPU, the link implementation must override this method to do so. Returns: self """ if self._cpu: return self for param in self.params(): param.to_cpu() d = self.__dict__ for name in self._persistent: value = d[name] if isinstance(value, cuda.ndarray): d[name] = value.get() self._cpu = True return self def to_gpu(self, device=None): """Copies parameter variables and persistent values to GPU. This method does not handle non-registered attributes. If some of such attributes must be copoied to GPU, the link implementation must override this method to do so. Args: device: Target device specifier. If omitted, the current device is used. Returns: self """ cuda.check_cuda_available() if not self._cpu: return self with cuda.get_device(device): for param in self.params(): param.to_gpu() d = self.__dict__ for name in self._persistent: value = d[name]
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 csvFilename in os.listdir('.'): if not csvFilename.endswith(".csv"): continue # skip non-csv files print("Removing header from " + csvFilename + "...") # Read the CSV file in (skipping first row). csvRows = [] csvFile
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) csvFileObj.close() if __name__ == '__main__': main()
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 = gRGB(255, 255, 255, 0) self.fColors = gRGB(255, 0, 0, 0) self.fColorm = gRGB(255, 0, 0, 0) self.fColorh = gRGB(255, 255, 255, 0) self.bColor = gRGB(0, 0, 0, 255) self.forend = -1 self.linewidth = 1 self.positionheight = 1 self.positionwidth = 1 self.linesize = 1 GUI_WIDGET = eCanvas def applySkin(self, desktop, parent): attribs = [] for (attrib, what,) in self.skinAttributes: if (attrib == 'hColor'): self.fColorh = parseColor(what) elif (attrib == 'mColor'): self.fColorm = parseColor(what) elif (attrib == 'sColor'): self.fColors = parseColor(what) elif (attrib == 'linewidth'): self.linewidth = int(what) elif (attrib == 'positionheight'): self.positionheight = int(what) elif (attrib == 'positionwidth'):
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((a * z))))) y = int(round((r * math.cos((a * z)))))
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.forend, self.linesize, r, r1) self.line_draw(r, r1, endX, endY) def line_draw(self, x0, y0, x1, y1): steep = (abs((y1 - y0)) > abs((x1 - x0))) if steep: x0, y0 = y0, x0 x1, y1 = y1, x1 if (x0 > x1): x0, x1 = x1, x0 y0, y1 = y1, y0 if (y0 < y1): ystep = 1 else: ystep = -1 deltax = (x1 - x0) deltay = abs((y1 - y0)) error = (-deltax / 2) y = int(y0) for x in range(int(x0), (int(x1) + 1)): if steep: self.instance.fillRect(eRect(y, x, self.linewidth, self.linewidth), self.fColor) else: self.instance.fillRect(eRect(x, y, self.linewidth, self.linewidth), self.fColor) error = (error + deltay) if (error > 0): y = (y + ystep) error = (error - deltax) def changed(self, what): opt = (self.source.text).split(',') try: sopt = int(opt[0]) if len(opt) < 2: opt.append('') except Exception as e: return if (what[0] == self.CHANGED_CLEAR): pass elif self.instance: self.instance.show() if (self.forend != sopt): self.forend = sopt self.instance.clear(self.bColor) self.hand(opt[1]) def parseSize(self, str): (x, y,) = str.split(',') return eSize(int(x), int(y)) def postWidgetCreate(self, instance): for (attrib, value,) in self.skinAttributes: if ((attrib == 'size') and self.instance.setSize(self.parseSize(value))): pass self.instance.clear(self.bColor)
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: missing_products.append(value) if len(missing_products) != 0: v = app.productdb.models.Vendor.objects.filter(id=vendor_id).first() msg = "The following products are not found in the database for the vendor %s: %s" % ( v.name, ",".join(missing_products) ) raise ValidationError(msg, code="invaild")
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,stream,count), image) # save frame as JPEG file success,image = vidcap.read() print('Read a new frame: ', success) count += 1 #parse metadata fields_to_extract=['timestamp','enhanced_altitude','enhanced_speed','utc_timestamp','timestamp_ms','heading','velocity'] fields_to_convert=['position_lat','position_long'] meta = {} for key in fields_to_extract+fields_to_convert: meta[key]=[] ff=fitparse.
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 heapq-based priority queue is that priorities of items can be efficiently updated (amortized O(1)) using code as 'thedict[item] = new_priority.' The 'smallest' method can be used to return the object with l
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: heappop(heap) v, k = heap[0] return k def pop_smallest(self): """Return the item with the lowest priority and remove it. Raises IndexError if the object is empty. """ heap = self._heap v, k = heappop(heap) while k not in self or self[k] != v: v, k = heappop(heap) del self[k] return k def __setitem__(self, key, val): # We are not going to remove the previous value from the heap, # since this would have a cost O(n). super(priority_dict, self).__setitem__(key, val) if len(self._heap) < 2 * len(self): heappush(self._heap, (val, key)) else: # When the heap grows larger than 2 * len(self), we rebuild it # from scratch to avoid wasting too much memory. self._rebuild_heap() def setdefault(self, key, val): if key not in self: self[key] = val return val return self[key] def update(self, *args, **kwargs): # Reimplementing dict.update is tricky -- see e.g. # http://mail.python.org/pipermail/python-ideas/2007-May/000744.html # We just rebuild the heap from scratch after passing to super. super(priority_dict, self).update(*args, **kwargs) self._rebuild_heap() def sorted_iter(self): """Sorted iterator of the priority dictionary items. Beware: this will destroy elements as they are returned. """ while self: yield self.pop_smallest()
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) <supergonkas@gmail.com> # # 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 License, or # (at your option) any later version. # # Medusa 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 Medusa. If not, see <http://www.gnu.org/licenses/>. """Provider code for Bitsnoop.""" from __future__ import unicode_literals import traceback from requests.compat import urljoin from ..torrent_provider import TorrentProvider from .... import app, logger, tv_cache from ....bs4_parser import BS4Parser from ....helper.common import convert_size, try_int class BitSnoopProvider(TorrentProvider): """BitSnoop Torrent provider.""" def __init__(self): """Initialize the class.""" super(self.__class__, self).__init__('BitSnoop') # Credentials self.public = True # URLs self.url = 'https://bitsnoop.com' self.urls = { 'base': self.url, 'rss': urljoin(self.url, '/new_video.html?fmt=rss'), 'search': urljoin(self.url, '/search/video/'), } # Proper Strings self.proper_strings = ['PROPER', 'REPACK'] # Miscellaneous Options # Torrent Stats self.minseed = None self.minleech = None # Cache self.cache = tv_cache.TVCache(self, search_params={'RSS': ['rss']}) def search(self, search_strings, age=0, ep_obj=None): """ Search a provider and parse the results. :param search_strings: A dict with mode (key) and the search value (value) :param age: Not used :param ep_obj: Not used :returns: A list of search results (structure) """ results = [] for mode in search_strings: logger.log('Search mode: {0}'.format(mode), logger.DEBUG) for search_string in search_strings[mode]: if mode != 'RSS': logger.log('Search string: {search}'.format (search=search_string), logger.DEBUG) search_url = (self.urls['rss'], self.urls['search'] + search_string + '/s/d/1/?fmt=rss')[mode != 'RSS'] response = self.get_url(search_url, returns='response') if not response or not response.text: logger.log('No data returned from provider', logger.DEBUG) continue elif not response or not response.text.startswith('<?xml'): logger.log('Expected xml but got something else, is your mirror failing?', logger.INFO) continue results += self.parse(response.text, mode) return results def parse(self, data, mode): """ Parse search results for items. :param data: The raw response from a search :param mode: The current mode used to search, e.g. RSS :return: A list of items found """ items = [] with BS4Parser(data, 'html5lib') as html: torrent_rows = html('item') for row in torrent_rows: try: if not row.category.text.endswith(('TV', 'Anime')): continue title = row.title.text # Use the torcache link bitsnoop provides, # unless it is not torcache or we are not using blackhole # because we want to use magnets if connecting direct to client # so that proxies work. download_url = row.enclosure['url'] if app.TORRENT_METHOD != 'blackhole' or 'torcache' not in download_url: download_url = row.find('magne
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': logger.log("Discarding torrent because it doesn't meet the " "minimum seeders: {0}. Seeders: {1}".format (title, seeders), logger.DEBUG) continue torrent_size = row.find('size').text size = convert_size(torrent_size) or -1 item = { 'title': title, 'link': download_url, 'size': size, 'seeders': seeders, 'leechers': leechers, 'pubdate': None, } if mode != 'RSS': logger.log('Found result: {0} with {1} seeders and {2} leechers'.format (title, seeders, leechers), logger.DEBUG) items.append(item) except (AttributeError, TypeError, KeyError, ValueError, IndexError): logger.log('Failed parsing provider. Traceback: {0!r}'.format (traceback.format_exc()), logger.ERROR) return items provider = BitSnoopProvider()
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 part of a filename. """ # This module is maintained by Marc-Andre Lemburg <mal@egenix.com>. # If you find problems, please submit bug reports/patches via the # Python bug tracker (http://bugs.python.org) and assign them to "lemburg". # # Note: Please keep this module compatible to Python 1.5.2. # # Still needed: # * more support for WinCE # * support for MS-DOS (PythonDX ?) # * support for Amiga and other still unsupported platforms running Python # * support for additional Linux distributions # # Many thanks to all those who helped adding platform-specific # checks (in no particular order): # # Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell, # Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef # Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg # Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark # Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support), # Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter # # History: # # <see CVS and SVN checkin messages for history> # # 1.0.7 - added DEV_NULL # 1.0.6 - added linux_distribution() # 1.0.5 - fixed Java support to allow running the module on Jython # 1.0.4 - added IronPython support # 1.0.3 - added normalization of Windows system name # 1.0.2 - added more Windows support # 1.0.1 - reformatted to make doc.py happy # 1.0.0 - reformatted a bit and checked into Python CVS # 0.8.0 - added sys.version parser and various new access # APIs (python_version(), python_compiler(), etc.) # 0.7.2 - fixed architecture() to use sizeof(pointer) where available # 0.7.1 - added support for Caldera OpenLinux # 0.7.0 - some fixes for WinCE; untabified the source file # 0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and # vms_lib.getsyi() configured # 0.6.1 - added code to prevent 'uname -p' on platforms which are # known not to support it # 0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k; # did some cleanup of the interfaces - some APIs have changed # 0.5.5 - fixed another type in the MacOS code... should have # used more coffee today ;-) # 0.5.4 - fixed a few typos in the MacOS code # 0.5.3 - added experimental MacOS support; added better popen() # workarounds in _syscmd_ver() -- still not 100% elegant # though # 0.5.2 - fixed uname() to return '' instead of 'unknown' in all # return values (the system uname command tends to return # 'unknown' instead of just leaving the field emtpy) # 0.5.1 - included code for slackware dist; added exception handlers # to cover up situations where platforms don't have os.popen # (e.g. Mac) or fail on socket.gethostname(); fixed libc # detection RE # 0.5.0 - changed the API names referring to system commands to *syscmd*; # added java_ver(); made syscmd_ver() a private # API (was system_ver() in previous versions) -- use uname() # instead; extended the win32_ver() to also return processor # type information # 0.4.0 - added win32_ver() and modified the platform() output for WinXX # 0.3.4 - fixed a bug in _follow_symlinks() # 0.3.3 - fixed popen() and "file" command invokation bugs # 0.3.2 - added architecture() API and support for it in platform() # 0.3.1 - fixed syscmd_ver() RE to support Windows NT # 0.3.0 - added system alias support # 0.2.3 - removed 'wince' again... oh well. # 0.2.2 - added 'wince' to syscmd_ver() supported platforms # 0.2.1 - added cache logic and changed the platform string format # 0.2.0 - changed the API to use functions instead of module globals # since some action take too long to be run on module import # 0.1.0 - first release # # You can always get the latest version of this module at: # # http://www.egenix.com/files/python/platform.py # # If that URL should fail, try contacting the author. __copyright__ = """ Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee or royalty is hereby granted, provided that the above copyright notice appear in all
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, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE ! """ __version__ = '1.0.7' import sys,string,os,re ### Globals & Constants # Determine the platform's /dev/null device try: DEV_NULL = os.devnull except AttributeError: # os.devnull was added in Python 2.4, so emulate it for earlier # Python versions if sys.platform in ('dos','win32','win16','os2'): # Use the old CP/M NUL as device name DEV_NULL = 'NUL' else: # Standard Unix uses /dev/null DEV_NULL = '/dev/null' ### Platform specific APIs _libc_search = re.compile(r'(__libc_init)' '|' '(GLIBC_([0-9.]+))' '|' '(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)') def libc_ver(executable=sys.executable,lib='',version='', chunksize=2048): """ Tries to determine the libc version that the file executable (which defaults to the Python interpreter) is linked against. Returns a tuple of strings (lib,version) which default to the given parameters in case the lookup fails. Note that the function has intimate knowledge of how different libc versions add symbols to the executable and thus is probably only useable for executables compiled using gcc. The file is read and scanned in chunks of chunksize bytes. """ if hasattr(os.path, 'realpath'): # Python 2.2 introduced os.path.realpath(); it is used # here to work around problems with Cygwin not being # able to open symlinks for reading executable = os.path.realpath(executable) f = open(executable,'rb') binary = f.read(chunksize) pos = 0 while 1: m = _libc_search.search(binary,pos) if not m: binary = f.read(chunksize) if not binary: break pos = 0 continue libcinit,glibc,glibcversion,so,threads,soversion = m.groups() if libcinit and not lib: lib = 'libc' elif glibc: if lib != 'glibc': lib = 'glibc' version = glibcversion elif glibcversion > version: version = glibcversion elif so: if lib != 'glibc': lib = 'libc' if soversion > version: version = soversion if threads and version[-len(threads):] != threads: version = version + threads pos = m.end() f.close() return lib,version def _dist_try_harder(distname,version,id): """ Tries some special tricks to get the distribution information in case the default method fails.
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): self._character = None Session.__init__(self) self._map = None def combatgrid(self): enemies = [] for enemy in copy.copy(frontend.campaign.characterlist): addme = True for cmp_enemy in enemies: if cmp_enemy.name() == enemy.name(): addme = False break if addme: enemies.append(enemy) chars = copy.copy(enemies) combatgrid = {} for character in chars: combatgrid[character.displayname()] = {} for enemy in enemies: roll = attack_roll(character, enemy, [], 0) combatgrid[character.displayname()][enemy.displayname()] = roll attack_mods = load_json('adnd2e', 'attack_mods') data = {'combatgrid': combatgrid, 'mods': attack_mods} frontend.campaign.messages = [] page = Page() html = page.tplrender('combatgrid.tpl', data) return '<html><head></head><body>%s</body></html>' % html def inputhandler(self, requestdata, page): if 'loadmap' in requestdata and requestdata['loadmap'] == 'New Map': self._data['charicons'] = {} self._map = GameMap(name='New Map') else: if requestdata and 'loadmap' in requestdata and requestdata['loadmap'] != 'New Map': self._map = GameMap(json=load_json('maps', '%s.json' % requestdata['loadmap'])) elif requestdata and 'savemap' in requestdata: self._map.put('/name', requestdata['mapname']) if 'max_x' in requestdata: self._map = GameMap(name=requestdata['mapname'], max_x=int(requestdata['max_x']), max_y=int(requestdata['max_y']), lightradius=int(requestdata['lightradius'])) page.message('Map saved as:' + self._map.save()) frontend.campaign.addmap(self._map.name()) if "clicked_x" in requestdata: self._data['zoom_x'] = int(requestdata['clicked_x']) self._data['zoom_y'] = int(requestdata['clicked_y']) if "loadtilefromfile" in requestdata: self._map.load_tile(self._data['zoom_x'], self._data['zoom_y'], '%s.json' % requestdata["load_tile_from_file"]) if 'pythonconsole' in requestdata: exec(requestdata['pythonconsole'], {'map': self._map}) if 'addchartotile' in requestdata: cname = requestdata['charactername'] character = Character(load_json('characters', cname)) character.moveto(self._map.name(), self._data['zoom_x'], self._data['zoom_y']) character.autosave() self._map.save() self._map = GameMap(load_json('maps', self._map.name())) if 'updatejson' in requestdata: newjson = loads(requestdata['jsonbox']) self._map.load_tile_from_json(self._data['zoom_x'], self._data['zoom_y'], newjson) if 'addnpctotile' in requestdata: cname = requestdata['npcname'] npc = Character(load_json('characters', cname)) npc.moveto(self._map.name(), self._data['zoom_x'], self._data['zoom_y']) self._map.addtotile(self._data['zoom_x'], self._data['zoom_y'], npc, 'npcs') self._map = GameMap(load_json('maps', self._map.name())) if 'additemtotile' in requestdata: self._map.addtotile(self._data['zoom_x'], self._data['zoom_y'], requestdata['itemname'], 'items') if 'removenpcfromtile' in requestdata: tile = self._map.tile(self._data['zoom_x'], self._data['zoom_y']) npcs = tile.get('/conditional/npcs', []) for npc in npcs: debug("Testing npc") n = Character(npcs[npc]) if n.name() == '%s.json' % requestdata['npcname']: debug(" Match") break self._map.removefromtile(self._data['zoom_x'], self._data['zoom_y'], n.get_hash(), 'npcs') self._map.save() if 'removeitemfromtile' in requestdata: self._map.removefromtile(self._data['zoom_x'], self._data['zoom_y'], requestdata['itemname'], 'items') if 'settargetmap' in requestdata: target = requestdata['targetmap'] if not target.endswith('.json'): target = '%s.json' % target target_x = int(requestdata['target_x']) target_y = int(requestdata['target_y']) self._map.tile(self._data['zoom_x'], self._data['zoom_y']).linktarget(target=target, x=target_x, y=target_y) if 'movehere' in requestdata: self._character.moveto(self._map.name(), self._data['zoom_x'], self._data['zoom_y']) self._character.autosave() self._map = GameMap(load_json('maps', self._map.name())) if 'moveallhere' in requestdata: for player in frontend.campaign.players(): p = Character(load_json('characters', player)) p.moveto(self._map.name(), self._data['zoom_x'], self._data['zoom_y']) p.autosave() self._map = GameMap(load_json('maps', self._map.name())) if "followlink" in requestdata: tile = self._map.tile(self._data['zoom_x'], self._data['zoom_y']) newmap = tile.get('/conditional/newmap/mapname', '') new_x = tile.get('/conditional/newmap/x', 0) new_y = tile.get('/conditional/newmap/y', 0) self._character.moveto(mapname=newmap, x=new_x, y=new_y, page=page) self._character.autosave() self._data['zoom_x'] = new_x self._data['zoom_y'] = new_y self._map.save() if 'sellitem' in requestdata: idx = int(requestdata['itemtosell']) self._character.sell_item(idx) self._character.autosave() if 'iconsection' in requestdata and requestdata['iconsection']: debug("Processing icon click") iconsection = requestdata['iconsection'] self._data['detailname'] = requestdata['iconname'] filename = filename_parser(requestdata['iconname']) if iconsection == 'money': self._data['detailview'] = {} self._data['detailview']['gold'] = self._map.tile(self._data['zoom_x'], self._data['zoom_y']).get('/conditional/gold', 0) self._data['detailview']['silver'] = self._map.tile(self._data['zoom_x'], self._data['zoom_y']).get('/conditional/silver', 0) self._data['detailview']['copper'] = self._map.tile(self._data['zoom_x'], self._data['zoom_y']).get('/conditional/copper', 0) self._data['detailtype'] = 'item' self._data['detailicon'] = 'icons/money.png' elif iconsection == 'items': i = Item(load_json('items', filename)) if self._map.tile(self._data['zoom_x'], self._data['zoom_y']).tiletype() == 'shop': debug("Pre-identifying item from shop") i.identify() self._data['detailview'] = i.render() self._data['detailtype'] = 'item' self._data['detailicon'] = i.get('/core/icon', None) if 'iconindex' in requestdata and requestdata
['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.assertRaises(light_sensor.LightSensorLowError): self.mock_adc.read_adc.return_value = (
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 interpreter's site-packages. Solves #705, #763, #779 if os.environ.get('VIRTUALENV_INTERPRETER_RUNNING'): for path in sys.path[:]: if os.path.realpath(os.path.dirname(__file__)) == os.path.realpath(path): sys.path.remove(path) import base64 import codecs import optparse import re import shutil import logging import zlib import errno import glob import distutils.sysconfig import struct import subprocess import pkgutil import tempfile import textwrap from distutils.util import strtobool from os.path import join try: import ConfigParser except ImportError: import configparser as ConfigParser __version__ = "15.0.4" virtualenv_version = __version__ # legacy if sys.version_info < (2, 6): print('ERROR: %s' % sys.exc_info()[1]) print('ERROR: this script requires Python 2.6 or greater.') sys.exit(101) try: basestring except NameError: basestring = str py_version = 'python%s.%s' % (sys.version_info[0], sys.version_info[1]) is_jython = sys.platform.startswith('java') is_pypy = hasattr(sys, 'pypy_version_info') is_win = (sys.platform == 'win32') is_cygwin = (sys.platform == 'cygwin') is_darwin = (sys.platform == 'darwin') abiflags = getattr(sys, 'abiflags', '') user_dir = os.path.expanduser('~') if is_win: default_storage_dir = os.path.join(user_dir, 'virtualenv') else: default_storage_dir = os.path.join(user_dir, '.virtualenv') default_config_file = os.path.join(default_storage_dir, 'virtualenv.ini') if is_pypy: expected_exe = 'pypy' elif is_jython: expected_exe = 'jython' else: expected_exe = 'python' # Return a mapping of version -> Python executable # Only provided for Windows, where the information in the registry is used if not is_win: def get_installed_pythons(): return {} else: try: import winreg except ImportError: import _winreg as winreg def get_installed_pythons(): try: python_core = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore") except WindowsError: # No registered Python installations return {} i = 0 versions = [] while True: try: versions.append(winreg.EnumKey(python_core, i)) i = i + 1 e
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 for ver in sorted(exes): exes[ver[0]] = exes[ver] return exes REQUIRED_MODULES = ['os', 'posix', 'posixpath', 'nt', 'ntpath', 'genericpath', 'fnmatch', 'locale', 'encodings', 'codecs', 'stat', 'UserDict', 'readline', 'copy_reg', 'types', 're', 'sre', 'sre_parse', 'sre_constants', 'sre_compile', 'zlib'] REQUIRED_FILES = ['lib-dynload', 'config'] majver, minver = sys.version_info[:2] if majver == 2: if minver >= 6: REQUIRED_MODULES.extend(['warnings', 'linecache', '_abcoll', 'abc']) if minver >= 7: REQUIRED_MODULES.extend(['_weakrefset']) elif majver == 3: # Some extra modules are needed for Python 3, but different ones # for different versions. REQUIRED_MODULES.extend([ '_abcoll', 'warnings', 'linecache', 'abc', 'io', '_weakrefset', 'copyreg', 'tempfile', 'random', '__future__', 'collections', 'keyword', 'tarfile', 'shutil', 'struct', 'copy', 'tokenize', 'token', 'functools', 'heapq', 'bisect', 'weakref', 'reprlib' ]) if minver >= 2: REQUIRED_FILES[-1] = 'config-%s' % majver if minver >= 3: import sysconfig platdir = sysconfig.get_config_var('PLATDIR') REQUIRED_FILES.append(platdir) REQUIRED_MODULES.extend([ 'base64', '_dummy_thread', 'hashlib', 'hmac', 'imp', 'importlib', 'rlcompleter' ]) if minver >= 4: REQUIRED_MODULES.extend([ 'operator', '_collections_abc', '_bootlocale', ]) if is_pypy: # these are needed to correctly display the exceptions that may happen # during the bootstrap REQUIRED_MODULES.extend(['traceback', 'linecache']) if majver == 3: # _functools is needed to import locale during stdio initialization and # needs to be copied on PyPy because it's not built in REQUIRED_MODULES.append('_functools') class Logger(object): """ Logging object for use in command-line script. Allows ranges of levels, to avoid some redundancy of displayed information. """ DEBUG = logging.DEBUG INFO = logging.INFO NOTIFY = (logging.INFO+logging.WARN)/2 WARN = WARNING = logging.WARN ERROR = logging.ERROR FATAL = logging.FATAL LEVELS = [DEBUG, INFO, NOTIFY, WARN, ERROR, FATAL] def __init__(self, consumers): self.consumers = consumers self.indent = 0 self.in_progress = None self.in_progress_hanging = False def debug(self, msg, *args, **kw): self.log(self.DEBUG, msg, *args, **kw) def info(self, msg, *args, **kw): self.log(self.INFO, msg, *args, **kw) def notify(self, msg, *args, **kw): self.log(self.NOTIFY, msg, *args, **kw) def warn(self, msg, *args, **kw): self.log(self.WARN, msg, *args, **kw) def error(self, msg, *args, **kw): self.log(self.ERROR, msg, *args, **kw) def fatal(self, msg, *args, **kw): self.log(self.FATAL, msg, *args, **kw) def log(self, level, msg, *args, **kw): if args: if kw: raise TypeError( "You may give positional or keyword arguments, not both") args = args or kw rendered = None for consumer_level, consumer in self.consumers: if self.level_matches(level, consumer_level): if (self.in_progress_hanging and consumer in (sys.stdout, sys.stderr)): self.in_progress_hanging = False sys.stdout.write('\n') sys.stdout.flush() if rendered is None: if args: rendered = msg % args else: rendered = msg rendered = ' '*self.indent + rendered if hasattr(consumer, 'write'): consumer.write(rendered+'\n') else: consumer(rendered) def start_progress(self, msg): assert not self.in_progress, ( "Tried to start_progress(%r) while in_progress %r" % (msg, self.in_progress)) if self.level_matches(self.NOTIFY, self._stdout_level()): sys.stdout.write(msg) sys.stdout.flush() self.in_progress_hanging = True else: self.in_progress_hanging = False self.in_progress = msg def end_progress(self, msg='done.'): assert self.in_progress, ( "Tried to end_progress without start_progress") if self.stdout_level_matches(self.NOTIFY): if not self.in_progress_hanging: # Some message has been printed out since start_progress sys.stdout.write('...' + self.in_progress + msg + '\n') sys.stdout.flush() else: sys.stdout.write(msg + '\n')
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.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. import datetime from lxml import etree import webob from nova.api.openstack.compute.plugins.v3 import simple_tenant_usage from nova.compute import api from nova.compute import flavors from nova import context from nova import exception from nova.openstack.common import jsonutils from nova.openstack.common import policy as common_policy from nova.openstack.common import timeutils from nova import policy from nova import test from nova.tests.api.openstack import fakes from nova import utils SERVERS = 5 TENANTS = 2 HOURS = 24 ROOT_GB = 10 EPHEMERAL_GB = 20 MEMORY_MB = 1024 VCPUS = 2 NOW = timeutils.utcnow() START = NOW - datetime.timedelta(hours=HOURS) STOP = NOW FAKE_INST_TYPE = {'id': 1, 'vcpus': VCPUS, 'root_gb': ROOT
_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-0000-00000000000000%02d' % instance_id, 'image_ref': '1', 'project_id': tenant_id, 'user_id': 'fakeuser', 'display_name': 'name', 'state_description': 'state', 'instance_type_id': 1, 'launched_at': start, 'terminated_at': end, 'system_metadata': sys_meta} def fake_instance_get_active_by_window_joined(self, context, begin, end, project_id): return [get_fake_db_instance(START, STOP, x, "faketenant_%s" % (x / SERVERS)) for x in xrange(TENANTS * SERVERS)] class SimpleTenantUsageTest(test.TestCase): def setUp(self): super(SimpleTenantUsageTest, self).setUp() self.stubs.Set(api.API, "get_active_by_window", fake_instance_get_active_by_window_joined) self.admin_context = context.RequestContext('fakeadmin_0', 'faketenant_0', is_admin=True) self.user_context = context.RequestContext('fakeadmin_0', 'faketenant_0', is_admin=False) self.alt_user_context = context.RequestContext('fakeadmin_0', 'faketenant_1', is_admin=False) self.flags( osapi_compute_extension=[ 'nova.api.openstack.compute.contrib.select_extensions'], osapi_compute_ext_list=['Simple_tenant_usage']) def _test_verify_index(self, start, stop): req = webob.Request.blank( '/v3/os-simple-tenant-usage?start=%s&end=%s' % (start.isoformat(), stop.isoformat())) req.method = "GET" req.headers["content-type"] = "application/json" res = req.get_response(fakes.wsgi_app_v3( fake_auth_context=self.admin_context, init_only=('os-simple-tenant-usage', 'servers'))) self.assertEqual(res.status_int, 200) res_dict = jsonutils.loads(res.body) usages = res_dict['tenant_usages'] for i in xrange(TENANTS): self.assertEqual(int(usages[i]['total_hours']), SERVERS * HOURS) self.assertEqual(int(usages[i]['total_local_gb_usage']), SERVERS * (ROOT_GB + EPHEMERAL_GB) * HOURS) self.assertEqual(int(usages[i]['total_memory_mb_usage']), SERVERS * MEMORY_MB * HOURS) self.assertEqual(int(usages[i]['total_vcpus_usage']), SERVERS * VCPUS * HOURS) self.assertFalse(usages[i].get('server_usages')) def test_verify_index(self): self._test_verify_index(START, STOP) def test_verify_index_future_end_time(self): future = NOW + datetime.timedelta(hours=HOURS) self._test_verify_index(START, future) def test_verify_index_with_invalid_time_format(self): req = webob.Request.blank( '/v3/os-simple-tenant-usage?start=%s&end=%s' % ('aa', 'bb')) req.method = "GET" req.headers["content-type"] = "application/json" res = req.get_response(fakes.wsgi_app_v3( fake_auth_context=self.admin_context, init_only=('os-simple-tenant-usage', 'servers'))) self.assertEqual(res.status_int, 400) def test_verify_show(self): self._test_verify_show(START, STOP) def test_verify_show_future_end_time(self): future = NOW + datetime.timedelta(hours=HOURS) self._test_verify_show(START, future) def test_verify_show_with_invalid_time_format(self): tenant_id = 0 req = webob.Request.blank( '/v3/os-simple-tenant-usage/' 'faketenant_%s?start=%s&end=%s' % (tenant_id, 'aa', 'bb')) req.method = "GET" req.headers["content-type"] = "application/json" res = req.get_response(fakes.wsgi_app_v3( fake_auth_context=self.user_context, init_only=('os-simple-tenant-usage', 'servers'))) self.assertEqual(res.status_int, 400) def _get_tenant_usages(self, detailed=''): req = webob.Request.blank( '/v3/os-simple-tenant-usage?' 'detailed=%s&start=%s&end=%s' % (detailed, START.isoformat(), STOP.isoformat())) req.method = "GET" req.headers["content-type"] = "application/json" res = req.get_response(fakes.wsgi_app_v3( fake_auth_context=self.admin_context, init_only=('os-simple-tenant-usage', 'servers'))) self.assertEqual(res.status_int, 200) res_dict = jsonutils.loads(res.body) return res_dict['tenant_usages'] def test_verify_detailed_index(self): usages = self._get_tenant_usages('1') for i in xrange(TENANTS): servers = usages[i]['server_usages'] for j in xrange(SERVERS): self.assertEqual(int(servers[j]['hours']), HOURS) def test_verify_simple_index(self): usages = self._get_tenant_usages(detailed='0') for i in xrange(TENANTS): self.assertEqual(usages[i].get('server_usages'), None) def test_verify_simple_index_empty_param(self): # NOTE(lzyeval): 'detailed=&start=..&end=..' usages = self._get_tenant_usages() for i in xrange(TENANTS): self.assertEqual(usages[i].get('server_usages'), None) def _test_verify_show(self, start, stop): tenant_id = 0 req = webob.Request.blank( '
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 logger=None class provisionError(Exception): def __init__(self, value): self.value=value def __str__(self): return repr(self.value) def complete_dom(text, line, begidx, endidx): logger.debug("In Function {0}".format(inspect.stack()[0][3])) comp_type=cli_fmwk.autocomp(['domain'], text) args=line.split() if len(args) == 2 and line[-1] == ' ': #Second level. if args[1]=='domain': print("<domain name>") comp_type=[''] return comp_type def complete_network(text, line, begidx, endidx): logger.debug("In Function {0}".format(inspect.stack()[0][3])) comp_type=cli_fmwk.autocomp(['network'], text) args=line.split() if len(args) == 2 and line[-1] == ' ': #Second level. if args[1]=='network': print("<network name>") comp_type=[''] return comp_type def complete_nwk_dom(text, line, begidx, endidx): logger.debug("In Function {0}".format(inspect.stack()[0][3])) comp_type=cli_fmwk.autocomp(['domain', 'network'], text) args=line.split() if len(args) == 2 and line[-1] == ' ': #Second level. if args[1]=='domain': print("<domain name>") comp_type=[''] if args[1]=='network': print("<network name>") comp_type=[''] return comp_type def complete_nwk_dom_ifc(text, line, begidx, endidx): logger.debug("In Function {0}".format(inspect.stack()[0][3])) comp_type=cli_fmwk.autocomp(['domain', 'network', 'interface'], text) args=line.split() if len(args) == 2 and line[-1] == ' ': #Second level. if args[1]=='domain': print("<domain name>") comp_type=[''] if args[1]=='network': print("<network name>") comp_type=[''] if args[1]=='interface': print("<interface name>") comp_type=[''] return comp_type def error_log_print(msg): logger.error(msg) print(msg) def _iso_prep(dom, pm_group): logger.debug("In Function {0}".format(inspect.stack()[0][3])) logger.info("Packgage group file {0}".format(pm_group)) d={} with open(pm_group) as f: d=json.load(f) if not 'main' in d: raise provisionError("'main' repository not defined in package group") main_d=d['main'] if 'iso' in main_d: logger.info("Attaching iso to dom") py_libvirt.attach_cdrom_hp(dom, main_d['iso']) elif 'dev' in main_d: logger.info("Attaching cdrom device to dom") py_libvirt.attach_cdrom_dev_hp(dom, main_d['dev']) def _cdrom_eject(dom): logger.debug("In Function {0}".format(inspect.stack()[0][3])) py_libvirt.detach_cdrom_dev_hp(dom) def _host_network_store(name, ip, mac): #Store domain net configs in net directory j_dict={} j_dict['fab0_dom_name']=name j_dict['fab0_dom_ip']=ip j_dict['fab0_dom_mac']=mac net_fname="{0}.net".format(name) net_file = os.path.join("net", net_fname) logger.info("Generating domain networking file {0}".format(net_file)) with open(net_file, 'w') as f: json.dump(j_dict, f) class provCLI(cli_fmwk.VCCli): def __init__(self): logger.debug("Initialized {0} class".format(self.__class__)) cli_fmwk.VCCli.__init__(self, intro="virtcluster provision cli") self.def_comp_lst=['domain', 'network'] def postloop(self): py_libvirt.con_fin(self._con) def preloop(self): self._con = py_libvirt.con_init() def do_domain(self, args): logger.debug("In Function {0}".format(inspect.stack()[0][3])) dom_cli=provCLI_domain(self._con) dom_cli.cmdloop() def help_domain(self): logger.debug("In Function {0}".format(inspect.stack()[0][3])) print(" Domain subcommands ") def do_network(self, args): logger.debug("In Function {0}".format(inspect.stack()[0][3])) nwk_cli=provCLI_network(self._con) nwk_cli.cmdloop() def help_network(self): logger.debug("In Function {0}".format(inspect.stack()[0][3])) print(" Network subcommands ") def do_commision(self, args): logger.debug("In Function {0}".format(inspect.stack()[0][3])) com_cli=provCLI_commision(self._con) com_cli.cmdloop() def help_commision(self): logger.debug("In Function {0}".format(inspect.stack()[0][3])) print(" Commision subcommands ") def do_info(self, args): logger.debug("In Function {0}".format(inspect.stack()[0][3])) arg_lst=args.split() if len(arg_lst) != 2: self.help_info() return comp_type=cli_fmwk.autocomp(['domain'], arg_lst[0]) if comp_type==['domain']: dom_name=arg_lst[1] dom = py_libvirt.dom_lookup(self._con, dom_name) if not dom: error_log_print("Domain not defined") return s=py_libvirt.info_domain(dom) print(s) s=py_libvirt.get_vncport(dom_name) print(s) else: print("Enter domain") return def help_info(self): logger.debug("In Function {0}".format(inspect.stack()[0][3])) print(" Info domain <domain name> ") def complete_info(self, text, line, begidx, endidx): logger.debug("In Function {0}".format(inspect.stack()[0][3])) return complete_dom(text, line, begidx, endidx) def do_list(self, args): logger.debug("In Function {0}".format(inspect.stack()[0][3])) print ("\nDomain:") print ("-------") s = py_libvirt.list_domains(self._con) print (s) print ("\nNetwork:") print ("--------") s = py_libvirt.list_network(self._con) new_s=s.replace('virtcluster_fabric0', 'fabric') print (new_s) print ("\nInterfaces:") print ("-----------") s = py_libvirt.list_interfaces(self._con) print (s) print ("\nStorage Volume:") print ("---------------") s = py_libvirt.list_storage_vol(self._con) print (s) def help_list(self): logger.debug("In Function {0}".format(inspect.stack()[0][3])) print(" List domains ") def do_dumpxml(self, args): logger.debug("In Function {0}".format(inspect.stack()[0][3])) arg_lst=args.split() if len(arg_lst) != 2: self.help_dumpxml() return comp_lst=['domain', 'network', 'interface'] comp_type=cli_fmwk.autocomp(comp_lst, arg_lst[0]) if comp_type==['domain']: dom_name=arg_lst[1] dom = py_libvirt.dom_lookup(self._con, dom_name) if not dom: error_log_print("Domain not defined") return s = py_libvirt.dumpxml_domain(dom) print(s) elif comp_type==['network']: nwk_name=arg_lst[1] nwk = py_libvirt.netw
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, ifc_name) if not ifc: error_log_print("Interface not defined") return s=py_libvirt.dumpxml_network(ifc) print(s) else: print("Enter domain, network or interface") return def help_dumpxml(self): logger.debug("In Function {0}".format(inspect.stack()[0][3])) print(" Dump XML of either: ") print(" domain <domain name>
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(rawBlockHeader, 32, 76) # self.__setupForParsing(rawBlockHeader) # version = readUInt32LE() # hashPrevBlock = self.readUnsignedBitsLE(256) # hashMerkleRoot = self.readUnsignedBitsLE(256) # time = readUInt32LE() # bits = readUInt32LE() # nonce = readUInt32LE() res = hashHeader(version, hashPrevBlock, hashMerkleRoot, time, bits, nonce) return(res) # def isNonceValid(version, hashPrevBlock, hashMerkleRoot, time, bits, nonce): # target = targetFromBits(bits) # # hash = hashHeader(version, hashPrevBlock, hashMerkleRoot, time, bits, nonce) # # if lt(hash, target): # return(1) # else: # return(0) macro hashHeader($version, $hashPrevBlock, $hashMerkleRoot, $time, $bits, $nonce): $_version = flipBytes($version, 4) $_hashPrevBlock = flipBytes($hashPrevBlock, 32) $_hashMerkleRoot = flipBytes($hashMerkleRoot, 32) $_time = flipBytes($time, 4) $_bits = flipBytes($bits, 4) $_nonce = flipBytes($nonce, 4) $hash = doRawHashBlockHeader($_version, $_hashPrevBlock, $_hashMerkleRoot, $_time, $_bits, $_nonce) $retHash = flipBytes($hash, 32) $retHash macro doRawHashBlockHeader($version, $hashPrevBlock, $hashMerkleRoot, $time, $bits, $nonce): verPart = shiftLeftBytes($version, 28) hpb28 = shiftRightBytes($hashPrevBlock, 4) # 81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a3080000 b1 = verPart | hpb28 hpbLast4 = shiftLeftBytes($hashPrevBlock, 28) # 000000000 hm28 = shiftRightBytes($hashMerkleRoot, 4) # e320b6c2fffc8d750423db8b1eb942ae710e951ed797f7affc8892b0 b2 = hpbLast4 | hm28 hmLast4 = shiftLeftBytes($hashMerkleRoot, 28) timePart = ZEROS | shiftLeftBytes($time, 24) bitsPart = ZEROS | shiftLeftBytes($bits, 20) noncePart = ZEROS | shiftLeftBytes($nonce, 16) b3 = hmLast4 | timePart | bitsPart | noncePart hash1 = sha256([b1,b2,b3], chars=80) hash2 = sha256([hash1], items=1) hash2 # eg 0x6162 will be 0x6261 macro flipBytes($n, $numByte): $b = byte(31, $n) $i = 30 $j = 1 while $j < $numByte: $b = ($b * 256) | byte($i, $n) $i -= 1 $j += 1 $b # shift left bytes macro shiftLeftBytes($n, $x): $n * 256^$x # set the base to 2 (instead of 256) if we want a macro to shift only bits # shift right macro shiftRightBytes($n, $x): div($n, 256^$x)
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): readonly_fields = ( 'date_modified', 'date_created', ) list_display = ( '__str__', 'amount', 'payment_provider', 'status', 'date_created', 'referrer', ) l
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): PartyInProgress = apps.get_model('viewsenators', 'Party') db_alias = schema_editor.connection.alias PartyInProgress.objects.using(db_alias).all().delete() # Convert and unconvert a party from a string to an object def convertParty(apps, schema_editor): SenatorInProgress = apps.get_model('viewsenators', 'Senator') PartyInProgress = apps.get_model('viewsenators', 'Party') db_alias = schema_editor.connection.alias for senator in SenatorInProgress.objects.using(db_alias).all(): senator.party = PartyInProgress.objects.using(db_alias).get(abbrev=senator.party_old) senator.save() def unconvertParty(apps, schema_editor): SenatorInProgress = apps.get_model('viewsenators', 'Senator') db_alias = schema_editor.connection.alias for senator in SenatorInProgress.objects.using(db_alias).all(): senator.party_old = senator.party.abbrev senator.save() class Migration(migrations.Migration): dependencies = [ ('viewsenators', '0003_contactlist_slug'), ] operations = [ migrations.CreateModel( name='City', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=64)), ('facebookId', models.CharField(max_length=16)), ('population', models.PositiveIntegerField()), ('state', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='viewsenators.State')), ], ), migrations.CreateModel( name='Congressmember', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('firstName', models.CharField(max_length=128)), ('lastName', models.CharField(max_length=128)), ('cities', models.ManyToManyField(to='viewsenators.City')), ], ), migrations.CreateModel( name='Party', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abbrev', models.CharField(max_length=1)), ('name', models.CharField(max_length=16)), ('adjective', models.CharField(max_length=16)), ], ), migrations.AddField( model_name='congressmember', name='party', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='viewsenators.Party'), ), # Generate the contactList on the fly instead. Add a default so # it's undoable. migrations.AlterField( model_name='ContactList', name='fbUrl', field=models.CharField(max_length=4096, default=""), preserve_default=True, ), migrations.RemoveField( model_name='ContactList', name='fbUrl', ), # move "party" to "party_old", create a new field, run code to convert, # then delete "party_old" migrations.RunPython(populateParties, reverse_code=unpopulateParties), migrations.RenameField( model_name='senator', old_name='party', new_name='party_old', ), migrations.AddField( model_name='senator', name='party', field=models.ForeignKey(null=True,on_delete=django.db.models.deletion.CASCADE, to='viewsenators.Party'), ), migrations.RunPython(convertParty, reverse_code=unconvertParty), migrations.AlterField( # make it not nullable anymore model_name='senator', name='party', field=models.ForeignKey(null=False,on_delete=django.db.models.deletion.CASCADE, to='viewsenators.Party'), ), migrations.AlterField( # make nullable so it can be reversed model_name='senator', name='party_old', preserve_default=True, field=models.CharField(max_length=1, default="R", null=True), ), migrations.RemoveField( model_name='senator', name='party_old', ), ]
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, pi from matplotlib import pyplot, ticker, rc rc('text', usetex=True) rc('font',**{'family':'serif','serif':['Computer Modern']}) if len(argv)==1: end_index = -1 data_path = "data" elif len(arg
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 = collect("T_electron", path=data_path, xind=2, info=True, yguards=True) Ti = collect("T_ion", path=data_path, xind=2, info=True, yguard
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') pyplot.title("Te (red) and Ti (blue) at the (left) boundary") pyplot.axes().xaxis.set_major_formatter(ticker.FormatStrFormatter("%g")) pyplot.axes().grid(color='grey', which='both') else: pyplot.semilogx(Te_left[:],'r',Ti_left[:],'b') pyplot.title("Te (red) and Ti (blue) at the (left) boundary") pyplot.axes().xaxis.set_major_formatter(ticker.FormatStrFormatter(r"$%g$")) pyplot.axes().grid(color='grey', which='both') pyplot.show()
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_RD_LSB_FIRST = _IOR(SPI_IOC_MAGIC, 2, "=B") SPI_IOC_WR_LSB_FIRST = _IOW(SPI_IOC_MAGIC, 2, "=B") SPI_IOC_RD_BITS_PER_WORD = _IOR(SPI_IOC_MAGIC, 3, "=B") SPI_IOC_WR_BITS_PER_WORD = _IOW(SPI_IOC_MAGIC, 3, "=B") SPI_IOC_RD_MAX_SPEED_HZ = _IOR(SPI_IOC_MAGIC, 4, "=I") SPI_IOC_WR_MAX_SPEED_HZ = _IOW(SPI_IOC_MAGIC, 4, "=I") SPI_CPHA = 0x01 # /* clock phase */ SPI_CPOL = 0x02 # /* clock polarity */ SPI_MODE_0 = (0|0) # /* (original MicroWire) */ SPI_MODE_1 = (0|SPI_CPHA) SPI_MODE_2 = (SPI_CPOL|0) SPI_MODE_3 = (SPI_CPOL|SPI_CPHA) class Lepton(object): """Communication class for FLIR Lepton module on SPI Args: spi_dev (str): Location of SPI device node. Default '/dev/spidev0.0'. """ ROWS = 60 COLS = 80 VOSPI_FRAME_SIZE = COLS + 2 VOSPI_FRAME_SIZE_BYTES = VOSPI_FRAME_SIZE * 2 MODE = SPI_MODE_3 BITS = 8 SPEED = 18000000 SPIDEV_MESSAGE_LIMIT = 24 def __init__(self, spi_dev = "/dev/spidev0.0"): self.__spi_dev = spi_dev self.__txbuf = np.zeros(Lepton.VOSPI_FRAME_SIZE, dtype=np.uint16) # struct spi_ioc_transfer { # __u64 tx_buf; # __u64 rx_buf; # __u32 len; # __u32 speed_hz; # __u16 delay_usecs; # __u8 bits_per_word; # __u8 cs_change; # __u32 pad; # }; self.__xmit_struct = struct.Struct("=QQIIHBBI") self.__msg_size = self.__xmit_struct.size self.__xmit_buf = np.zeros((self.__msg_size * Lepton.ROWS), dtype=np.uint8) self.__msg = _IOW(SPI_IOC_M
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_SIZE_BYTES * i, # __u64 rx_buf; Lepton.VOSPI_FRAME_SIZE_BYTES, # __u32 len; Lepton.SPEED, # __u32 speed_hz; 0, # __u16 delay_usecs; Lepton.BITS, # __u8 bits_per_word; 1, # __u8 cs_change; 0) # __u32 pad; def __enter__(self): # "In Python 3 the only way to open /dev/tty under Linux appears to be 1) in binary mode and 2) with buffering disabled." self.__handle = open(self.__spi_dev, "wb+", buffering=0) ioctl(self.__handle, SPI_IOC_RD_MODE, struct.pack("=B", Lepton.MODE)) ioctl(self.__handle, SPI_IOC_WR_MODE, struct.pack("=B", Lepton.MODE)) ioctl(self.__handle, SPI_IOC_RD_BITS_PER_WORD, struct.pack("=B", Lepton.BITS)) ioctl(self.__handle, SPI_IOC_WR_BITS_PER_WORD, struct.pack("=B", Lepton.BITS)) ioctl(self.__handle, SPI_IOC_RD_MAX_SPEED_HZ, struct.pack("=I", Lepton.SPEED)) ioctl(self.__handle, SPI_IOC_WR_MAX_SPEED_HZ, struct.pack("=I", Lepton.SPEED)) return self def __exit__(self, type, value, tb): self.__handle.close() @staticmethod def capture_segment(handle, xs_buf, xs_size, capture_buf): messages = Lepton.ROWS iow = _IOW(SPI_IOC_MAGIC, 0, xs_size) ioctl(handle, iow, xs_buf, True) while (capture_buf[0] & 0x000f) == 0x000f: # byteswapped 0x0f00 ioctl(handle, iow, xs_buf, True) messages -= 1 # NB: the default spidev bufsiz is 4096 bytes so that's where the 24 message limit comes from: 4096 / Lepton.VOSPI_FRAME_SIZE_BYTES = 24.97... # This 24 message limit works OK, but if you really need to optimize the read speed here, this hack is for you: # The limit can be changed when spidev is loaded, but since it is compiled statically into newer raspbian kernels, that means # modifying the kernel boot args to pass this option. This works too: # $ sudo chmod 666 /sys/module/spidev/parameters/bufsiz # $ echo 65536 > /sys/module/spidev/parameters/bufsiz # Then Lepton.SPIDEV_MESSAGE_LIMIT of 24 can be raised to 59 while messages > 0: if messages > Lepton.SPIDEV_MESSAGE_LIMIT: count = Lepton.SPIDEV_MESSAGE_LIMIT else: count = messages iow = _IOW(SPI_IOC_MAGIC, 0, xs_size * count) ret = ioctl(handle, iow, xs_buf[xs_size * (60 - messages):], True) if ret < 1: raise IOError("can't send {0} spi messages ({1})".format(60, ret)) messages -= count def capture(self, data_buffer = None, log_time = False, debug_print = False, retry_reset = True): """Capture a frame of data. Captures 80x60 uint16 array of non-normalized (raw 12-bit) data. Returns that frame and a frame_id (which is currently just the sum of all pixels). The Lepton will return multiple, identical frames at a rate of up to ~27 Hz, with unique frames at only ~9 Hz, so the frame_id can help you from doing additional work processing duplicate frames. Args: data_buffer (numpy.ndarray): Optional. If specified, should be ``(60,80,1)`` with `dtype`=``numpy.uint16``. Returns: tuple consisting of (data_buffer, frame_id) """ start = time.time() if data_buffer is None: data_buffer = np.ndarray((Lepton.ROWS, Lepton.COLS, 1), dtype=np.uint16) elif data_buffer.ndim < 2 or data_buffer.shape[0] < Lepton.ROWS or data_buffer.shape[1] < Lepton.COLS or data_buffer.itemsize < 2: raise Exception("Provided input array not large enough") while True: Lepton.capture_segment(self.__handle, self.__xmit_buf, self.__msg_size, self.__capture_buf[0]) if retry_reset and (self.__capture_buf[20, 0] & 0xFF0F) != 0x1400: # make sure that this is a well-formed frame, should find line 20 here # Leave chip select deasserted for at least 185 ms to reset if debug_print: print("Garbage frame number reset waiting...") time.sleep(0.185) else: break self.__capture_buf.byteswap(True) data_buffer[:,:] = self.__capture_buf[:,2:] end = time.time() if debug_print: print("---") for i in range(Lepton.ROWS): fid = self.__capture_buf[i, 0, 0] crc = self.__capture_buf[i, 1, 0] fnum = fid & 0xFFF print("0x{0:04x} 0x{1:04x} : Row {2:2} : crc={1}".format(fid, crc, fnum)) print("---") if log_time: print("frame processed int {0}s, {1}hz".format(end-start, 1.0/(end-start))) # TODO: turn on telemetry to get real frame id, sum on this array is fast enough though (< 500us) return data_buffer, data_buffer.sum()
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) def test_root_resource_not_found_url(self): request = make_request(uri='shouldneverfindthisthing') self.assertEquals(request.responseCode, NOT_FOUND) class AuthResourceTestCase(TestCase): def _try_auth(self, credentials, expected): request = make_request(uri='/auth/', method='POST', args=credentials) self.assertEquals(request.responseCode, OK) self.assertEquals(request.data, expected) def test_auth_success_with_good_parameters(self): credentials = {'username': 'myself', 'password': 'somethingawesome'} self._try_auth(credentials, '{"status": "success"}') def test_auth_failure_with_missing_parameters(self): credentials = {'username': 'myself', 'password': 'somethingawesome'} for (k, v) in credentials.items(): self._try_auth({k: v}, '{"status": "failure"}')
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_logging():
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): with patch_find_executable(['/bin/docker', None]): with handle_connection_errors(mock.Mock()): raise ConnectionError() _, args, _ = mock_logging.error.mock_calls[0] assert "Couldn't connect to Docker daemon" in args[0] def test_api_error_version_mismatch(self, mock_logging): with pytest.raises(errors.ConnectionError): with handle_connection_errors(mock.Mock(api_version='1.22')): raise APIError(None, None, b"client is newer than server") _, args, _ = mock_logging.error.mock_calls[0] assert "Docker Engine of version 1.10.0 or greater" in args[0] def test_api_error_version_mismatch_unicode_explanation(self, mock_logging): with pytest.raises(errors.ConnectionError): with handle_connection_errors(mock.Mock(api_version='1.22')): raise APIError(None, None, u"client is newer than server") _, args, _ = mock_logging.error.mock_calls[0] assert "Docker Engine of version 1.10.0 or greater" in args[0] def test_api_error_version_other(self, mock_logging): msg = b"Something broke!" with pytest.raises(errors.ConnectionError): with handle_connection_errors(mock.Mock(api_version='1.22')): raise APIError(None, None, msg) mock_logging.error.assert_called_once_with(msg.decode('utf-8')) def test_api_error_version_other_unicode_explanation(self, mock_logging): msg = u"Something broke!" with pytest.raises(errors.ConnectionError): with handle_connection_errors(mock.Mock(api_version='1.22')): raise APIError(None, None, msg) mock_logging.error.assert_called_once_with(msg)
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.util import Throttle import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) _RESOURCE = 'http://apilayer.net/api/live' CONF_ATTRIBUTION = "Data provided by currencylayer.com" DEFAULT_BASE = 'USD' DEFAULT_NAME = 'CurrencyLayer Sensor' ICON = 'mdi:currency' MIN_TIME_BETWEEN_UPDATES = timedelta(hours=2) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_API_KEY): cv.string, vol.Required(CONF_QUOTE): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_BASE, default=DEFAULT_BASE): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, }) def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Currencylayer sensor.""" base = config.get(CONF_BASE) api_key = config.get(CONF_API_KEY) parameters = { 'source': base, 'access_key': api_key, 'format': 1, } rest = CurrencylayerData(_RESOURCE, parameters) response = requests.get(_RESOURCE, params=parameters, timeout=10) sensors = [] for variable in config['quote']: sensors.append(CurrencylayerSensor(rest, base, variable)) if 'error' in response.json(): return False else: add_devices(sensors) rest.update() class CurrencylayerSensor(Entity): """Implementing the Currencylayer sensor.""" def __init__(self, rest, base, quote): """Initialize the sensor.""" self.rest = rest self._quote = quote self._base = base self.update() @property def name(self): """Return the name of the sensor.""" return '{} {}'.format(self._base, self._quote) @property def icon(self): """Return the icon to use in the frontend, if any.""" return ICON @property def state(self): """Return the state of the sensor.""" return self._state @property def device_state_attributes(self): """Return the state attributes of the sensor.""" return { ATTR_ATTRIBUTION: CONF_ATTRIBUTION, } def update(self): """Update current date.""" self.rest.update() value = self.rest.data if value is not None: self._state = round( value['{}{}'.format(self._base, self._quote)], 4) class CurrencylayerData(object): """Get data from Currencylayer.org.""" def __init__(self, resource, parameters): """Initialize the data object.""" self._resource = resource self._parameters = parameters self.data = None @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data from Currencylayer.""" try: result = requests.get( self._resource, params=self._parameters, timeout=10) if 'error' in result.json(): raise ValueError(result.json()['error']['info']) else: self.data = result.json()['quotes'] _LOGGER.debug("Currencylayer data updated: %s", result.json()['timestamp']) except ValueError as err: _LOGGER.error("Check Currencylayer API %s", err.args) self.data = None
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 more notifications. Notifications can be created just for the triggering user, or for all friends of the user, or for those who have the user as a contact, etc. See the header to notification.py for more information about notifications. 2. Creates activities for operations that modify viewpoint assets. 3. Sends push alerts to client devices for operations that require them. """ __authors__ = ['spencer@emailscrubbed.com (Spencer Kimball)', 'andy@emailscrubbed.com (Andy Kimball)'] import json import logging from tornado import gen from viewfinder.backend.base import util from viewfinder.backend.db.activity import Activity from viewfinder.backend.db.contact import Contact from viewfinder.backend.db.device import Device from viewfinder.backend.db.followed import Followed from viewfinder.backend.db.notification import Notification from viewfinder.backend.db.operation import Operation from viewfinder.backend.db.settings import AccountSettings class NotificationManager(object): """Viewfinder notification data object. Methods on this class may be safely called without acquiring a lock for the notified user. This is important, because operations from multiple other users might trigger the concurrent creation of notifications for the same user. This class contains race detection and retry logic to handle this case. Methods on this class assume that an operation is currently in progress and that Operation.GetCurrent() will return a valid operation. Various attributes of the notifications are based upon the current operation in order to make notification creation idempotent in case the operation restarts. Tricky cases to consider when making changes: - unshare: Can generate notifications on viewpoints to which the current user does not have access. This happens when the unshared photo(s) have been reshared. - update_follower: Modifies metadata returned by query_viewpoints, but since only follower metadata is affected, no activity is created. This means that the notification viewpoint_id is defined but the activity is not. """ MAX_INLINE_COMMENT_LEN = 512 """Maximum length of a comment message that will be in-lined in a NotificationManager.""" _QUERY_LIMIT = 100 """Maximum number of notifications returned by QuerySince.""" @classmethod @gen.coroutine def QuerySince(cls, client, user_id, device_id, start_key, limit=None, scan_forward=True): """Queries all notifications intended for 'user_id' with max 'limit' notifications since 'start_key'. Creates a special "clear_badges" notification once all notifications have been queried. This resets the current badge counter and results in the push of an alert to all *other* devices so that their badge number can be updated to 0. If 'scan_forward' is false, then query in reverse (descending order), and do not set clear_badges. """ from viewfinder.backend.op.alert_manager import AlertManager # Use consistent read to ensure that no notifications are skipped. limit = NotificationManager._QUERY_LIMIT if limit is None else limit notifications = yield gen.Task(Notification.RangeQuery, client, hash_key=user_id, range_desc=None, limit=limit, col_names=None, excl_start_key=start_key, consistent_read=True, scan_forward=scan_forward) # If all notifications have been queried, get the last notification. if len(notifications) < limit and scan_forward: if len(notifications) == 0: last_notification = yield Notification.QueryLast(client, user_id, consistent_read=True) else: last_notification = notifications[-1] # If all notifications have been queried, add the special "clear_badges" notification. if last_notification is None or last_notification.badge == 0: raise gen.Return(notifications) # If TryClearBadge returns false, then new notifications showed up while the query was running, and so # retry creation of the notification. notification_id = last_notification.notification_id + 1 if last_notification else 0 success = yield Notification.TryClearBadge(client, user_id, device_id, notification_id) if not success: results = yield NotificationManager.QuerySince(client, user_id, device_id, start_key, scan_forward=scan_forward) raise gen.Return(results) # Push badge update to any other devices this user owns, but exclude the current device # because pushing badge=0 to it is redundant and annoying. AlertManager.SendClearBadgesAlert(client, user_id, exclude_device_id=device_id) raise gen.Return(notifications) @classmethod @gen.coroutine def NotifyAddFollowers(cls, client, viewpoint_id, existing_followers, new_followers, contact_user_ids, act_dict, timestamp): """Notifies the specified followers that th
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. new_follower_ids = set(follower.user_id for follower in new_followers) def _GetInvalidate(follower_id): if follower_id in new_follower_ids: return {'viewpoints': [NotificationManager._CreateViewpointInvalidation(viewpoint_id)]} else: return {'viewpoints': [{'viewpoint_id': viewpoint_id, 'get_followers': True}]} yield NotificationManager._NotifyFollowers(client, viewpoint_id, existing_followers + new_followers, _GetInvalidate, activity_func) @classmethod @gen.coroutine def NotifyCreateProspective(cls, client, prospective_identity_keys, timestamp): """Sends notifications that the given identities have been linked to new prospective user accounts. Sends notifications to all users that have a contact with a matching identity. """ # Invalidate any contacts that may have been bound to a user id. yield [NotificationManager._NotifyUsersWithContact(client, 'create prospective user', identity_key, timestamp) for identity_key in prospective_identity_keys] @classmethod @gen.coroutine def NotifyFetchContacts(cls, client, user_id, timestamp, reload_all): """Adds a notification for the specified user that new contacts have been fetched and need to be pulled to the client. Invalidates all the newly fetched contacts, which all have sort_key greater than "timestamp". """ invalidate = {'contacts': {'start_key': Contact.CreateSortKey(None, 0 if reload_all else timestamp)}} if reload_all: invalidate['contacts']['all'] = True yield NotificationManager.CreateForUser(client, user_id, 'fetch_co