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
tao12345666333/tornado-zh
tornado/test/twisted_test.py
Python
mit
27,525
0.000327
# Author: Ovidiu Predescu # Date: July 2011 # # 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. """ Unittest for the twisted-style reactor. """ from __future__ import absolute_import, division, print_function, with_statement import logging import os import shutil import signal import sys import tempfile import threading import warnings try: import fcntl from twisted.internet.defer import Deferred, inlineCallbacks, returnValue from twisted.internet.interfaces import IReadDescriptor, IWriteDescriptor from twisted.internet.protocol import Protocol from twisted.python import log from tornado.platform.twisted import TornadoReactor, TwistedIOLoop from zope.interface import implement
er have_twisted = True except ImportError: have_twisted = False # The core of Twisted 12.3.0 is available on python 3, but twisted.web is not # so test for it separately. try: from twisted.web.client import Agent, readBody from twisted.web.resource import Resource from twisted.web.server import Site # As of Twisted 15.0.0, twisted.web is present but fails our # tests due to internal str/bytes errors. have_twisted_web = sys.
version_info < (3,) except ImportError: have_twisted_web = False try: import thread # py2 except ImportError: import _thread as thread # py3 from tornado.escape import utf8 from tornado import gen from tornado.httpclient import AsyncHTTPClient from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.platform.auto import set_close_exec from tornado.platform.select import SelectIOLoop from tornado.testing import bind_unused_port from tornado.test.util import unittest from tornado.util import import_object from tornado.web import RequestHandler, Application skipIfNoTwisted = unittest.skipUnless(have_twisted, "twisted module not present") skipIfPy26 = unittest.skipIf(sys.version_info < (2, 7), "twisted incompatible with singledispatch in py26") def save_signal_handlers(): saved = {} for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGCHLD]: saved[sig] = signal.getsignal(sig) if "twisted" in repr(saved): if not issubclass(IOLoop.configured_class(), TwistedIOLoop): # when the global ioloop is twisted, we expect the signal # handlers to be installed. Otherwise, it means we're not # cleaning up after twisted properly. raise Exception("twisted signal handlers already installed") return saved def restore_signal_handlers(saved): for sig, handler in saved.items(): signal.signal(sig, handler) class ReactorTestCase(unittest.TestCase): def setUp(self): self._saved_signals = save_signal_handlers() self._io_loop = IOLoop() self._reactor = TornadoReactor(self._io_loop) def tearDown(self): self._io_loop.close(all_fds=True) restore_signal_handlers(self._saved_signals) @skipIfNoTwisted class ReactorWhenRunningTest(ReactorTestCase): def test_whenRunning(self): self._whenRunningCalled = False self._anotherWhenRunningCalled = False self._reactor.callWhenRunning(self.whenRunningCallback) self._reactor.run() self.assertTrue(self._whenRunningCalled) self.assertTrue(self._anotherWhenRunningCalled) def whenRunningCallback(self): self._whenRunningCalled = True self._reactor.callWhenRunning(self.anotherWhenRunningCallback) self._reactor.stop() def anotherWhenRunningCallback(self): self._anotherWhenRunningCalled = True @skipIfNoTwisted class ReactorCallLaterTest(ReactorTestCase): def test_callLater(self): self._laterCalled = False self._now = self._reactor.seconds() self._timeout = 0.001 dc = self._reactor.callLater(self._timeout, self.callLaterCallback) self.assertEqual(self._reactor.getDelayedCalls(), [dc]) self._reactor.run() self.assertTrue(self._laterCalled) self.assertTrue(self._called - self._now > self._timeout) self.assertEqual(self._reactor.getDelayedCalls(), []) def callLaterCallback(self): self._laterCalled = True self._called = self._reactor.seconds() self._reactor.stop() @skipIfNoTwisted class ReactorTwoCallLaterTest(ReactorTestCase): def test_callLater(self): self._later1Called = False self._later2Called = False self._now = self._reactor.seconds() self._timeout1 = 0.0005 dc1 = self._reactor.callLater(self._timeout1, self.callLaterCallback1) self._timeout2 = 0.001 dc2 = self._reactor.callLater(self._timeout2, self.callLaterCallback2) self.assertTrue(self._reactor.getDelayedCalls() == [dc1, dc2] or self._reactor.getDelayedCalls() == [dc2, dc1]) self._reactor.run() self.assertTrue(self._later1Called) self.assertTrue(self._later2Called) self.assertTrue(self._called1 - self._now > self._timeout1) self.assertTrue(self._called2 - self._now > self._timeout2) self.assertEqual(self._reactor.getDelayedCalls(), []) def callLaterCallback1(self): self._later1Called = True self._called1 = self._reactor.seconds() def callLaterCallback2(self): self._later2Called = True self._called2 = self._reactor.seconds() self._reactor.stop() @skipIfNoTwisted class ReactorCallFromThreadTest(ReactorTestCase): def setUp(self): super(ReactorCallFromThreadTest, self).setUp() self._mainThread = thread.get_ident() def tearDown(self): self._thread.join() super(ReactorCallFromThreadTest, self).tearDown() def _newThreadRun(self): self.assertNotEqual(self._mainThread, thread.get_ident()) if hasattr(self._thread, 'ident'): # new in python 2.6 self.assertEqual(self._thread.ident, thread.get_ident()) self._reactor.callFromThread(self._fnCalledFromThread) def _fnCalledFromThread(self): self.assertEqual(self._mainThread, thread.get_ident()) self._reactor.stop() def _whenRunningCallback(self): self._thread = threading.Thread(target=self._newThreadRun) self._thread.start() def testCallFromThread(self): self._reactor.callWhenRunning(self._whenRunningCallback) self._reactor.run() @skipIfNoTwisted class ReactorCallInThread(ReactorTestCase): def setUp(self): super(ReactorCallInThread, self).setUp() self._mainThread = thread.get_ident() def _fnCalledInThread(self, *args, **kwargs): self.assertNotEqual(thread.get_ident(), self._mainThread) self._reactor.callFromThread(lambda: self._reactor.stop()) def _whenRunningCallback(self): self._reactor.callInThread(self._fnCalledInThread) def testCallInThread(self): self._reactor.callWhenRunning(self._whenRunningCallback) self._reactor.run() class Reader(object): def __init__(self, fd, callback): self._fd = fd self._callback = callback def logPrefix(self): return "Reader" def close(self): self._fd.close() def fileno(self): return self._fd.fileno() def readConnectionLost(self, reason): self.close() def connectionLost(self, reason): self.close() def doRead(self): self._callback(self._fd) if have_twisted: Reader = implementer(IReadDescriptor)(Reader) class Writer(object): def __init__(self, fd, callback): self._fd = fd self._c
fepe55/RAMB0
python/huffman2.py
Python
mit
6,447
0.005119
#!/usr/bin/python # -*- encoding: utf-8 -*- import os import marshal import cPickle import array class HuffmanNode(object): recurPrint = False def __init__(self, ch=None, fq=None, lnode=None, rnode=None, parent=None): self.L = lnode self.R = rnode self.p = parent self.c = ch self.fq = fq def __repr__(self): if HuffmanNode.recurPrint: lnode = self.L if self.L else '#' rnode = self.R if self.R else '#' return ''.join( ('(%s:%d)'%(self.c, self.fq), str(lnode), str(rnode) ) ) else: return '(%s:%d)'%(self.c, self.fq) def __cmp__(self, other): if not isinstance(other, HuffmanNode): return super(HuffmanNode, self).__cmp__(other) return cmp(self.fq, other.fq) def _pop_first_two_nodes(nodes): if len(nodes)>1: first=nodes.pop(0) second=nodes.pop(0) return first, second else: #print "[popFirstTwoNodes] nodes's length <= 1" return nodes[0], None def _build_tree(nodes): nodes.sort() while(True): first, second = _pop_first_two_nodes(nodes) if not second: return first parent = HuffmanNode(lnode=first, rnode=second, fq=first.fq+second.fq) first.p = parent second.p = parent nodes.insert(0, parent) nodes.sort() def _gen_huffman_code(node, dict_codes, buffer_stack=[]): if not node.L and not node.R: dict_codes[node.c] = ''.join(buffer_stack) return buffer_stack.append('0') _gen_huffman_code(node.L, dict_codes, buffer_stack) buffer_stack.pop() buffer_stack.append('1') _gen_huffman_code(node.R, dict_codes, buffer_stack) buffer_stack.pop() def _cal_freq(long_str): from collections import defaultdict d = defaultdict(int) for c in long_str: d[c] += 1 return d MAX_BITS =
8 class Encoder(object): def __init__(self, filename_or_long_str=None): if filename_or_long_str: if os.pat
h.exists(filename_or_long_str): self.encode(filename_or_long_str) else: #print '[Encoder] take \'%s\' as a string to be encoded.'\ # % filename_or_long_str self.long_str = filename_or_long_str def __get_long_str(self): return self._long_str def __set_long_str(self, s): self._long_str = s if s: self.root = self._get_tree_root() self.code_map = self._get_code_map() self.array_codes, self.code_length = self._encode() long_str = property(__get_long_str, __set_long_str) def _get_tree_root(self): d = _cal_freq(self.long_str) return _build_tree( [HuffmanNode(ch=ch, fq=int(fq)) for ch, fq in d.iteritems()] ) def _get_code_map(self): a_dict={} _gen_huffman_code(self.root, a_dict) return a_dict def _encode(self): array_codes = array.array('B') code_length = 0 buff, length = 0, 0 for ch in self.long_str: code = self.code_map[ch] for bit in list(code): if bit=='1': buff = (buff << 1) | 0x01 else: # bit == '0' buff = (buff << 1) length += 1 if length == MAX_BITS: array_codes.extend([buff]) buff, length = 0, 0 code_length += len(code) if length != 0: array_codes.extend([buff << (MAX_BITS-length)]) return array_codes, code_length def encode(self, filename): fp = open(filename, 'rb') self.long_str = fp.read() fp.close() def write(self, filename): if self._long_str: fcompressed = open(filename, 'wb') marshal.dump( (cPickle.dumps(self.root), self.code_length, self.array_codes), fcompressed) fcompressed.close() else: print "You haven't set 'long_str' attribute." class Decoder(object): def __init__(self, filename_or_raw_str=None): if filename_or_raw_str: if os.path.exists(filename_or_raw_str): filename = filename_or_raw_str self.read(filename) else: print '[Decoder] take \'%s\' as raw string' % filename_or_raw_str raw_string = filename_or_raw_str unpickled_root, length, array_codes = marshal.loads(raw_string) self.root = cPickle.loads(unpickled_root) self.code_length = length self.array_codes = array.array('B', array_codes) def _decode(self): string_buf = [] total_length = 0 node = self.root for code in self.array_codes: buf_length = 0 while (buf_length < MAX_BITS and total_length != self.code_length): buf_length += 1 total_length += 1 if code >> (MAX_BITS - buf_length) & 1: node = node.R if node.c: string_buf.append(node.c) node = self.root else: node = node.L if node.c: string_buf.append(node.c) node = self.root return ''.join(string_buf) def read(self, filename): fp = open(filename, 'rb') unpickled_root, length, array_codes = marshal.load(fp) self.root = cPickle.loads(unpickled_root) self.code_length = length self.array_codes = array.array('B', array_codes) fp.close() def decode_as(self, filename): decoded = self._decode() fout = open(filename, 'wb') fout.write(decoded) fout.close() if __name__=='__main__': original_file = 'filename.txt' compressed_file = 'compressed.scw' decompressed_file = 'filename2.txt' # first way to use Encoder/Decoder enc = Encoder(original_file) enc.write(compressed_file) dec = Decoder(compressed_file) dec.decode_as(decompressed_file) # second way #enc = Encoder() #enc.encode(original_file) #enc.write(compressed_file) #dec = Decoder() #dec.read(compressed_file) #dec.decode_as(decompressed_file)
Jc2k/libcloud
docs/examples/compute/openstack_simple.py
Python
apache-2.0
610
0
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver import libcloud.security # T
his assumes you don't have SSL set up. # Note: Code like this poses a security risk (MITM attack) and # that's the reason why you should never use it for anything else # besides testing. You have been warned. libcloud.security.VERIFY_SSL_CERT = False OpenStack = get_driver(Provider.OPENSTACK) driver = OpenStack('your_auth_username', 'your_auth_password', ex_force_auth_url='http://192.168.1.101:5000/v2.0', ex_
force_auth_version='2.0_password')
catapult-project/catapult
telemetry/telemetry/story/expectations.py
Python
bsd-3-clause
9,428
0.005834
# Copyright 2017 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. from __future__ import absolute_import from telemetry.core import os_version as os_version_module # TODO(rnephew): Since TestConditions are being used for more than # just story expectations now, this should be decoupled and refactored # to be clearer. class _TestCondition(object): def ShouldDisable(self, platform, finder_options): raise NotImplementedError def __str__(self): raise NotImplementedError def GetSupportedPlatformNames(self): """Returns a set of supported platforms' names.""" raise NotImplementedError class _TestConditionByPlatformList(_TestCondition): def __init__(self, platforms, name): self._platforms = platforms self._name = name def ShouldDisable(self, platform, finder_options): del finder_options # Unused. return platform.GetOSName() in self._platforms def __str__(self): return self._name def GetSupportedPlatformNames(self): return set(self._platforms) class _AllTestCondition(_TestCondition): def ShouldDisable(self, platform, finder_options): del platform, finder_options # Unused. return True def __str__(self): return 'All' def GetSupportedPlatformNames(self): return {'all'} class _TestConditionAndroidSvelte(_TestCondition): """Matches android devices with a svelte (low-memory) build.""" def ShouldDisable(self, platform, finder_options): del finder_options # Unused. return platform.GetOSName() == 'android' and platform.IsSvelte() def __str__(self): return 'Android Svelte' def GetSupportedPlatformNames(self): return {'android'} class _TestConditionByAndroidModel(_TestCondition): def __init__(self, model, name=None): self._model = model self._name = name if name else model def ShouldDisable(self, platform, finder_options): return (platform.GetOSName() == 'android' and self._model == platform.GetDeviceTypeName()) def __str__(self): return self._name def GetSupportedPlatformNames(self): return {'android'} class _TestConditionAndroidWebview(_TestCondition): def ShouldDisable(self, platform, finder_options): return (platform.GetOSName() == 'android' and finder_options.browser_type.startswith('android-webview')) def __str__(self): return 'Android Webview' def GetSupportedPlatformNames(self): return {'android'} class _TestConditionAndroidNotWebview(_TestCondition): def ShouldDisable(self, platform, finder_options): return (platform.GetOSName() == 'android' and not finder_options.browser_type.startswith('android-webview')) def __str__(self): return 'Android but not webview' def GetSupportedPlatformNames(self): return {'android'} class _TestConditionByMacVersion(_TestCondition): def __init__(self, version, name=None): self._version = version self._name = name def __str__(self): return self._name def GetSupportedPlatformNames(self): return {'mac'} def ShouldDisable(self, platform, finder_options): if platform.GetOSName() != 'mac': return False return platform.GetOSVersionDetailString().startswith(self._version) class _TestConditionByWinVersion(_TestCondition): def __init__(self, version, name): self._version = version self._name = name def __str__(self): return self._name def GetSupportedPlatformNames(self): return {'win'} def ShouldDisable(self, platform, finder_options): if platform.GetOSName() != 'win': return False return platform.GetOSVersionName() == self._version class _TestConditionFuchsiaWebEngineShell(_TestCondition): def ShouldDisable(self, platform, finder_options): return (platform.GetOSName() == 'fuchsia' and finder_options.browser_type.startswith('web-engine-shell')) def __str__(self): return 'Fuchsia with web-engine-shell' def GetSupportedPlatformNames(self): return {'fuchsia', 'fuchsia-board-astro', 'fuchsia-board-sherlock'} class _TestConditionFuchsiaByBoard(_TestCondition): def __init__(self, board): self._board = 'fuchsia-board-' + b
oard def ShouldDisable(self, platform, finder_options): return (platform.GetOSName() == 'fuchsia' and platform.GetDeviceTypeName() == self._board) def __str__(self): return 'Fuchsia on ' + self._board def GetSupportedPlatformNames(self): return {'fuchsia', 'fuchsia-board-' + self._board} class _TestConditionLogicalA
ndConditions(_TestCondition): def __init__(self, conditions, name): self._conditions = conditions self._name = name def __str__(self): return self._name def GetSupportedPlatformNames(self): platforms = set() for cond in self._conditions: platforms.update(cond.GetSupportedPlatformNames()) return platforms def ShouldDisable(self, platform, finder_options): return all( c.ShouldDisable(platform, finder_options) for c in self._conditions) class _TestConditionLogicalOrConditions(_TestCondition): def __init__(self, conditions, name): self._conditions = conditions self._name = name def __str__(self): return self._name def GetSupportedPlatformNames(self): platforms = set() for cond in self._conditions: platforms.update(cond.GetSupportedPlatformNames()) return platforms def ShouldDisable(self, platform, finder_options): return any( c.ShouldDisable(platform, finder_options) for c in self._conditions) ALL = _AllTestCondition() ALL_MAC = _TestConditionByPlatformList(['mac'], 'Mac') ALL_WIN = _TestConditionByPlatformList(['win'], 'Win') WIN_7 = _TestConditionByWinVersion(os_version_module.WIN7, 'Win 7') WIN_10 = _TestConditionByWinVersion(os_version_module.WIN10, 'Win 10') ALL_LINUX = _TestConditionByPlatformList(['linux'], 'Linux') ALL_CHROMEOS = _TestConditionByPlatformList(['chromeos'], 'ChromeOS') ALL_ANDROID = _TestConditionByPlatformList(['android'], 'Android') # Fuchsia setup, while similar to mobile, renders, Desktop pages. ALL_DESKTOP = _TestConditionByPlatformList( ['mac', 'linux', 'win', 'chromeos', 'fuchsia'], 'Desktop') ALL_MOBILE = _TestConditionByPlatformList(['android'], 'Mobile') ANDROID_NEXUS5 = _TestConditionByAndroidModel('Nexus 5') _ANDROID_NEXUS5X = _TestConditionByAndroidModel('Nexus 5X') _ANDROID_NEXUS5XAOSP = _TestConditionByAndroidModel('AOSP on BullHead') ANDROID_NEXUS5X = _TestConditionLogicalOrConditions( [_ANDROID_NEXUS5X, _ANDROID_NEXUS5XAOSP], 'Nexus 5X') _ANDROID_NEXUS6 = _TestConditionByAndroidModel('Nexus 6') _ANDROID_NEXUS6AOSP = _TestConditionByAndroidModel('AOSP on Shamu') ANDROID_NEXUS6 = _TestConditionLogicalOrConditions( [_ANDROID_NEXUS6, _ANDROID_NEXUS6AOSP], 'Nexus 6') ANDROID_NEXUS6P = _TestConditionByAndroidModel('Nexus 6P') ANDROID_NEXUS7 = _TestConditionByAndroidModel('Nexus 7') ANDROID_GO = _TestConditionByAndroidModel('gobo', 'Android Go') ANDROID_ONE = _TestConditionByAndroidModel('W6210', 'Android One') ANDROID_SVELTE = _TestConditionAndroidSvelte() ANDROID_LOW_END = _TestConditionLogicalOrConditions( [ANDROID_GO, ANDROID_SVELTE, ANDROID_ONE], 'Android Low End') ANDROID_PIXEL2 = _TestConditionByAndroidModel('Pixel 2') ANDROID_WEBVIEW = _TestConditionAndroidWebview() ANDROID_NOT_WEBVIEW = _TestConditionAndroidNotWebview() # MAC_10_11 Includes: # Mac 10.11 Perf, Mac Retina Perf, Mac Pro 10.11 Perf, Mac Air 10.11 Perf MAC_10_11 = _TestConditionByMacVersion('10.11', 'Mac 10.11') # Mac 10_12 Includes: # Mac 10.12 Perf, Mac Mini 8GB 10.12 Perf MAC_10_12 = _TestConditionByMacVersion('10.12', 'Mac 10.12') ANDROID_NEXUS6_WEBVIEW = _TestConditionLogicalAndConditions( [ANDROID_NEXUS6, ANDROID_WEBVIEW], 'Nexus6 Webview') ANDROID_NEXUS5X_WEBVIEW = _TestConditionLogicalAndConditions( [ANDROID_NEXUS5X, ANDROID_WEBVIEW], 'Nexus5X Webview') ANDROID_GO_WEBVIEW = _TestConditionLogicalAndConditions( [ANDROID_GO, ANDROID_WEBVIEW], 'Android Go Webview') ANDROID_PIXEL2_WEBVIEW = _TestConditionLogicalAndConditions( [ANDROID_PIXEL2, ANDROID_WEBVIEW], 'Pixel2 W
andmos/ansible
test/units/modules/storage/netapp/test_na_ontap_lun_copy.py
Python
gpl-3.0
5,814
0.00172
# (c) 2018, NetApp, Inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ''' unit test template for ONTAP Ansible module ''' from __future__ import print_function import json import pytest from units.compat import unittest from units.compat.mock import patch, Mock from ansible.module_utils import basic from ansible.module_utils._text import to_bytes import ansible.module_utils.netapp as netapp_utils from ansible.modules.storage.netapp.na_ontap_lun_copy \ import NetAppOntapLUNCopy as my_module # module under test if not netapp_utils.has_netapp_lib(): pytestmark = pytest.mark.skip('skipping as missing required netapp_lib') def set_module_args(args): """prepare arguments so that they will be picked up during module creation""" args = json.dumps({'ANSIBLE_MODULE_ARGS': args}) basic._ANSIBLE_ARGS = to_bytes(args) # pylint: disable=protected-access class AnsibleExitJson(Exception): """Exception class to be raised by module.exit_json and caught by the test case""" pass class AnsibleFailJson(Exception): """Exception class to be raised by module.fail_json and caught by the test case""" pass def exit_json(*args, **kwargs): # pylint: disable=unused-argument """function to patch over exit_json; package return data into an exception""" if 'changed' not in kwargs: kwargs['changed'] = False raise AnsibleExitJson(kwargs) def fail_json(*args, **kwargs): # pylint: disable=unused-argument """function to patch over fail_json; package return data into an exception""" kwargs['failed'] = True raise AnsibleFailJson(kwargs) class MockONTAPConnection(object): ''' mock server connection to ONTAP host ''' def __init__(self, kind=None, parm1=None): ''' save arguments ''' self.type = kind self.parm1 = parm1 self.xml_in = None self.xml_out = None def invoke_successfully(self, xml, enable_tunneling): # pylint: disable=unused-argument ''' mock invoke_successfully returning xml data ''' self.xml_in = xml if self.type == 'destination_vserver': xml = self.build_lun_info(self.parm1) self.xml_out = xml return xml @staticmethod def build_lun_info(data): ''' build xml data for lun-info ''' xml = netapp_utils.zapi.NaElement('xml') attributes = { 'num-records': 1, } xml.translate_struct(attributes) return xml class TestMyModule(unittest.TestCase): ''' a group of related Unit Tests ''' def setUp(self): self.mock_module_helper = patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json) self.mock_module_helper.start() self.addCleanup(self.mock_module_helper.stop) self.mock_lun_copy = { 'source_vserver': 'ansible', 'destination_path': '/vol/test/test_copy_dest_dest_new_reviewd_new', 'source_path': '/vol/test/test_copy_1', 'destination_vserver': 'ansible', 'state': 'present' } def mock_args(self): return { 'source_vserver': self.mock_lun_copy['source_vserver'], 'destination_path': self.mock_lun_copy['destination_path'], 'source_path': self.mock_lun_copy['source_path'], 'destination_vserver': self.mock_lun_copy['destination_vserver'], 'state': self.mock_lun_copy['state'], 'hostname': 'hostname', 'username': 'username', 'password': 'password', } # self.server = MockONTAPConnection() def get_lun_copy_mock_object(self, kind=None): """ Helper method to return an na_ontap_lun_copy object :param kind: passes this param to MockONTAPConnection() :return: na_ontap_interface object """ lun_copy_obj = my_module() lun_copy_obj.autosupport_log = Mock(return_value=None) if kind is None: lun_copy_obj.server = MockONTAPConnection() else: lun_copy_obj.server = MockONTAPConnection(kind=kind) return lun_copy_obj def test_module_fail_when_required_args_missing(self): ''' required arguments are reported as errors ''' with pytest.raises(AnsibleFailJson) as exc: set_module_args({}) my_module() print('Info: %s' % exc.value.args[0]['msg']) def test_create_error_missing_param(self): ''' Test if create throws an error if required param 'destination_vserver' is not specified''' data = self.mock_args() del data['destination_vserver'] set_module_args(data) with pytest.raises(AnsibleFailJson) as exc: self.get_lun_copy_mock_object('lun_copy').copy_lun() msg = 'Error: Missing one or more required parameters for copying lun: ' \ 'destination_path, source_
path, destination_path' expected = sorted(','.split(msg)) received = sorted(','.split(exc.value.args[0]['msg'])) assert expected == received def test_successful_copy(self): ''' Test successful create ''' # data = self
.mock_args() set_module_args(self.mock_args()) with pytest.raises(AnsibleExitJson) as exc: self.get_lun_copy_mock_object().apply() assert exc.value.args[0]['changed'] def test_copy_idempotency(self): ''' Test create idempotency ''' set_module_args(self.mock_args()) with pytest.raises(AnsibleExitJson) as exc: self.get_lun_copy_mock_object('destination_vserver').apply() assert not exc.value.args[0]['changed']
aronsky/home-assistant
homeassistant/components/uptimerobot/entity.py
Python
apache-2.0
1,942
0.000515
"""Base UptimeRobot entity.""" from __future__ import annotations from pyuptimerobot import UptimeRobotMonitor from homeassistant.helpers.entity import DeviceInfo, EntityDescription from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from .const import ATTR_TARGET, ATTRIBUTION, DOMAIN class UptimeRobotEntity(CoordinatorEntity): """Base UptimeRobot entity.""" _attr_attribution = ATTRIBUTION def __init__( self, coordinator: DataUpdateCoordinator, description: EntityDescription, monitor: UptimeRobotMonitor, ) -> None: """Initialize UptimeRobot entities.""" super().__init__(coordinator) self.entity_description = description self._monitor = monitor self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, str(self.monitor.id))}, name=self.monito
r.friendly_name, manufacturer="UptimeRobot Team", entry_type="service", model=self.monitor.type.name, configuration_url=f"https://uptimerobot.com/dashboard#{self.monitor.id}", ) self._a
ttr_extra_state_attributes = { ATTR_TARGET: self.monitor.url, } self._attr_unique_id = str(self.monitor.id) @property def _monitors(self) -> list[UptimeRobotMonitor]: """Return all monitors.""" return self.coordinator.data or [] @property def monitor(self) -> UptimeRobotMonitor: """Return the monitor for this entity.""" return next( ( monitor for monitor in self._monitors if str(monitor.id) == self.entity_description.key ), self._monitor, ) @property def monitor_available(self) -> bool: """Returtn if the monitor is available.""" return bool(self.monitor.status == 2)
abonaca/gary
gary/util.py
Python
mit
3,607
0.001941
# coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <adrn@astro.columbia.edu>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy
self._hash = None def __getitem__(self,
key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict
jopohl/urh
src/urh/controller/widgets/DeviceSettingsWidget.py
Python
gpl-3.0
24,781
0.00339
from statistics import median import numpy as np from PyQt5.QtCore import QRegExp, pyqtSlot, pyqtSignal from PyQt5.QtGui import QRegExpValidator, QIcon from PyQt5.QtWidgets import QWidget, QSpinBox, QLabel, QComboBox, QSlider from urh import settings from urh.dev import config from urh.dev.BackendHandler import BackendHandler, Backends from urh.dev.VirtualDevice import VirtualDevice from urh.plugins.NetworkSDRInterface.NetworkSDRInterfacePlugin import NetworkSDRInterfacePlugin from urh.plugins.PluginManager import PluginManager from urh.ui.ui_send_recv_device_settings import Ui_FormDeviceSettings from urh.util.ProjectManager import ProjectManager class DeviceSettingsWidget(QWidget): selected_device_changed = pyqtSignal() gain_edited = pyqtSignal() device_parameters_changed = pyqtSignal(dict) def __init__(self, project_manager: ProjectManager, is_tx: bool, backend_handler: BackendHandler = None, continuous_send_mode=False, parent=None): super().__init__(parent) self.ui = Ui_FormDeviceSettings() self.ui.setupUi(self) self.__device = None # type: VirtualDevice self.is_tx = is_tx self.is_rx = not is_tx if backend_handler is None: self.backend_handler = BackendHandler() else: self.backend_handler = backend_handler if self.is_rx: self.ui.spinBoxNRepeat.hide() self.ui.labelNRepeat.hide() else: self.ui.labelDCCorrection.hide() self.ui.checkBoxDCCorrection.hide() self.bw_sr_are_locked = settings.read("lock_bandwidth_sample_rate", True, bool) self.ui.cbDevice.clear() items = self.get_devices_for_combobox(continuous_send_mode) self.ui.cbDevice.addItems(items) self.bootstrap(project_manager.device_conf, enforce_default=True) self.ui.btnLockBWSR.setChecked(self.bw_sr_are_locked) self.on_btn_lock_bw_sr_clicked() ip_range = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])" ip_regex = QRegExp("^" + ip_range + "\\." + ip_range + "\\." + ip_range + "\\." + ip_range + "$") self.ui.lineEditIP.setValidator(QRegExpValidator(ip_regex)) self.create_connects() self.sync_gain_sliders() def bootstrap(self, conf_dict: dict, enforce_default=False): def set_val(ui_widget, key: str, default): try: value = conf_dict[key] except KeyError: value = default if enforce_default else None if value is not None: ui_widget.setValue(value) self.set_bandwidth_status() self.ui.cbDevice.setCurrentText(conf_dict.get("name", "")) dev_name = self.ui.cbDevice.currentText() self.set_device_ui_items_visibility(dev_name, overwrite_settings=True) set_val(self.ui.spinBoxFreq, "frequency", config.DEFAULT_FREQUENCY) set_val(self.ui.spinBoxSampleRate, "sample_rate", config.DEFAULT_SAMPLE_RATE) set_val(self.ui.spinBoxBandwidth, "bandwidth", config.DEFAULT_BANDWIDTH) set_val(self.ui.spinBoxGain, self.rx_tx_prefix + "gain", config.DEFAULT_GAIN) set_val(self.ui.spinBoxIFGain, self.rx_tx_prefix + "if_gain", config.DEFAULT_IF_GAIN) set_val(self.ui.spinBoxBasebandGain, self.rx_tx_prefix + "baseband_gain", config.DEFAULT_BB_GAIN) set_val(self.ui.spinBoxFreqCorrection, "freq_correction", config.DEFAULT_FREQ_CORRECTION) set_val(self.ui.spinBoxNRepeat, "num_sending_repeats", settings.read('num_sending_repeats', 1, type=int)) self.ui.lineEditSubdevice.setText(conf_dict.get("subdevice", "")) if self.rx_tx_prefix + "antenna_index" in conf_dict: self.ui.comboBoxAntenna.setCurrentIndex(conf_dict[self.rx_tx_prefix + "antenna_index"]) if self.rx_tx_prefix + "gain" not in conf_dict: self.set_default_rf_gain() if self.rx_tx_prefix + "if_gain" not in conf_dict: self.set_default_if_gain() if self.rx_tx_prefix + "baseband_gain" not in conf_dict: self.set_default_bb_gain() if self.is_rx: checked = conf_dict.get("apply_dc_correction", True) if isinstance(checked, str): checked = True if checked == "True" else False self.ui.checkBoxDCCorrection.setChecked(checked) checked = conf_dict.get("bias_tee_enabled", False) if isinstance(checked, str): checked = True if checked == "True" else False self.ui.checkBoxBiasTee.setChecked(checked) self.emit_editing_finished_signals() @property def device(self) -> VirtualDevice: return self.__device @device.setter def device(self, value: VirtualDevice): self.__device = value @property def rx_tx_prefix(self) -> str: return "rx_" if self.is_rx else "tx_" @property def selected_device_conf(self) -> dict: device_name = self.ui.cbDevice.currentText() key = device_name if device_name in config.DEVICE_CONFIG.keys() else "Fallback" return config.DEVICE_CONFIG[key] def create_connects(self): self.ui.spinBoxFreq.editingFinished.connect(self.on_spinbox_frequency_editing_finished) self.ui.spinBoxSampleRate.editingFinished.connect(self.on_spinbox_sample_rate_editing_finished) self.ui.spinBoxGain.editingFinished.connect(self.on_spinbox_gain_editing_finished) self.ui.spinBoxGain.valueChanged.connect(self.on_spinbox_gain_value_changed) self.ui.sliderGain.valueChanged.connect(self.on_slider_gain_value_changed) self.ui.spinBoxIFGain.editingFinished.connect(self.on_spinbox_if_gain_editing_finished) self.ui.spinBoxIFGain.valueChanged.connect(self.on_spinbox_if_gain_value_changed) self.ui.sliderIFGain.valueChanged.connect(self.on_slider_if_gain_value_changed) self.ui.spinBoxBasebandGain.editingFinished.connect(self.on_spinbox_baseband_gain_editing_finished) self.ui.spinBoxBasebandGain.valueChanged.connect(self.on_spinbox_baseband_gain_value_changed) self.ui.sliderBasebandGain.valueChanged.connect(self.on_slider_baseband_gain_value_changed) self.ui.spinBoxBandwidth.editingFinished.connect(self.on_spinbox_bandwidth_editing_finished) self.ui.spinBoxPort.editingFinished.connect(self.on_spinbox_port_editing_finished) self.ui.lineEditIP.editingFinished.connect(self.on_line_edit_ip_editing_finished) self.ui.lineEditSubdevice.editingFinished.connect(self.on_line_edit_subdevice_editing_finished) self.ui.comboBoxAntenna.currentIndexChanged.connect(self.on_combobox_antenna_current_index_changed) self.ui.comboBoxChannel.currentIndexChanged.connect(self.on_combobox_channel_current_index_changed) self.ui.spinBoxFreqCorrection.editingFinished.connect(self.on_spinbox_freq_correction_editing_finished) self.ui.comboBoxDirectSampling.currentIndexChanged.connect(self.on_combobox_direct_sampling_index_changed) self.ui.cbDevice.currentIndexChanged.connect(self.on_cb_device_current_index_changed) self.ui.spinBoxNRepeat.editingFinished.connect(self.on_num_repeats_changed) self.ui.btnLockBWSR.clicked.connect(self.on_btn_lock_bw_sr_clicked) self.ui.btnRefreshDeviceIdentifier.clicked.connect(self.on_btn_refresh_device_identifier_clicked) self.ui.comboBoxDeviceIdentifier.currentIndexChanged.connect( self.on_combo_box_device_identifier_current_index_changed) self.ui.comboBoxDeviceIdentifier.editTextChanged.connect(self.on_combo_box_device_identifier_edit_text_changed) self.ui.checkBoxBiasTee.clicked.connect(self.on_check_box_bias_tee_clicked) self.ui.checkBoxDCCorrection.clicked.connect(
self.on_check_box_dc_correction_clicked) def set_gain_defaults(self): self.set_default_rf_gain() self.set_default_if_gain() self.set
_default_bb_gain() def set_default_rf_gain(self): conf = self.selected_device_conf pre
gkc1000/pyscf
pyscf/shciscf/examples/03_c2_diffsymm.py
Python
apache-2.0
1,773
0.002256
#!/usr/bin/env python
# Copyright 2014-2019 The PySCF Developers. 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. # # Authors: Sandeep Sharma <sanshar@gmail.com> # James Smith <james.smith9113@gmail.com> # """ All output is deleted after the run to keep the directory neat. Comment out the cleanup section to view output. """ import time import numpy import math import os from pyscf import gto, scf, ao2mo, mcscf, tools, fci from pyscf.shciscf import shci, settings t0 = time.time() alpha = 0.007297351 mol = gto.M( atom="C 0 0 0; C 0 0 1.3119", basis="cc-pvqz", verbose=5, symmetry=1, spin=2 ) myhf = scf.RHF(mol) myhf.kernel() ##USE SHCISCF solver1 = shci.SHCI(mol) solver1.irrep_nelec = {"A1g": (2, 1), "A1u": (1, 1), "E1ux": (1, 1), "E1uy": (1, 0)} solver1.prefix = "solver1" solver1.epsilon2 = 1.0e-7 solver1.stochastic = False solver2 = shci.SHCI(mol) solver2.irrep_nelec = {"A1g": (2, 1), "A1u": (1, 1), "E1ux": (1, 0), "E1uy": (1, 1)} solver2.prefix = "solver2" solver2.epsilon2 = 1.0e-7 solver2.stochastic = False mycas = shci.SHCISCF(myhf, 8, 8) mcscf.state_average_mix_(mycas, [solver1, solver2], numpy.ones(2) / 2) mycas.kernel() print("Total Time: ", time.time() - t0) # File cleanup solver1.cleanup_dice_files()
geimer/easybuild-framework
test/framework/toy_build.py
Python
gpl-2.0
33,739
0.004742
# # # Copyright 2013-2014 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (http://www.herculesstichting.be/in_English) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # http://github.com/hpcugent/easybuild # # EasyBuild 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 v2. # # EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. # # """ Toy build unit test @author: Kenneth Hoste (Ghent University) """ import glob import grp import os import re import shutil import stat import sys import tempfile from test.framework.utilities import EnhancedTestCase from unittest import TestLoader from unittest import main as unittestmain from vsc.utils.fancylogger import setLogLevelDebug, logToScreen import easybuild.tools.module_naming_scheme # required to dynamically load test module naming scheme(s) from easybuild.framework.easyconfig.easyconfig import EasyConfig from easybuild.tools.build_log import EasyBuildError from easybuild.tools.filetools import mkdir, read_file, write_file from easybuild.tools.modules import modules_tool class ToyBuildTest(EnhancedTestCase): """Toy build unit test.""" def setUp(self): """Test setup.""" super(ToyBuildTest, self).setUp() fd, self.dummylogfn = tempfile.mkstemp(prefix='easybuild-dummy', suffix='.log') os.close(fd) # adjust PYTHONPATH such that test easyblocks are found import easybuild eb_blocks_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'sandbox')) if not eb_blocks_path in sys.path: sys.path.append(eb_blocks_path) easybuild = reload(easybuild) import easybuild.easyblocks reload(easybuild.easyblocks) reload(easybuild.tools.module_naming_scheme) # clear log write_file(self.logfile, '') def tearDown(self): """Cleanup.""" super(ToyBuildTest, self).tearDown() # remove logs if os.path.exists(self.dummylogfn): os.remove(self.dummylogfn) def check_toy(self, installpath, outtxt, version='0.0', versionprefix='', versionsuffix=''): """Check whether toy build succeeded.""" full_version = ''.join([versionprefix, version, versionsuffix]) # check for success success = re.compile("COMPLETED: Installation ended successfully") self.asse
rtTrue(success.search(outtxt), "COMPLETED message found in '%s" % outtxt) # if the module exists, it should be fine toy
_module = os.path.join(installpath, 'modules', 'all', 'toy', full_version) msg = "module for toy build toy/%s found (path %s)" % (full_version, toy_module) self.assertTrue(os.path.exists(toy_module), msg) # module file is symlinked according to moduleclass toy_module_symlink = os.path.join(installpath, 'modules', 'tools', 'toy', full_version) self.assertTrue(os.path.islink(toy_module_symlink)) self.assertTrue(os.path.exists(toy_module_symlink)) # make sure installation log file and easyconfig file are copied to install dir software_path = os.path.join(installpath, 'software', 'toy', full_version) install_log_path_pattern = os.path.join(software_path, 'easybuild', 'easybuild-toy-%s*.log' % version) self.assertTrue(len(glob.glob(install_log_path_pattern)) == 1, "Found 1 file at %s" % install_log_path_pattern) # make sure test report is available test_report_path_pattern = os.path.join(software_path, 'easybuild', 'easybuild-toy-%s*test_report.md' % version) self.assertTrue(len(glob.glob(test_report_path_pattern)) == 1, "Found 1 file at %s" % test_report_path_pattern) ec_file_path = os.path.join(software_path, 'easybuild', 'toy-%s.eb' % full_version) self.assertTrue(os.path.exists(ec_file_path)) devel_module_path = os.path.join(software_path, 'easybuild', 'toy-%s-easybuild-devel' % full_version) self.assertTrue(os.path.exists(devel_module_path)) def test_toy_build(self, extra_args=None, ec_file=None, tmpdir=None, verify=True, fails=False, verbose=True, raise_error=False, test_report=None, versionsuffix=''): """Perform a toy build.""" if extra_args is None: extra_args = [] test_readme = False if ec_file is None: ec_file = os.path.join(os.path.dirname(__file__), 'easyconfigs', 'toy-0.0.eb') test_readme = True full_ver = '0.0%s' % versionsuffix args = [ ec_file, '--sourcepath=%s' % self.test_sourcepath, '--buildpath=%s' % self.test_buildpath, '--installpath=%s' % self.test_installpath, '--debug', '--unittest-file=%s' % self.logfile, '--force', '--robot=%s' % os.pathsep.join([self.test_buildpath, os.path.dirname(__file__)]), ] if tmpdir is not None: args.append('--tmpdir=%s' % tmpdir) if test_report is not None: args.append('--dump-test-report=%s' % test_report) args.extend(extra_args) myerr = None try: outtxt = self.eb_main(args, logfile=self.dummylogfn, do_build=True, verbose=verbose, raise_error=raise_error) except Exception, err: myerr = err if raise_error: raise myerr if verify: self.check_toy(self.test_installpath, outtxt, versionsuffix=versionsuffix) if test_readme: # make sure postinstallcmds were used toy_install_path = os.path.join(self.test_installpath, 'software', 'toy', full_ver) self.assertEqual(read_file(os.path.join(toy_install_path, 'README')), "TOY\n") # make sure full test report was dumped, and contains sensible information if test_report is not None: self.assertTrue(os.path.exists(test_report)) if fails: test_result = 'FAIL' else: test_result = 'SUCCESS' regex_patterns = [ r"Test result[\S\s]*Build succeeded for %d out of 1" % (not fails), r"Overview of tested easyconfig[\S\s]*%s[\S\s]*%s" % (test_result, os.path.basename(ec_file)), r"Time info[\S\s]*start:[\S\s]*end:", r"EasyBuild info[\S\s]*framework version:[\S\s]*easyblocks ver[\S\s]*command line[\S\s]*configuration", r"System info[\S\s]*cpu model[\S\s]*os name[\S\s]*os version[\S\s]*python version", r"List of loaded modules", r"Environment", ] test_report_txt = read_file(test_report) for regex_pattern in regex_patterns: regex = re.compile(regex_pattern, re.M) msg = "Pattern %s found in full test report: %s" % (regex.pattern, test_report_txt) self.assertTrue(regex.search(test_report_txt), msg) return outtxt def test_toy_broken(self): """Test deliberately broken toy build.""" tmpdir = tempfile.mkdtemp() broken_toy_ec = os.path.join(tmpdir, "toy-broken.eb") toy_ec_file = os.path.join(os.path.dirname(__file__), 'easyconfigs', 'toy-0.0.eb') broken_toy_ec_txt = read_file(toy_ec_file) broken_toy_ec_txt += "checksums = ['clearywrongchecksum']" write_file(broken_toy_ec, broken_toy_ec_txt) erro
repotvsupertuga/repo
script.module.stream.tvsupertuga.addon/resources/lib/indexers/episodes.py
Python
gpl-2.0
65,914
0.011909
# -*- coding: utf-8 -*- ''' flixnet Add-on Copyright (C) 2016 flixnet This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later 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 resources.lib.modules import trakt from resources.lib.modules import cleantitle from resources.lib.modules import cleangenre from resources.lib.modules import control from resources.lib.modules import client from resources.lib.modules import cache from resources.lib.modules import playcount from resources.lib.modules import workers from resources.lib.modules import views from resources.lib.modules import utils import os,sys,re,json,zipfile,StringIO,urllib,urllib2,urlparse,datetime params = dict(urlparse.parse_qsl(sys.argv[2].replace('?',''))) if len(sys.argv) > 1 else dict() action = params.get('action') class seasons: def __init__(self): self.list = [] self.lang = control.apiLanguage()['tvdb'] self.datetime = (datetime.datetime.utcnow() - datetime.timedelta(hours = 5)) self.today_date = (self.datetime).strftime('%Y-%m-%d') self.tvdb_key = 'MUQ2MkYyRjkwMDMwQzQ0NA==' self.tvdb_info_link = 'http://thetvdb.com/api/%s/series/%s/all/%s.zip' % (self.tvdb_key.decode('base64'), '%s', '%s') self.tvdb_by_imdb = 'http://thetvdb.com/api/GetSeriesByRemoteID.php?imdbid=%s' self.tvdb_by_query = 'http://thetvdb.com/api/GetSeries.php?seriesname=%s' self.tvdb_image = 'http://thetvdb.com/banners/' self.tvdb_poster = 'http://thetvdb.com/banners/_cache/' def get(self, tvshowtitle, year, imdb, tvdb, idx=True, create_directory=True): if control.window.getProperty('PseudoTVRunning') == 'True': return episodes().get(tvshowtitle, year, imdb, tvdb) if idx == True: self.list = cache.get(self.tvdb_list, 24, tvshowtitle, year, imdb, tvdb, self.lang) if create_directory == True: self.seasonDirectory(self.list) return self.list else: self.list = self.tvdb_list(tvshowtitle, year, imdb, tvdb, 'en') return self.list def tvdb_list(self, tvshowtitle, year, imdb, tvdb, lang, limit=''): try: if imdb == '0': try: imdb = trakt.SearchTVShow(tvshowtitle, year, full=False)[0] imdb = imdb.get('show', '0') imdb = imdb.get('ids', {}).get('imdb', '0') imdb = 'tt' + re.sub('[^0-9]', '', str(imdb)) if not imdb: imdb = '0' except: imdb = '0' if tvdb == '0' and not imdb == '0': url = self.tvdb_by_imdb % imdb result = client.request(url, timeout='10') try: tvdb = client.parseDOM(result, 'seriesid')[0] except: tvdb = '0' try: name = client.parseDOM(result, 'SeriesName')[0] except: name = '0' dupe = re.compile('[***]Duplicate (\d*)[***]').findall(name) if len(dupe) > 0: tvdb = str(dupe[0]) if tvdb == '': tvdb = '0' if tvdb == '0': url = self.tvdb_by_query % (urllib.quote_plus(tvshowtitle)) years = [str(year), str(int(year)+1), str(int(year)-1)] tvdb = client.request(url, timeout='10') tvdb = re.sub(r'[^\x00-\x7F]+', '', tvdb) tvdb = client.replaceHTMLCodes(tvdb) tvdb = client.parseDOM(tvdb, 'Series') tvdb = [(x, client.parseDOM(x, 'SeriesName'), client.parseDOM(x, 'FirstAired')) for x in tvdb] tvdb = [(x, x[1][0], x[2][0]) for x in tvdb if len(x[1]) > 0 and len(x[2]) > 0] tvdb = [x for x in tvdb if cleantitle.get(tvshowtitle) == cleantitle.get(x[1])] tvdb = [x[0][0] for x in tvdb if any(y in x[2] for y in years)][0] tvdb = client.parseDOM(tvdb, 'seriesid')[0] if tvdb == '': tvdb = '0' except: return try: if tvdb == '0': return url = self.tvdb_info_link % (tvdb, 'en') data = urllib2.urlopen(url, timeout=30).read() zip = zipfile.ZipFile(StringIO.StringIO(data)) result = zip.read('%s.xml' % 'en') artwork = zip.read('banners.xml') zip.close() dupe = client.parseDOM(result, 'SeriesName')[0] dupe = re.compile('[***]Duplicate (\d*)[***]').findall(dupe) if len(dupe) > 0: tvdb = str(dupe[0]).encode('utf-8') url = self.tvdb_info_link % (tvdb, 'en') data = urllib2.urlopen(url, timeout=30).read() zip = zipfile.ZipFile(StringIO.StringIO(data)) result = zip.read('%s.xml' % 'en') artwork = zip.read('banners.xml') zip.close() if not lang == 'en': url = self.tvdb_info_link % (tvdb, lang) data = urllib2.urlopen(url, timeout=30).read() zip = zipfile.ZipFile(StringIO.StringIO(data)) result2 = zip.read('%s.xml' % lang) zip.close() else: result2 = result artwork = artwork.split('<Banner>') artwork = [i for i in artwork if '<Language>en</Language>' in i and '<BannerType>season</BannerType>' in i] artwork = [i for i in artwork if not 'seasonswide' in re.findall('<BannerPath>(.+?)</BannerPath>', i)[0]] result = result.split('<Episode>') result2 = result2.split('<Episode>') item = result[0] ; item2 = result2[0] episodes = [i for i in result if '<EpisodeNumber>' in i] episodes = [i for i in episodes if not '<SeasonNumber>0</SeasonNumber>' in i] episodes = [i for i in episodes if not '<EpisodeNumber>0</EpisodeNumber>' in i] seasons = [i for i in episodes if '<EpisodeNumber>1</EpisodeNumber>' in i] locals = [i for i in result2 if '<EpisodeNumber>' in i] result = '' ; result2 = '' if limit == '': episodes = [] elif limit == '-1': seasons = [] else: episodes = [i for i in episodes if '<SeasonNumber>%01d</SeasonNumber>' % int(limit) in i] seasons = [] try: poster = client.parseDOM(item, 'poster')[0] except: poster = '' if not poster == '': poster = self.tvdb_image + poster else: poster = '0' poster = client.replaceHTMLCodes(poster) poster = poster.encode('utf-8') try: banner = client.parseDOM(item, 'banner')[0] except: banner = '' if not banner == '': banner = self.tvdb_image + banner else: banner = '0' banner = client.replaceHTMLCodes(banner) banner = banner.encode('utf-8') try: fanart = client.parseDOM(item, '
fanart')[0]
except: fanart = '' if not fanart == '': fanart = self.tvdb_image + fanart else: fanart = '0' fanart = client.replaceHTMLCodes(fanart) fanart = fanart.encode('utf-8') if not poster == '0': pass elif not fanart == '0': poster = fanart elif not banner == '0': poster = banner if not banner == '0': pass elif not fanart == '0': banner = fanart elif not poster == '0': banner = poster try: status = client.p
Erethon/synnefo
snf-astakos-app/astakos/im/views/target/redirect.py
Python
gpl-3.0
4,711
0
# Copyright (C) 2010-2014 GRNET S.A. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later 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 django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ from django.utils.http import urlencode from django.contrib.auth import authenticate from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseForbidden) from django.core.exceptions import ValidationError from django.views.decorators.http import require_http_methods from urlparse import urlunsplit, urlsplit, parse_qsl from astakos.im.util import restrict_next from astakos.im.user_utils import login as auth_login, logout from astakos.im.views.decorators import cookie_fix import astakos.im.messages as astakos_messages from astakos.im.settings import REDIRECT_ALLOWED_SCHEMES import logging logger = logging.getLogger(__name__) @require_http_methods(["GET"]) @cookie_fix def login(request): """ If there is no ``next`` request parameter redirects to astakos index page displaying an error message. If the request user is authenticated and has signed the approval terms, redirects to `next` request parameter. If not, redirects to approval terms in order to return back here after agreeing with the terms. Otherwise, redirects to login in order to return back here after successful login. """ next = request.GET.get('next') if not next: return HttpResponseBadRequest('Missing next parameter') if not restrict_next(next, allowed_schemes=REDIRECT_ALLOWED_SCHEMES): return HttpResponseForbidden(_( astakos_messages.NOT_ALLOWED_NEXT_PARAM)) force = request.GET.get('force', None) response = HttpResponse() if force == '' and request.user.is_authenticated(): logout(request) if request.user.is_authenticated(): # if user has not signed the approval terms # redirect to approval terms with next the request path if not request.user.signed_terms: # first build next parameter parts = list(urlsplit(request.build_absolute_uri())) params = dict(parse_qsl(parts[3], keep_blank_values=True)) parts[3] = urlencode(params) next = urlunsplit(parts) # build url location parts[2] = reverse('latest_terms') params = {'next': next} parts[3] = urlencode(params) url = urlunsplit(parts) response['Location'] = url response.status_code = 302 return response renew = request.GET.get('renew', None) if renew == '': request.user.renew_token( flush_sessions=True, current_key=request.session.session_key ) try: request.user.save() except ValidationError, e: return HttpResponseBadRequest(e) # authenticate before login user = authenticate( username=request.user.username, auth_token=request.user.auth_token ) auth_login(request, user) logger.info('Token reset for %s' % user.username)
parts = list(urlsplit(next)) parts[3] = urlencode({ 'uuid': request.user.uuid, 'token': request.user.auth_token }) url = urlunsplit(parts) response['Location'] = url response.status_code = 302 return response else: # redirect to login with next the request path # first build next parameter parts = list(urlsplit(request.build_absolute_uri())) params = dic
t(parse_qsl(parts[3], keep_blank_values=True)) # delete force parameter if 'force' in params: del params['force'] parts[3] = urlencode(params) next = urlunsplit(parts) # build url location parts[2] = reverse('login') params = {'next': next} parts[3] = urlencode(params) url = urlunsplit(parts) response['Location'] = url response.status_code = 302 return response
seanfisk/ecs
ecs/managers.py
Python
mit
8,344
0
"""Entity and System Managers.""" import six from ecs.exceptions import ( NonexistentComponentTypeForEntity, DuplicateSystemTypeError, SystemAlreadyAddedToManagerError) from ecs.models import Entity class EntityManager(object): """Provide database-like access to components based on an entity key.""" def __init__(self): self._database = {} self._next_guid = 0 @property def database(self): """Get this manager's database. Direct modification is not permitted. :return: the database :rtype: :class:`dict` """ return self._database def create_entity(self): """Return a new entity instance with the current lowest GUID value. Does not store a reference to it, and does not make any entries in the database referencing it. :return: the new entity :rtype: :class:`ecs.models.Entity` """ entity = Entity(self._next_guid) self._next_guid += 1 return entity def add_component(self, entity, component_instance): """Add a component to the database and associate it with the given entity. :param entity: entity to associate :type entity: :class:`ecs.models.Entity` :param component_instance: component to add to the entity :type component_instance: :class:`ecs.models.Component` """ component_type = type(component_instance) if component_type not in self._database: self._database[component_type] = {} self._database[component_type][entity] = component_instance def remove_component(self, entity, component_type): """Remove the component of ``component_type`` associated with entity from the database. Doesn't do any kind of data-teardown. It is up to the system calling this code to do that. In the future, a callback system may be used to implement type-specific destructors. :param entity: entity to associate :type entity: :class:`ecs.models.Entity` :param component_type: component type to remove from the entity :type component_type: :class:`type` which is :class:`Component` subclass """ try: del self._database[component_type][entity] if self._database[component_type] == {}: del self._database[component_type] except KeyError: pass def pairs_for_type(self, component_type): """Return an iterator over ``(entity, component_instance)`` tuples for all entities in the database possessing a component of ``component_type``. Return an empty iterator if there are no components of this type in the database. It should be used in a loop like this, where ``Renderable`` is a component type: .. code-block:: python for ent
ity, renderable_component in \ entity_manager.pairs_for_type(Renderable): pass # do something :param component_type: a type of created component :type component_type: :clas
s:`type` which is :class:`Component` subclass :return: iterator on ``(entity, component_instance)`` tuples :rtype: :class:`iter` on (:class:`ecs.models.Entity`, :class:`ecs.models.Component`) """ try: return six.iteritems(self._database[component_type]) except KeyError: return six.iteritems({}) def component_for_entity(self, entity, component_type): """Return the instance of ``component_type`` for the entity from the database. :param entity: associated entity :type entity: :class:`ecs.models.Entity` :param component_type: a type of created component :type component_type: :class:`type` which is :class:`Component` subclass :return: component instance :rtype: :class:`ecs.models.Component` :raises: :exc:`NonexistentComponentTypeForEntity` when ``component_type`` does not exist on the given entity """ try: return self._database[component_type][entity] except KeyError: raise NonexistentComponentTypeForEntity( entity, component_type) def remove_entity(self, entity): """Remove all components from the database that are associated with the entity, with the side-effect that the entity is also no longer in the database. :param entity: entity to remove :type entity: :class:`ecs.models.Entity` """ # For Python 2, don't use iterkeys(), otherwise we will get a # RuntimeError about mutating the length of the dictionary at runtime. # For Python 3, we can't even use keys(), because that is a view object # that acts like iterkeys(). We therefore make a copy using list() to # avoid modifying the iterator. for comp_type in list(self._database.keys()): try: del self._database[comp_type][entity] if self._database[comp_type] == {}: del self._database[comp_type] except KeyError: pass class SystemManager(object): """A container and manager for :class:`ecs.models.System` objects.""" def __init__(self, entity_manager): """:param entity_manager: this manager's entity manager :type entity_manager: :class:`SystemManager` """ self._systems = [] self._system_types = {} self._entity_manager = entity_manager # Allow getting the list of systems but not directly setting it. @property def systems(self): """Get this manager's list of systems. :return: system list :rtype: :class:`list` of :class:`ecs.models.System` """ return self._systems def add_system(self, system_instance, priority=0): """Add a :class:`ecs.models.System` instance to the manager. :param system_instance: instance of a system :param priority: non-negative integer (default: 0) :type system_instance: :class:`ecs.models.System` :type priority: :class:`int` :raises: :class:`ecs.exceptions.DuplicateSystemTypeError` when the system type is already present in this manager :raises: :class:`ecs.exceptions.SystemAlreadyAddedToManagerError` when the system already belongs to a system manager """ system_type = type(system_instance) if system_type in self._system_types: raise DuplicateSystemTypeError(system_type) if system_instance.system_manager is not None: raise SystemAlreadyAddedToManagerError( system_instance, self, system_instance.system_manager) system_instance.entity_manager = self._entity_manager system_instance.system_manager = self self._system_types[system_type] = system_instance self._systems.append(system_instance) system_instance.priority = priority self._systems.sort(key=lambda x: x.priority) def remove_system(self, system_type): """Tell the manager to no longer run the system of this type. :param system_type: type of system to remove :type system_type: :class:`type` """ system = self._system_types[system_type] system.entity_manager = None system.system_manager = None self._systems.remove(system) del self._system_types[system_type] def update(self, dt): """Run each system's ``update()`` method for this frame. The systems are run in the order in which they were added. :param dt: delta time, or elapsed time for this frame :type dt: :class:`float` """ # Iterating over a list of systems instead of values in a dictionary is # noticeably faster. We maintain a list in addition to a dictionary # specifically for this purpose. # # Though initially we had the entity manager being passed through to # each update() method, this turns
Hearen/OnceServer
Server/Eve/post.py
Python
mit
12,002
0.000167
# -*- coding: utf-8 -*- """ eve.methods.post ~~~~~~~~~~~~~~~~ This module imlements the POST method, supported by the resources endopints. :copyright: (c) 2015 by Nicola Iarocci. :license: BSD, see LICENSE for more details. """ from datetime import datetime from flask import current_app as app, abort from eve.utils import config, parse_request, debug_error_message from eve.auth import requires_auth from eve.defaults import resolve_default_values from eve.validation import ValidationError from eve.methods.common import parse, payload, ratelimit, \ pre_event, store_media_files, resolve_user_restricted_access, \ resolve_embedded_fields, build_response_document, marshal_write_response, \ resolve_sub_resource_path, resolve_document_etag, oplog_push from eve.versioning import resolve_document_version, \ insert_versioning_documents @ratelimit() @requires_auth('resource') @pre_event def post(resource, payl=None): """ Default function for handling POST requests, it has decorators for rate limiting, authentication and for raising pre-request events. After the decorators are applied forwards to call to :func:`post_internal` .. versionchanged:: 0.5 Split original post() into post/post_internal combo. """ return post_internal(resource, payl, skip_validation=False) def post_internal(resource, payl=None, skip_validation=False): """ Intended for internal post calls, this method is not rate limited, authentication is not checked and pre-request events are not raised. Adds one or more documents to a resource. Each document is validated against the domain schema. If validation passes the document is inserted and ID_FIELD, LAST_UPDATED and DATE_CREATED along with a link to the document are returned. If validation fails, a list of validation issues is returned. :param resource: name of the resource involved. :param payl: alternative payload. When calling post() from your own code you can provide an alternative payload. This can be useful, for example, when you have a callback function hooked to a certain endpoint, and want to perform additional post() calls from there. Please be advised that in order to successfully use this option, a request context must be available. See https://github.com/nicolaiarocci/eve/issues/74 for a discussion, and a typical use case. :param skip_validation: skip payload validation before write (bool) .. versionchanged:: 0.6 Fix: since v0.6, skip_validation = True causes a 422 response (#726). .. versionchanged:: 0.6 Initialize DELETED field when soft_delete is enabled. .. versionchanged:: 0.5 Back to resolving default values after validaton as now the validator can properly validate dependency even when some have default values. See #353. Push updates to the OpLog. Original post() has been split into post() and post_internal(). ETAGS are now stored with documents (#369). .. versionchanged:: 0.4 Resolve default values before validation is performed. See #353. Support for document versioning. .. versionchanged:: 0.3 Return 201 if at least one document has been successfully inserted. Fix #231 auth field not set if resource level authentication is set. Support for media fields. When IF_MATCH is disabled, no etag is included in the payloa
d. Support for new validation format introduced with Cerberus v0.5. .. versionchanged:: 0.2 Use the new STATUS setting. Use the new ISSUES setting. Raise '
on_pre_<method>' event. Explictly resolve default values instead of letting them be resolved by common.parse. This avoids a validation error when a read-only field also has a default value. Added ``on_inserted*`` events after the database insert .. versionchanged:: 0.1.1 auth.request_auth_value is now used to store the auth_field value. .. versionchanged:: 0.1.0 More robust handling of auth_field. Support for optional HATEOAS. .. versionchanged: 0.0.9 Event hooks renamed to be more robuts and consistent: 'on_posting' renamed to 'on_insert'. You can now pass a pre-defined custom payload to the funcion. .. versionchanged:: 0.0.9 Storing self.app.auth.userid in auth_field when 'user-restricted resource access' is enabled. .. versionchanged: 0.0.7 Support for Rate-Limiting. Support for 'extra_response_fields'. 'on_posting' and 'on_posting_<resource>' events are raised before the documents are inserted into the database. This allows callback functions to arbitrarily edit/update the documents being stored. .. versionchanged:: 0.0.6 Support for bulk inserts. Please note: validation constraints are checked against the database, and not between the payload documents themselves. This causes an interesting corner case: in the event of a multiple documents payload where two or more documents carry the same value for a field where the 'unique' constraint is set, the payload will validate successfully, as there are no duplicates in the database (yet). If this is an issue, the client can always send the documents once at a time for insertion, or validate locally before submitting the payload to the API. .. versionchanged:: 0.0.5 Support for 'application/json' Content-Type . Support for 'user-restricted resource access'. .. versionchanged:: 0.0.4 Added the ``requires_auth`` decorator. .. versionchanged:: 0.0.3 JSON links. Superflous ``response`` container removed. """ date_utc = datetime.utcnow().replace(microsecond=0) resource_def = app.config['DOMAIN'][resource] schema = resource_def['schema'] validator = None if skip_validation else app.validator(schema, resource) documents = [] results = [] failures = 0 if config.BANDWIDTH_SAVER is True: embedded_fields = [] else: req = parse_request(resource) embedded_fields = resolve_embedded_fields(resource, req) # validation, and additional fields if payl is None: payl = payload() # print "\n\ninside eve post\n\n***************************************" # print embedded_fields # print "payl " # print payl ''' Added by : LHearen E-mail : LHearen@126.com Description: Used to construct our own RESTful interfaces - but the extra items should not be stored in DB; ''' if "_id" in payl: payl["_id"] = '27167fe7-fc9d-47d5-9cd0-717106ef67be' if "Module" in payl: del payl["Module"] if "Method" in payl: del payl["Method"] # print "payl " # print payl # print "resource " # print resource # print "\n\nend here" if isinstance(payl, dict): payl = [payl] if not payl: # empty bulkd insert abort(400, description=debug_error_message( 'Empty bulk insert' )) if len(payl) > 1 and not config.DOMAIN[resource]['bulk_enabled']: abort(400, description=debug_error_message( 'Bulk insert not allowed' )) for value in payl: document = [] doc_issues = {} try: document = parse(value, resource) resolve_sub_resource_path(document, resource) if skip_validation: validation = True else: validation = validator.validate(document) if validation: # validation is successful # validator might be not available if skip_validation. #726. if validator: # Apply coerced values document = validator.document # Populate meta and default fields document[config.LAST_UPDATED] = \ do
hzlf/openbroadcast
website/apps/invitation/views.py
Python
gpl-3.0
7,841
0.000893
from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.template import RequestContext from django.shortcuts import render_to_response from django.utils.translation import ugettext from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required from models import InvitationError, Invitation, InvitationStats from forms import InvitationForm, RegistrationFormInvitation from registration.signals import user_registered def apply_extra_context(context, extra_context=None): if extra_context is None: extra_context = {} for key, value in extra_context.items(): context[key] = callable(value) and value() or value return context @login_required def invite(request, success_url=None, form_class=InvitationForm, template_name='invitation/invitation_form.html', extra_context=None): """ Create an invitation and send invitation email. Send invitation email and then redirect to success URL if the invitation form is valid. Redirect named URL ``invitation_unavailable`` on InvitationError. Render invitation form template otherwise. **Required arguments:** None. **Optional arguments:** :success_url: The URL to redirect to on successful registration. Default value is ``None``, ``invitation_complete`` will be resolved in this case. :form_class: A form class to use for invitation. Takes ``request.user`` as first argument to its constructor. Must have an ``email`` field. Custom validation can be implemented here. :template_name: A custom template to use. Default value is ``invitation/invitation_form.html``. :extra_context: A dictionary of variables to add to the template context. Any callable object in this dictionary will be called to produce the end result which appears in the context. **Template:** ``invitation/invitation_form.html`` or ``template_name`` keyword argument. **Context:** A ``RequestContext`` instance is used rendering the template. Context, in addition to ``extra_context``, contains: :form: The invitation form. """ if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): try: invitation = Invitation.objects.invite( request.user, form.cleaned_data["email"], form.cleaned_data["message"]) except InvitationError, e: print '****' print e print '****' return HttpResponseRedirect(reverse('invitation_unavailable')) invitation.send_email(request=request) if 'next' in request.REQUEST: return HttpResponseRedirect(request.REQUEST['next']) return HttpResponseRedirect(success_url or reverse('
invitation_complete')) else: form = form_class() context = apply_extra_context(RequestContext(request), extra_context) return rende
r_to_response(template_name, {'form': form}, context_instance=context) def register(request, invitation_key, wrong_key_template='invitation/wrong_invitation_key.html', redirect_to_if_authenticated='/', success_url=None, form_class=RegistrationFormInvitation, template_name='registration/registration_form.html', extra_context=None): """ Allow a new user to register via invitation. Send invitation email and then redirect to success URL if the invitation form is valid. Redirect named URL ``invitation_unavailable`` on InvitationError. Render invitation form template otherwise. Sends registration.signals.user_registered after creating the user. **Required arguments:** :invitation_key: An invitation key in the form of ``[\da-e]{40}`` **Optional arguments:** :wrong_key_template: Template to be used when an invalid invitation key is supplied. Default value is ``invitation/wrong_invitation_key.html``. :redirect_to_if_authenticated: URL to be redirected when an authenticated user calls this view. Defaults value is ``/`` :success_url: The URL to redirect to on successful registration. Default value is ``None``, ``invitation_registered`` will be resolved in this case. :form_class: A form class to use for registration. Takes the invited email as first argument to its constructor. :template_name: A custom template to use. Default value is ``registration/registration_form.html``. :extra_context: A dictionary of variables to add to the template context. Any callable object in this dictionary will be called to produce the end result which appears in the context. **Templates:** ``invitation/invitation_form.html`` or ``template_name`` keyword argument as the *main template*. ``invitation/wrong_invitation_key.html`` or ``wrong_key_template`` keyword argument as the *wrong key template*. **Context:** ``RequestContext`` instances are used rendering both templates. Context, in addition to ``extra_context``, contains: For wrong key template :invitation_key: supplied invitation key For main template :form: The registration form. """ if request.user.is_authenticated(): return HttpResponseRedirect(redirect_to_if_authenticated) try: invitation = Invitation.objects.find(invitation_key) except Invitation.DoesNotExist: context = apply_extra_context(RequestContext(request), extra_context) return render_to_response(wrong_key_template, {'invitation_key': invitation_key}, context_instance=context) if request.method == 'POST': form = form_class(invitation.email, request.POST, request.FILES) if form.is_valid(): new_user = form.save() invitation.mark_accepted(new_user) user_registered.send(sender="invitation", user=new_user, request=request) # return HttpResponseRedirect(success_url or reverse('invitation_registered')) # return HttpResponseRedirect(success_url or reverse('profiles-profile-detail', kwargs={'slug':new_user.username})) return HttpResponseRedirect(success_url or reverse('auth_login')) else: form = form_class(invitation.email) context = apply_extra_context(RequestContext(request), extra_context) return render_to_response(template_name, {'form': form}, context_instance=context) @staff_member_required def reward(request): """ Add invitations to users with high invitation performance and redirect refferring page. """ rewarded_users, invitations_given = InvitationStats.objects.reward() if rewarded_users: message = ugettext(u'%(users)s users are given a total of ' \ u'%(invitations)s invitations.') % { 'users': rewarded_users, 'invitations': invitations_given} else: message = ugettext(u'No user has performance above ' \ u'threshold, no invitations awarded.') request.user.message_set.create(message=message) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
sunlightlabs/horseradish
photolib/search_indexes.py
Python
bsd-3-clause
592
0.001689
from haystack import indexes from photolib.models import Photo class PhotoIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=Tru
e, use_template=True) alt = indexes.CharField(model_attr='alt', indexed=False) uuid = indexes.CharField(model_attr='uuid', indexed=False) thumbnail_url
= indexes.CharField(indexed=False, model_attr='image_thumbnail__url') def get_model(self): return Photo def get_updated_field(self): return 'last_updated' def index_queryset(self, using=None): return Photo.objects.visible()
HBEE/odoo-addons
account_journal_security/res_users.py
Python
agpl-3.0
741
0.008097
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in mod
ule root # directory ############################################################################## from openerp.osv
import osv, fields class users(osv.osv): _name = 'res.users' _inherit = 'res.users' _columns = { 'journal_ids': fields.many2many('account.journal', 'journal_security_journal_users','user_id', 'journal_id', 'Restricted Journals', help="This journals and the information related to it will be only visible for users where you specify that they can see them setting this same field."), }
Microvellum/Fluid-Designer
win64-vc/2.78/scripts/addons/io_scene_ms3d/ms3d_utils.py
Python
gpl-3.0
5,817
0.002235
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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 2 # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> ############################################################################### #234567890123456789012345678901234567890123456789012345678901234567890123456789 #--------1---------2---------3---------4---------5---------6---------7--------- # ##### BEGIN COPYRIGHT BLOCK ##### # # initial script copyright (c)2011-2013 Alexander Nussbaumer # # ##### END COPYRIGHT BLOCK ##### #import python stuff from os import ( path ) # import io_scene_ms3d stuff from io_scene_ms3d.ms3d_strings import ( ms3d_str, ) #import blender stuff from bpy import ( ops, ) ############################################################################### def enable_edit_mode(enable, blender_context): if blender_context.active_object is None \ or not blender_context.active_object.type in {'MESH', 'ARMATURE', }: return if enable: modeString = 'EDIT' else: modeString = 'OBJECT' if ops.object.mode_set.poll(): ops.object.mode_set(mode=modeString) ############################################################################### def enable_pose_mode(enable, blender_context): if blender_context.active_object is None \ or not blender_context.active_object.type in {'ARMATURE', }: return if enable: modeString = 'POSE' else: modeString = 'OBJECT' if ops.object.mode_set.poll(): ops.object.mode_set(mode=modeString) ############################################################################### def select_all(select): if select: actionString = 'SELECT' else: actionString = 'DESELECT' if ops.object.select_all.poll(): ops.object.select_all(action=actionString) if ops.mesh.select_all.poll(): ops.mesh.select_all(action=actionString) if ops.pose.select_all.poll(): ops.pose.select_all(action=actionString) ############################################################################### def pre_setup_environment(porter, blender_context): # inject undo to porter # and turn off undo porter.undo = blender_context.user_preferences.edit.use_global_undo blender_context.user_preferences.edit.use_global_undo = False # inject active_object to self porter.active_object = blender_context.scene.objects.active # change to a well defined mode enable_edit_mode(True, blender_context) # enable face-selection-mode blender_context.tool_settings.mesh_select_mode = (False, False, True) # change back to object mode enable_edit_mode(False, blender_context) ############################################################################### def post_setup_environment(porter, blender_context): # restore active object blender_context.scene.objects.active = porter.active_object if not blender_context.scene.objects.active \ and blender_context.selected_objects: blender_context.scene.objects.active \ = blender_context.selected_objects[0] # restore pre operator undo state blender_context.user_preferences.edit.use_global_undo = porter.undo ############################################################################### def get_edge_split_modifier_add_if(blender_mesh_object): blender_modifier = blender_mesh_object.modifiers.get( ms3d_str['OBJECT_MODIFIER_SMOOTHING_GROUP']) if blender_modifier is None: blender_modifier = blender_mesh_object.modifiers.new( ms3d_str['OBJECT_MODIFIER_SMOOTHING_GROUP'], type='EDGE_SPLIT') blender_modifier.show_expanded = False blender_modifier.use_edge_angle = False blender_modifier.use_edge_sharp = True blender_mesh_object.data.show_edge_seams = True blender_mesh_object.data.show_edge_sharp = True return blender_modifier ########################################################################### def rotation_matrix(v_track, v_up): ## rotation matrix from two vectors ## http://gamedev.stackexchange.com/questions/20097/how-to-calculate-a-3x3-rotation-matrix-from-2-direction-vectors ## http://www.fastgraph.com/makegames/3drotation/ matrix = Matrix().to_3x3() c1 = v_track c1.normalize() c0 = c1.cross(v_up) c0.normalize() c2 = c0.cross(c1) c2.normalize() matrix.col[0] = c0 matrix.col[1] = c1 matrix.col[2] = c2 return matrix ############################################################################### def matrix
_difference(mat_src, mat_dst): mat_dst_inv = mat_dst.inverted() return mat_dst_inv * mat_src ############################################################################### ############################################################################### #23456789012345678901234567890123456789012345678901234567890123
4567890123456789 #--------1---------2---------3---------4---------5---------6---------7--------- # ##### END OF FILE #####
rochapps/django-datamaps
datamaps/__init__.py
Python
bsd-2-clause
103
0
""" Django-Datamaps
provides helper functions compatible with datamaps.js. """
__version__ = '0.2.2'
benjamin-hodgson/build
test/evaluate_callables_tests.py
Python
mit
2,020
0.001485
from build import evaluate_callables class WhenEvaluatingAD
ictWithNoCallables: def when_i_evaluate_the_dict(self): self.result = evaluate_callables
({"abc": 123, "def": 456, "xyz": 789}) def it_should_return_the_same_dict(self): assert self.result == {"abc": 123, "def": 456, "xyz": 789} class WhenEvaluatingADictWithCallables: def given_input_containing_lambdas(self): self.input = {"abc": lambda: 123, "def": lambda: 456, "xyz": 789} self.input_copy = self.input.copy() def when_i_evaluate_the_dict(self): self.result = evaluate_callables(self.input) def it_should_return_the_dict_having_called_the_functions(self): assert self.result == {"abc": 123, "def": 456, "xyz": 789} def it_should_not_change_the_original_dict(self): assert self.input == self.input_copy class MyDict(dict): def __eq__(self, other): if not isinstance(other, MyDict): return False return super().__eq__(other) def copy(self): return MyDict({k: v for k, v in self.items()}) class WhenEvaluatingACustomDictWithNoCallables: def when_i_evaluate_the_dict(self): self.result = evaluate_callables(MyDict({"abc": 123, "def": 456, "xyz": 789})) def it_should_return_an_instance_of_the_same_class(self): assert self.result == MyDict({"abc": 123, "def": 456, "xyz": 789}) class WhenEvaluatingACustomDictWithCallables: def given_input_containing_lambdas(self): self.input = MyDict({"abc": lambda: 123, "def": lambda: 456, "xyz": 789}) self.input_copy = self.input.copy() def when_i_evaluate_the_dict(self): self.result = evaluate_callables(self.input) def it_should_return_an_instance_of_the_same_class_having_called_the_functions(self): assert self.result == MyDict({"abc": 123, "def": 456, "xyz": 789}) def it_should_not_change_the_original_dict(self): assert self.input == self.input_copy # todo: make it work for other sequences
guibernardino/mezzanine
mezzanine/core/defaults.py
Python
bsd-2-clause
18,350
0.004741
""" Default settings for the ``mezzanine.core`` app. Each of these can be overridden in your project's settings module, just like regular Django settings. The ``editable`` argument for each controls whether the setting is editable via Django's admin. Thought should be given to how a setting is actually used before making it editable, as it may be inappropriate - for example settings that are only read during startup shouldn't be editable, since changing them would require an application reload. """ from django.conf import settings from django.utils.translation import ugettext_lazy as _ from mezzanine.conf import register_setting register_setting( name="ADMIN_MENU_ORDER", description=_("Controls the ordering and grouping of the admin menu."), editable=False, default=( (_("Content"), ("pages.Page", "blog.BlogPost", "generic.ThreadedComment", (_("Media Library"), "fb_browse"),)), (_("Site"), ("sites.Site", "redirects.Redirect", "conf.Setting")), (_("Users"), ("auth.User", "auth.Group",)), ), ) register_setting( name="ADMIN_REMOVAL", description=_("Unregister these models from the admin."), editable=False, default=(), ) register_setting( name="ADMIN_THUMB_SIZE", description=_("Size of thumbnail previews for image fields in the " "admin interface."), editable=False, default="24x24", ) register_setting( name="CACHE_SET_DELAY_SECONDS", description=_("Mezzanine's caching uses a technique know as mint " "caching. This is where the requested expiry for a cache entry " "is stored with the cache entry in cache, and the real expiry " "used has the ``CACHE_SET_DELAY`` added to it. Then on a cache get, " "the store expiry is checked, and if it has past, the cache entry " "is set again, and no entry is returned. This tries to ensure that " "cache misses never occur, and if many clients were to get a cache " "miss at once, only one would actually need to re-generated the " "cache entry."), editable=False, default=30, ) register_setting( name="AKISMET_API_KEY", label=_("Akismet API Key"), description=_("Key for http://akismet.com spam filtering service. Used " "for filtering comments and forms."), editable=True, default="", ) if "mezzanine.blog" in settings.INSTALLED_APPS: dashboard_tags = ( ("blog_tags.quick_blog", "mezzanine_tags.app_list"), ("comment_tags.recent_comments",), ("mezzanine_tags.recent_actions",), ) else: dashboard_tags = ( ("mezzanine_tags.app_list",), ("mezzanine_tags.recent_actions",), (), ) register_setting( name="DASHBOARD_TAGS", description=_("A three item sequence, each containing a sequence of " "template tags used to render the admin dashboard."), editable=False, default=dashboard_tags, ) register_setting( name="DEVICE_DEFAULT", description=_("Device specific template sub-directory to use as the " "default device."), editable=False, default="", ) register_setting( name="DEVICE_USER_AGENTS", description=_("Mapping of device specific template sub-directory names to " "the sequence of strings that may be found in their user agents."), editable=False, default=( ("mobile", ("2.0 MMP", "240x320", "400X240", "AvantGo", "BlackBerry", "Blazer", "Cellphone", "Danger", "DoCoMo", "Elaine/3.0", "EudoraWeb", "Googlebot-Mobile", "hiptop", "IEMobile", "KYOCERA/WX310K", "LG/U990", "MIDP-2.", "MMEF20", "MOT-V", "NetFront", "Newt", "Ninte
ndo Wii", "Nitro", "Nokia", "Opera Mini", "Palm", "PlayStation Portable", "portalmmm", "Proxinet", "ProxiNet", "SHARP-TQ-GX10", "SHG-i900", "Small", "SonyEricsson", "Symbian OS", "SymbianOS", "TS21i-10", "UP.Browser", "UP.Link", "webOS", "Windows CE", "WinWAP", "YahooSeeker/M1A1-R2D2", "iPhone", "iPod", "Android",
"BlackBerry9530", "LG-TU915 Obigo", "LGE VX", "webOS", "Nokia5800",) ), ), ) register_setting( name="FORMS_USE_HTML5", description=_("If ``True``, website forms will use HTML5 features."), editable=False, default=False, ) register_setting( name="EXTRA_MODEL_FIELDS", description=_("A sequence of fields that will be injected into " "Mezzanine's (or any library's) models. Each item in the sequence is " "a four item sequence. The first two items are the dotted path to the " "model and its field name to be added, and the dotted path to the " "field class to use for the field. The third and fourth items are a " "sequence of positional args and a dictionary of keyword args, to use " "when creating the field instance. When specifying the field class, " "the path ``django.models.db.`` can be omitted for regular Django " "model fields."), editable=False, default=(), ) register_setting( name="GOOGLE_ANALYTICS_ID", label=_("Google Analytics ID"), editable=True, description=_("Google Analytics ID (http://www.google.com/analytics/)"), default="", ) register_setting( name="HOST_THEMES", description=_("A sequence mapping host names to themes, allowing " "different templates to be served per HTTP hosts " "Each item in the sequence is a two item sequence, " "containing a host such as ``othersite.example.com``, and " "the name of an importable Python package for the theme. " "If the host is matched for a request, the templates " "directory inside the theme package will be first searched " "when loading templates."), editable=False, default=(), ) register_setting( name="JQUERY_FILENAME", label=_("Name of the jQuery file."), description=_("Name of the jQuery file found in " "mezzanine/core/static/mezzanine/js/"), editable=False, default="jquery-1.7.1.min.js", ) register_setting( name="MAX_PAGING_LINKS", label=_("Max paging links"), description=_("Max number of paging links to display when paginating."), editable=True, default=10, ) register_setting( name="RICHTEXT_WIDGET_CLASS", description=_("Dotted package path and class name of the widget to use " "for the ``RichTextField``."), editable=False, default="mezzanine.core.forms.TinyMceWidget", ) register_setting( name="RICHTEXT_ALLOWED_TAGS", description=_("List of HTML tags that won't be stripped from " "``RichTextField`` instances."), editable=False, default=("a", "abbr", "acronym", "address", "area", "b", "bdo", "big", "blockquote", "br", "button", "caption", "center", "cite", "code", "col", "colgroup", "dd", "del", "dfn", "dir", "div", "dl", "dt", "em", "fieldset", "font", "form", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "i", "img", "input", "ins", "kbd", "label", "legend", "li", "map", "menu", "ol", "optgroup", "option", "p", "pre", "q", "s", "samp", "select", "small", "span", "strike", "strong", "sub", "sup", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "tr", "tt", "u", "ul", "var", "wbr"), ) register_setting( name="RICHTEXT_ALLOWED_ATTRIBUTES", description=_("List of HTML attributes that won't be stripped from " "``RichTextField`` instances."), editable=False, default=("abbr", "accept", "accept-charset", "accesskey", "action", "align", "alt", "axis", "border", "cellpadding", "cellspacing", "char", "charoff", "charset", "checked", "cite", "class", "clear", "cols", "colspan", "color", "compact", "coords", "datetime", "dir", "disabled", "enctype", "for", "frame", "headers", "height", "href", "hreflang", "hspace", "id", "ismap", "label", "lang", "longdesc", "maxlength", "media", "method", "multiple", "name", "nohref", "noshade", "nowrap
LogicalDash/kivy
kivy/core/camera/__init__.py
Python
mit
4,415
0
''' Camera ====== Core class for acquiring the camera and converting its input into a :class:`~kivy.graphics.texture.Texture`. .. versionchanged:: 1.10.0 The pygst and videocapture providers have been removed. .. versionchanged:: 1.8.0 There is now 2
distinct Gstream
er implementation: one using Gi/Gst working for both Python 2+3 with Gstreamer 1.0, and one using PyGST working only for Python 2 + Gstreamer 0.10. ''' __all__ = ('CameraBase', 'Camera') from kivy.utils import platform from kivy.event import EventDispatcher from kivy.logger import Logger from kivy.core import core_select_lib class CameraBase(EventDispatcher): '''Abstract Camera Widget class. Concrete camera classes must implement initialization and frame capturing to a buffer that can be uploaded to the gpu. :Parameters: `index`: int Source index of the camera. `size`: tuple (int, int) Size at which the image is drawn. If no size is specified, it defaults to the resolution of the camera image. `resolution`: tuple (int, int) Resolution to try to request from the camera. Used in the gstreamer pipeline by forcing the appsink caps to this resolution. If the camera doesnt support the resolution, a negotiation error might be thrown. :Events: `on_load` Fired when the camera is loaded and the texture has become available. `on_texture` Fired each time the camera texture is updated. ''' __events__ = ('on_load', 'on_texture') def __init__(self, **kwargs): kwargs.setdefault('stopped', False) kwargs.setdefault('resolution', (640, 480)) kwargs.setdefault('index', 0) self.stopped = kwargs.get('stopped') self._resolution = kwargs.get('resolution') self._index = kwargs.get('index') self._buffer = None self._format = 'rgb' self._texture = None self.capture_device = None kwargs.setdefault('size', self._resolution) super(CameraBase, self).__init__() self.init_camera() if not self.stopped: self.start() def _set_resolution(self, res): self._resolution = res self.init_camera() def _get_resolution(self): return self._resolution resolution = property(lambda self: self._get_resolution(), lambda self, x: self._set_resolution(x), doc='Resolution of camera capture (width, height)') def _set_index(self, x): if x == self._index: return self._index = x self.init_camera() def _get_index(self): return self._x index = property(lambda self: self._get_index(), lambda self, x: self._set_index(x), doc='Source index of the camera') def _get_texture(self): return self._texture texture = property(lambda self: self._get_texture(), doc='Return the camera texture with the latest capture') def init_camera(self): '''Initialise the camera (internal)''' pass def start(self): '''Start the camera acquire''' self.stopped = False def stop(self): '''Release the camera''' self.stopped = True def _update(self, dt): '''Update the camera (internal)''' pass def _copy_to_gpu(self): '''Copy the the buffer into the texture''' if self._texture is None: Logger.debug('Camera: copy_to_gpu() failed, _texture is None !') return self._texture.blit_buffer(self._buffer, colorfmt=self._format) self._buffer = None self.dispatch('on_texture') def on_texture(self): pass def on_load(self): pass # Load the appropriate providers providers = () if platform == 'macosx': providers += (('avfoundation', 'camera_avfoundation', 'CameraAVFoundation'), ) elif platform == 'android': providers += (('android', 'camera_android', 'CameraAndroid'), ) else: providers += (('picamera', 'camera_picamera', 'CameraPiCamera'), ) providers += (('gi', 'camera_gi', 'CameraGi'), ) providers += (('opencv', 'camera_opencv', 'CameraOpenCV'), ) Camera = core_select_lib('camera', (providers))
shtrom/gtg
GTG/core/plugins/api.py
Python
gpl-3.0
8,572
0.00035
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # 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/>. # ----------------------------------------------------------------------------- import os import pickle from GTG.core.dirs import plugin_configuration_dir from GTG.tools.logger import Log class PluginAPI(object): """The plugin engine's API. L{PluginAPI} is a object that provides a nice API for plugins to interact with GTG. Multiple L{PluginAPI}s can exist. A instance is created to be used with the task browser and another instance is created to be used with the task editor. """ def __init__(self, requester, view_manager, taskeditor=None): """ Construct a PluginAPI object. @param requester: The requester. @param view_manager: The view manager @param task_id: The Editor, if we are in one otherwise. """ self.__requester = requester self.__view_manager = view_manager self.selection_changed_callback_listeners = [] if taskeditor: self.__ui = taskeditor self.__builder = self.__ui.get_builder() self.__toolbar = self.__builder.get_object('task_tb1') self.__task_id = taskeditor.get_task() else: self.__ui = self.__view_manager.get_browser() self.__builder = self.__ui.get_builder() self.__toolbar = self.__builder.get_object('task_toolbar') self.__task_id = None self.__view_manager.browser.selection.connect( "changed", self.__selection_changed) self.taskwidget_id = 0 self.taskwidget_widg = [] def __selection_changed(self, selection): for func in self.selection_changed_callback_listeners: func(selection) # Accessor methods ============================================================ def is_editor(self): """ Returns true if this is an Editor API """ return bool(self.__task_id) def is_browser(self): """ Returns true if this is a Browser API """ return not self.is_editor() def get_view_manager(self): """ returns a GTG.gtk.manager.Manager """ return self.__view_manager def get_requester(self): """ returns a GTG.core.requester.Requester """ return self.__requester def get_gtk_builder(self): """ Returns the gtk builder for the parent window """ return self.__builder def get_ui(self): ''' Returns a Browser or an Editor ''' return self.__ui def get_browser(self): ''' Returns a Browser ''' return self.__view_manager.get_browser() def get_selected(self): ''' Returns the selected tasks in the browser or the task ID if the editor ''' if self.is_editor(): return self.__task_id else: return self.__view_manager.browser.get_selected_tasks() def set_active_selection_
changed_callback(self, func): if func not in self.selection_changed_callback_listeners: self.selection_changed_callback_listeners.append(func) def remove_active_selection_changed_callback(self, plugin_class): new_list = [func for func in self.selection_changed_callback_listeners if func.__class__ != plugin_class] self.selection_changed_call
back_listeners = new_list # Changing the UI =========================================================== def add_menu_item(self, item): """Adds a menu entry to the Plugin Menu of the Main Window (task browser). @param item: The Gtk.MenuItem that is going to be added. """ widget = self.__builder.get_object('plugin_mi') widget.get_submenu().append(item) widget.show_all() def remove_menu_item(self, item): """Removes a menu entry from the Plugin Menu of the Main Window (task browser). @param item: The Gtk.MenuItem that is going to be removed. @return: Returns C{True} if the operation has sucess or c{False} if it fails. """ menu = self.__builder.get_object('plugin_mi') submenu = menu.get_submenu() try: submenu.remove(item) except: pass if not submenu.get_children(): menu.hide() def add_toolbar_item(self, widget): """Adds a button to the task browser's toolbar or the task editor toolbar, depending on which plugin api it's being used. @param widget: The Gtk.ToolButton that is going to be added to the toolbar. """ # -1 means "append to the end" self.__toolbar.insert(widget, -1) def remove_toolbar_item(self, widget): """ Remove a widget from the toolbar. """ try: self.__toolbar.remove(widget) except Exception as e: print("Error removing the toolbar item in the TaskEditor: %s" % e) def add_widget_to_taskeditor(self, widget): """Adds a widget to the bottom of the task editor dialog @param widget: The Gtk.Widget that is going to be added. """ vbox = self.__builder.get_object('vbox4') if vbox: vbox.pack_start(widget, True, True, 0) vbox.reorder_child(widget, -2) widget.show_all() self.taskwidget_id += 1 self.taskwidget_widg.append(widget) return self.taskwidget_id else: return None def remove_widget_from_taskeditor(self, widg_id): """Remove a widget from the bottom of the task editor dialog @param widget: The Gtk.Widget that is going to be removed """ if self.is_editor() and widg_id: try: wi = self.__builder.get_object('vbox4') if wi and widg_id in self.taskwidget_widg: wi.remove(self.taskwidget_widg.pop(widg_id)) except Exception as e: Log.debug("Error removing the toolbar item in the TaskEditor:" "%s" % e) def set_bgcolor_func(self, func=None): """ Set a function which defines a background color for each task NOTE: This function stronglye depend on browser and could be easily broken by changes in browser code """ browser = self.get_browser() # set default bgcolor? if func is None: func = browser.tv_factory.task_bg_color for pane in browser.vtree_panes.values(): pane.set_bg_color(func, 'bg_color') pane.basetree.get_basetree().refresh_all() # file saving/loading ======================================================= def load_configuration_object(self, plugin_name, filename, default_values=None): if default_values is not None: config = dict(default_values) else: config = dict() dirname = plugin_configuration_dir(plugin_name) path = os.path.join(dirname, filename) try: with open(path, 'rb') as file: item = pickle.load(file) conf
costibleotu/czl-scrape
sanatate/scrapy_proj/helpers/romanian.py
Python
mpl-2.0
509
0.004132
# -*- coding: utf-8 -*- class RomanianHelper(object): @staticmethod def englishize_romanian(string): symbols = (u"țţȚŢșşȘŞăǎĂîÎâÂ", u"ttTTssSSaaAiIaA") tr = {ord(a):ord(b) for a, b in zip(*symbols)} return string.transl
ate(tr) @staticmethod def beautify_romanian(string): symbols = (u"ǎţşŢ
Ş", u"ățșȚȘ") tr = {ord(a):ord(b) for a, b in zip(*symbols)} return string.translate(tr)
robiame/AndroidGeodata
pil/PcxImagePlugin.py
Python
mit
4,834
0.005379
# # The Python Imaging Library. # $Id$ # # PCX file handling # # This format was originally used by ZSoft's popular PaintBrush # program for the IBM PC. It is also supported by many MS-DOS and # Windows applications, including the Windows PaintBrush program in # Windows 3. # # history: # 1995-09-01 fl Created # 1996-05-20 fl Fixed RGB support # 1997-01-03 fl Fixed 2-bit and 4-bit support # 1999-02-03 fl Fixed 8-bit support (broken in 1.0b1) # 1999-02-07 fl Added write support # 2002-06-09 fl Made 2-bit and 4-bit support a bit more robust # 2002-07-30 fl Seek from to current position, not beginning of file # 2003-06-03 fl Extract DPI settings (info["dpi"]) # # Copyright (c) 1997-2003 by Secret Labs AB. # Copyright (c) 1995-2003 by Fredrik Lundh. # # See the README file for information on usage and redistribution. # __
version__ = "0.6" import Image, ImageFile, ImagePalette def i16(c,o): return ord(c[o]) + (ord(c[o+1])<<8) def _accept(prefix): return ord(prefix[0]) == 10 and ord(prefix[1
]) in [0, 2, 3, 5] ## # Image plugin for Paintbrush images. class PcxImageFile(ImageFile.ImageFile): format = "PCX" format_description = "Paintbrush" def _open(self): # header s = self.fp.read(128) if not _accept(s): raise SyntaxError, "not a PCX file" # image bbox = i16(s,4), i16(s,6), i16(s,8)+1, i16(s,10)+1 if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]: raise SyntaxError, "bad PCX image size" # format version = ord(s[1]) bits = ord(s[3]) planes = ord(s[65]) stride = i16(s,66) self.info["dpi"] = i16(s,12), i16(s,14) if bits == 1 and planes == 1: mode = rawmode = "1" elif bits == 1 and planes in (2, 4): mode = "P" rawmode = "P;%dL" % planes self.palette = ImagePalette.raw("RGB", s[16:64]) elif version == 5 and bits == 8 and planes == 1: mode = rawmode = "L" # FIXME: hey, this doesn't work with the incremental loader !!! self.fp.seek(-769, 2) s = self.fp.read(769) if len(s) == 769 and ord(s[0]) == 12: # check if the palette is linear greyscale for i in range(256): if s[i*3+1:i*3+4] != chr(i)*3: mode = rawmode = "P" break if mode == "P": self.palette = ImagePalette.raw("RGB", s[1:]) self.fp.seek(128) elif version == 5 and bits == 8 and planes == 3: mode = "RGB" rawmode = "RGB;L" else: raise IOError, "unknown PCX mode" self.mode = mode self.size = bbox[2]-bbox[0], bbox[3]-bbox[1] bbox = (0, 0) + self.size self.tile = [("pcx", bbox, self.fp.tell(), (rawmode, planes * stride))] # -------------------------------------------------------------------- # save PCX files SAVE = { # mode: (version, bits, planes, raw mode) "1": (2, 1, 1, "1"), "L": (5, 8, 1, "L"), "P": (5, 8, 1, "P"), "RGB": (5, 8, 3, "RGB;L"), } def o16(i): return chr(i&255) + chr(i>>8&255) def _save(im, fp, filename, check=0): try: version, bits, planes, rawmode = SAVE[im.mode] except KeyError: raise ValueError, "Cannot save %s images as PCX" % im.mode if check: return check # bytes per plane stride = (im.size[0] * bits + 7) / 8 # under windows, we could determine the current screen size with # "Image.core.display_mode()[1]", but I think that's overkill... screen = im.size dpi = 100, 100 # PCX header fp.write( chr(10) + chr(version) + chr(1) + chr(bits) + o16(0) + o16(0) + o16(im.size[0]-1) + o16(im.size[1]-1) + o16(dpi[0]) + o16(dpi[1]) + chr(0)*24 + chr(255)*24 + chr(0) + chr(planes) + o16(stride) + o16(1) + o16(screen[0]) + o16(screen[1]) + chr(0)*54 ) assert fp.tell() == 128 ImageFile._save(im, fp, [("pcx", (0,0)+im.size, 0, (rawmode, bits*planes))]) if im.mode == "P": # colour palette fp.write(chr(12)) fp.write(im.im.getpalette("RGB", "RGB")) # 768 bytes elif im.mode == "L": # greyscale palette fp.write(chr(12)) for i in range(256): fp.write(chr(i)*3) # -------------------------------------------------------------------- # registry Image.register_open("PCX", PcxImageFile, _accept) Image.register_save("PCX", _save) Image.register_extension("PCX", ".pcx")
jim-cooley/abletonremotescripts
remote-scripts/samples/APC_64_40_r1b/APC_64_40/EncoderUserModesComponent.py
Python
apache-2.0
6,872
0.005675
# http://remotescripts.blogspot.com """ Track Control User Modes component originally designed for use with the APC40. Copyright (C) 2010 Hanz Petrov <hanz.petrov@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 (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 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/>. """ import Live from _Framework.ModeSelectorComponent import ModeSelectorComponent from _Framework.ButtonElement import ButtonElement from _Framework.DeviceComponent import DeviceComponent class EncoderUserModesComponent(ModeSelectorComponent): ' SelectorComponent that assigns encoders to different user functions ' __module__ = __name__ def __init__(self, parent, encoder_modes, param_controls, bank_buttons, mixer, device, encoder_device_modes, encoder_eq_modes): #, mixer, sliders): assert (len(bank_buttons) == 4) ModeSelectorComponent.__init__(self) self._parent = parent self._encoder_modes = encoder_modes self._param_controls = param_controls self._bank_buttons = bank_buttons self._mixer = mixer self._device = device self._encoder_device_modes = encoder_device_modes self._encoder_eq_modes = encoder_eq_modes self._mode_index = 0 self._modes_buttons = [] self._user_buttons = [] self._last_mode = 0 def disconnect(self): ModeSelectorComponent.disconnect(self) self._parent = None self._encoder_modes = None self._param_controls = None self._bank_buttons = None self._mixer = None self._device = None self._encoder_device_modes = None self._encoder_eq_modes = None self._modes_buttons = None self._user_buttons = None def on_enabled_changed(self): pass def set_mode(self, mode): assert isinstance(mode, int) assert (mode in range(self.number_of_modes())) if (self._mode_index != mode): self._last_mode = self._mode_index # keep track of previous mode, to allow conditional actions self._mode_index = mode self._set_modes() def set_mode_buttons(self, buttons): assert isinstance(buttons, (tuple, type(None))) for button in self._modes_buttons: button.remove_value_listener(self._mode_value) self._modes_buttons = [] if (buttons != None): for button in buttons: assert isinstance(button, ButtonElement) identify_sender = True button.add_value_listener(self._mode_value, identify_sender) self._modes_buttons.append(button) assert (self._mode_index in range(self.number_of_modes())) def number_of_modes(self): return 4 def update(self): pass def _mode_value(self, value, sender): assert (len(self._modes_buttons) > 0) assert isinstance(value, int) assert isinstance(sender, ButtonElement) assert (self._modes_buttons.count(sender) == 1) if ((value is not 0) or (not sender.is_momentary())): self.set_mode(self._modes_buttons.index(sender)) def _set_modes(self): if self.is_enabled(): assert (self._mode_index in range(self.number_of_modes())) for index in range(len(self._modes_buttons)): if (index <= self._mode_index): self._modes_buttons[index].turn_on() else: self._modes_buttons[index].turn_off() for button in self._modes_buttons: button.release_parameter() button.use_default_message() for control in self._param_controls: control.release_parameter() control.use_default_message() #control.set_needs_takeover(False) self._encoder_modes.set_enabled(False) self._encoder_device_modes.set_lock_button(None) self._encoder_device_modes._alt_device.set_bank_nav_buttons(None, None) self._encoder_device_modes._alt_device.set_on_off_button(None) if self._encoder_device_modes._alt_device._parameter_controls != None: for control in self._encoder_device_modes._alt_device._parameter_controls: control.release_parameter() self._encoder_device_modes.set_enabled(False) self._encoder_eq_modes.set_enabled(False) self._encoder_eq_modes.set_lock_button(None) if self._encoder_eq_modes._track_eq != None: self._encoder_eq_modes._track_eq.set_cut_buttons(None) if self._encoder_eq_modes._track_eq._gain_controls != None: for control in self._encoder_eq_modes._track_eq._gain_controls: control.release_parameter() if self._encoder_eq_modes._strip != None: self._encoder_eq_modes._strip.set_send_controls(None) self._user_buttons = [] if (self._mode_index == 0): self._encoder_modes.set_enabled(True) elif (self._mode_index == 1): self._encoder_device_modes.set_enabled(True) self._encoder_device_modes.set_controls_and_buttons(self._param_controls, self._modes_buttons) elif (self._mode_index == 2): self._encoder_eq_modes.set_enabled(True)
self._encoder_eq_modes.set_controls_and_buttons(self._param_controls, self._modes_buttons) elif (sel
f._mode_index == 3): self._encoder_eq_modes._ignore_buttons = True if self._encoder_eq_modes._track_eq != None: self._encoder_eq_modes._track_eq._ignore_cut_buttons = True self._encoder_device_modes._ignore_buttons = True for button in self._modes_buttons: self._user_buttons.append(button) for control in self._param_controls: control.set_identifier((control.message_identifier() - 9)) control._ring_mode_button.send_value(0) else: pass #self._rebuild_callback() # local variables: # tab-width: 4
holloway/docvert-python3
docvert-web.py
Python
gpl-3.0
12,330
0.007218
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import io import uuid import os.path import socket import optparse import cgi docvert_root = os.path.dirname(os.path.abspath(__file__)) inbuilt_bottle_path = os.path.join(docvert_root, 'lib/bottle') try: import bottle if not hasattr(bottle, 'static_file'): message = "Notice: Old version of Bottle at %s, instead using bundled version at %s%sbottle.py" % (bottle.__file__, inbuilt_bottle_path, os.sep) print(message) raise ImportError(message) except ImportError as exception: try: sys.path.insert(0, inbuilt_bottle_path) try: reload(bottle) except NameError: import bottle except ImportError: sys.stderr.write("Error: Unable to find Bottle libraries in %s. Exiting...\n" % sys.path) sys.exit(0) import lib.bottlesession.bottlesession bottle.debug(True) import core.docvert import core.docvert_storage import core.docvert_exception import core.document_type # START DEFAULT CONFIG theme='default' host='localhost' port=8080 # END CONFIG parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", help="Port to run on", type="int") parser.add_option("-H", "--host", dest="host", help="Hostname or IP run on", type="str") (options, args) = parser.parse_args() if options.port: port = options.port if options.host: host = options.host theme_directory='%s/core/web_service_themes' % docvert_root bottle.TEMPLATE_PATH.append('%s/%s' % (theme_directory, theme)) # URL mappings @bottle.route('/index', method='GET') @bottle.route('/', method='GET') @bottle.view('index') def index(): return dict(list(core.docvert.get_all_pipelines(False).items()) + list({"libreOfficeStatus": core.docvert_libreoffice.checkLibreOfficeStatus()}.items()) ) @bottle.route('/static/:path#.*#', method='GET') def static(path=''): return bottle.static_file(path, root=theme_directory) @bottle.route('/lib/:path#.*#', method='GET') def libstatic(path=None): return bottle.static_file(path, root='%s/lib' % docvert_root) @bottle.route('/web-service.php', method='POST') #for legacy Docvert support @bottle.route('/web-service', method='POST') @bottle.view('web-service') def webservice(): files = dict() first_document_id = None there_was_at_least_one_thing_uploaded = False for key, item in bottle.request.files.items(): there_was_at_least_one_thing_uploaded = True items = bottle.request.files.getall(key) for field_storage in items: filename = field_storage.filename unique = 1 if filename in files and files[filename].getvalue() == field_storage.value: #remove same file uploaded multiple times continue while filename in files: filename = field_storage.filename + str(unique) unique += 1 files[filename] = io.BytesIO(field_storage.value) pipeline_id = bottle.request.POST.get('pipeline') if pipeline_id.startswith('autopipeline:'): #Docvert 4.x pipeline_id = pipeline_id[len('autopipeline:'):] auto_pipeline_id = None if bottle.request.POST.get('break_up_pages_ui_version'): if bottle.request.POST.get('break_up_pages'): auto_pipeline_id = bottle.request.POST.get('autopipeline') if auto_pipeline_id is None: pipelines = list(core.docvert.get_all_pipelines().items()) for pipelinetype_key, pipelinetype_value in pipelines: if pipelinetype_key == "auto_pipelines": for pipeline in pipelinetype_value: if "nothing" in pipeline["id"].lower(): auto_pipeline_id = pipeline["id"] else: auto_pipeline_id = bottle.request.POST.get('autopipeline') docvert_4_default = '.default' if auto_pipeline_id and auto_pipeline_id.endswith(docvert_4_default): auto_pipeline_id = auto_pipeline_id[0:-len(docvert_4_default)] after_conversion = bottle.request.POST.get('afterconversion') urls = bottle.request.POST.getall('upload_web[]') if len(urls) == 1 and urls[0] == '': urls = list() else: urls = set(urls) response = None if there_was_at_least_one_thing_uploaded is False: #while we could have counted len(files) or len(urls) the logic around those is more complex, and I don't want to show this error unless there was genuinely no files uploaded bottle.response.content_type = "text/html" return '<!DOCTYPE html><html><body><h1>Error: No files were uploaded</h1><p>Known issues that can cause this:</p><ul><li>Permissions problem on the server or browser: Try ensuring that your upload file has all read permissions set.</li><li>Chrome/Chromium can sometimes cause file upload problems (some combination of Chrome/Bottle, it\'s not a Docvert-specific bug). Sorry, but Firefox seems to work.</li></ul><hr><a href="/">Try again?</a></body></html>' try: response = core.docvert.process_conversion(files, urls, pipeline_id, 'pipelines', auto_pipeline_id, suppress_errors=True) except core.docvert_exception.debug_exception as exception: bottle.response.content_type = exception.content_type return exception.data conversion_id = "%s" % uuid.uuid4() if after_conversion == "downloadZip" or after_conversion == "zip": bottle.response.content_type = 'application/zip' bottle.response.headers['Content-Disposition'] = 'attachment; filename="%s.zip"' % response.get_zip_name() return response.to_zip().getvalue() pipeline_summary = "%s (%s)" % (pipeline_id, auto_pipeline_id) session_manager = lib.bottlesession.bottlesession.PickleSession() session = session_manager.get_session() session[conversion_id] = response conversions_tabs = dict() first_document_url = "conversions/%s/%s/" % (conversion_
id, response.default_document) for filename in list(files.keys()): thumbnail_path = "%s/thumbnail.png" % filename if thumbnail_path in response: thumbnail_path = None conversions_tabs[filename] = dict(friendly_name=response.get_friendly_name_if_available(filename), pipeline=pipeline_id, auto_pipeline=auto_pipeline_id, thumbnail_path=thumbnail_path
) try: session_manager.save(session) except OSError as e: import traceback traceback.print_exc(file=sys.stdout) conversions_tabs = {'Session file problem': dict(friendly_name='Session file problem', pipeline=None, auto_pipeline=None, thumbnail_path=None) } first_document_url = "/bottle_session_file_problem" return dict(conversions=conversions_tabs, conversion_id=conversion_id, first_document_url=first_document_url) @bottle.route('/favicon.ico', method='GET') def favicon(): return bottle.static_file('favicon.ico', root='%s/%s' % (theme_directory, theme)) @bottle.route('/bottle_session_file_problem', method='GET') def bottle_session_file_problem(): print('%s/lib/bottle' % docvert_root) return bottle.static_file('bottle_session_file_problem.html', root='%s/lib/bottle' % docvert_root) @bottle.route('/conversions/:conversion_id/:path#.*#') def conversion_static_file(conversion_id, path): session_manager = lib.bottlesession.bottlesession.PickleSession() session = session_manager.get_session() if conversion_id not in session: # They don't have authorisation raise bottle.HTTPError(code=404) filetypes = {".xml":"text/xml", ".html":"text/html", ".xhtml":"text/html", ".htm":"text/html", ".svg":"image/svg+xml", ".txt":"text/plain", ".png":"image/png", ".gif":"image/gif", ".bmp":"image/x-ms-bmp", ".jpg":"image/jpeg", ".jpe":"image/jpeg", ".jpeg":"image/jpeg", ".css":"text/css", ".js":"text/javascript", ".odt":"application/vnd.oasis.opendocument.text", ".odp":"application/vnd.oasis.opendocument.presentation", ".ods":"application/vnd.oasis.opendocument.spreadsheet", ".dbk":"application/docbook+xml"} if path not in session[conversion_id]: # They have authorisation but that exact path doesn't exist, try fallbacks fallbacks = ["index.ht
OCA/partner-contact
partner_contact_department/models/res_partner.py
Python
agpl-3.0
839
0
# © 2014-2015 Tecnativa S.L. - Jairo Llopis # © 2016 Tecnativa S.L. - Vicent Cubells # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResPartner(models.Model): _inherit = "res.partner" department_id = fields.Many2one("res.partner.department", "Department") class ResPart
nerDepartment(models.Model): _name = "res.partner.department" _order = "parent_path" _parent_order = "name" _parent_store = T
rue _description = "Department" name = fields.Char(required=True, translate=True) parent_id = fields.Many2one( "res.partner.department", "Parent department", ondelete="restrict" ) child_ids = fields.One2many( "res.partner.department", "parent_id", "Child departments" ) parent_path = fields.Char(index=True)
phillxnet/rockstor-core
src/rockstor/scripts/qgroup_clean.py
Python
gpl-3.0
2,273
0.0022
""" Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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. RockStor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warrant
y 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/>. """ import re from storageadmin.models import Pool from system.osi import run_command from fs.btrfs import mount_root BTRFS = "/usr/sbin/btrfs" def main(): for p in Pool.objects.all(): try: print("Processing pool(%s)" % p.name) mnt_pt = mount_root(p) o, e, rc = run_command([BTRFS, "subvol", "list", mnt_pt]) subvol_ids = [] for l in o: if re.match("ID ", l) is not None: subvol_ids.append(l.split()[1]) o, e, rc = run_command([BTRFS, "qgroup", "show", mnt_pt], throw=False) if rc != 0: print("Quotas not enabled on pool(%s). Skipping it." % p.name) continue qgroup_ids = [] for l in o: if re.match("0/", l) is not None: q = l.split()[0].split("/")[1] if q == "5": continue qgroup_ids.append(l.split()[0].split("/")[1]) for q in qgroup_ids: if q not in subvol_ids: print("qgroup %s not in use. deleting" % q) run_command([BTRFS, "qgroup", "destroy", "0/%s" % q, mnt_pt]) else: print("qgroup %s is in use. Moving on." % q) print("Finished processing pool(%s)" % p.name) except Exception as e: print( "Exception while qgroup-cleanup of Pool(%s): %s" % (p.name, e.__str__()) ) if __name__ == "__main__": main()
SUNET/eduid-common
src/eduid_common/config/workers.py
Python
bsd-3-clause
3,033
0.00033
# # Copyright (c) 2013-2016 NORDUnet A/S # Copyright (c) 2019 SUNET # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # 3. Neither the name of the NORDUnet nor the names of its # con
tributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILIT
Y AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # from typing import Any, Optional from pydantic import Field from eduid_common.config.base import WorkerConfig class AmConfig(WorkerConfig): """ Configuration for the attribute manager celery worker """ new_user_date: str = '2001-01-01' action_plugins: list = Field(default_factory=lambda: ['tou']) class MsgConfig(WorkerConfig): """ Configuration for the msg celery worker """ audit: bool = True devel_mode: bool = False mail_certfile: str = '' mail_host: str = 'localhost' mail_keyfile: str = '' mail_password: str = '' mail_port: int = 25 mail_starttls: bool = False mail_username: str = '' message_rate_limit: Optional[int] = None # for celery. tasks per second - None for no rate limit # TODO: Purge everything about the MM API mm_api_uri: str = 'MM-API-not-available' mm_default_subject: str = 'MM-API-not-available' mongo_dbname: str = 'eduid_msg' navet_api_pw: str = '' navet_api_uri: str = '' navet_api_user: str = '' navet_api_verify_ssl: bool = False sms_acc: str = '' sms_key: str = '' sms_sender: str = 'eduID' template_dir: str = '' class MobConfig(WorkerConfig): """ Configuration for the lookup mobile celery worker """ devel_mode: bool = False log_path: str = '' teleadress_client_password: str = '' teleadress_client_user: str = ''
brianr747/SFC_models
sfc_models/gl_book/__init__.py
Python
apache-2.0
2,795
0.003936
""" Models from Godley & Lavoie text. [G&L 2012] "Monetary Economics: An Integrated Approach to credit, Money, Income, Production and Wealth; Second Edition", by Wynne Godley and Marc Lavoie, Palgrave Macmillan, 2012. ISBN 978-0-230-30184-9 Copyright 2016 Brian Romanchuk 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 h
ttp://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 sfc_models.models as
models class GL_book_model(object): """ Base class for example models from [G&L 2012] for single-country models. Generates the sectors, either in a new model object, or an object that is passed in. The user supplies a country code. """ def __init__(self, country_code, model=None, use_book_exogenous=True): """ Constructor for an example model. Builds a single country, using a code that is passed in. If the user supplies an existing Model object, uses that. This allows us to embed in a multi-country model. :param country_code: str :param model: sfc_models.models.Model :param use_book_exogenous: bool """ if model is None: model = models.Model() self.Model = model self.Country = models.Country(model, country_code, country_code) self.UseBookExogenous = use_book_exogenous def build_model(self): # pragma: no cover This is a virtual base class """ Does the work of building the sectors within a country. Returns the Model object. :return: sfc_models.models.Model """ return self.Model def expected_output(self): # pragma: no cover -- Virtual base class. """ Returns a list of expected output. Used to validate the framework output. Uses the default exogenous series. Format: A list of tuples, that consist of the variable name, and (limited) time series of output. For example: [ ('GOOD_SUP_GOOD', [0., 10., 12.]), ('HH_AfterTax', [0., 15., 18., 22.]), ] In this case, the variable 'GOOD_SUP_GOOD' is expected to be [0., 10., 12.] for the first 3 periods and 'HH_AftterTax' is expected to be [0., 15., 18., 22.] over the fiest 4 periods. In other words, target outputs do not have to be the same length. :return: list """ return []
IQSS/geoconnect
gc_apps/content_pages/migrations/0001_initial.py
Python
apache-2.0
1,770
0.003955
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-05-12 16:09 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='MaintenanceMode', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(default=b'Maintenance Mode', max_length=255)), ('is_active', models.BooleanField(default=False)),
('message', models.TextField(blank=True, help_text=b'Message to Display on Page. When ava
ilable, displayed instead of a template.')), ('template_name', models.CharField(default=b'content_pages/maintenance_message.html', help_text=b'Template with HTML snippet to display. Note: This field is ignored if a "message" is available.', max_length=255)), ('end_datetime', models.DateTimeField(blank=True, help_text=b'End datetime to display within the template. Important: Maintenance mode NEEDS TO BE TURNED OFF *manually*. This date/time is for display purposes only.', null=True)), ], options={ 'db_table': 'content_pages', 'verbose_name_plural': 'Maintenance Mode', }, ), ]
AbleCoder/pyjade_coffin
pyjade_coffin/template/loader.py
Python
mit
2,320
0
"""Replacement for ``django.template.loader`` that uses Jinja 2. The module provides a generic way to load templates from an arbitrary backend storage (e.g. filesystem, database). """ from coffin.template import Template as CoffinTemplate from jinja2 import TemplateNotFound def find_template_source(name, dirs=None): # This is Django's most basic loading function through which # all template retrievals go. Not sure if Jinja 2 publishes #
an equivalent, but no matter, it mostly for internal use # anyway - developers will want to start with # ``get_template()`` or ``get_template_from_string`` anyway. raise NotImplementedError() def get_template(template_name): # Jinja will handle this for us, and env also initializes # the loader backends the first time it is called. from pyjade_coffin.common import env return
env.get_template(template_name) def get_template_from_string(source): """ Does not support then ``name`` and ``origin`` parameters from the Django version. """ from pyjade_coffin.common import env return env.from_string(source) def render_to_string(template_name, dictionary=None, context_instance=None): """Loads the given ``template_name`` and renders it with the given dictionary as context. The ``template_name`` may be a string to load a single template using ``get_template``, or it may be a tuple to use ``select_template`` to find one of the templates in the list. ``dictionary`` may also be Django ``Context`` object. Returns a string. """ dictionary = dictionary or {} if isinstance(template_name, (list, tuple)): template = select_template(template_name) else: template = get_template(template_name) if context_instance: context_instance.update(dictionary) else: context_instance = dictionary return template.render(context_instance) def select_template(template_name_list): "Given a list of template names, returns the first that can be loaded." for template_name in template_name_list: try: return get_template(template_name) except TemplateNotFound: continue # If we get here, none of the templates could be loaded raise TemplateNotFound(', '.join(template_name_list))
sellberg/SACLA2016A8015
scripts/09_make_dark.py
Python
bsd-2-clause
3,025
0.018182
#!/home/software/SACLA_tool/bin/python2.7 import numpy as np import h5py import matplotlib import matplotlib.pyplot as plt import argparse import time #import pandas as pd import sys from argparse import ArgumentParser parser = ArgumentParser() parser = ArgumentParser(description="Plot intense ice shots") parser.add_argument("-run", "--run-number", type=int, dest="run", required=True, help="run to process") parser.add_argument("-exp", "--exp-year", type=int, dest="exp", default=2016, help="experimental year to compress (default: 2016)") parser.add_argument("-multi", "--multi-run", action="store_true", dest="multi", required=False, default=False, help="process multi-file run converted using DataConvert4") parser.add_argument("-tag", "--output-tag", type=str, dest="tag", default="run", help="tag for output folder (default: run)") parser.add_argument("-o", "--output-flag", type=str, dest="outputFlag", help="where to process runs. 'W' refers to /work/perakis/ and 'UD' refers to '/UserData/fperakis' (default: UD)", choices=['W','UD'], default='UD') args = parser.parse_args() # -- default parameters file_folder = '/UserData/fperakis/2016_6/%s%d/'%(args.tag,args.run) # h5 files folder src_folder = '/home/fperakis/2016_06/git/SACLA2016A8015/src/' # src files folder adu_gain = 75.0 # adu/photon @ 5 keV # -- files and folders file_name = '%d.h5'%(args.run) file_path = file_folder+file_name sys.path.insert(0, src_folder) from img_class import * # -- import data fh5 = h5py.File(file_path, 'r') run_key = [ k for k in fh5.keys() if k.startswith('run_') ][0] tags = fh5['/%s/detector_2d_assembled_1'%run_key].keys()[1:] # -- image generator img_gen = ( fh5['%s/detector_2d_assembled_1/%s/detector_data'%(run_key,tag) ].value for tag in tags ) num_im = len(tags) mean_int = np.zeros(num_im) # -- average image im_avg = img_gen.next() mean_int[0] = np.average(im_avg.flatten()) i=1 for im_next in img_gen: t1 = time.time() im_avg += im_next mean_int[i] = np.average(im_next.flatten()) print 'R.%d | M.%.1f ADU | S.%d/%d | %.1f Hz'%(args.run,mean_
int[i],i,num_im,1.0/(time.time() - t1)) i += 1 im_avg /= num_im # -- save dark np.save(file_folder+'%d_dark.npy'%args.run, im_avg) # -- run mean total_mean = np.average(im_avg.flatten(
)) # -- mean hist hist_bins = np.arange(np.floor(mean_int.min()), np.ceil(mean_int.max()) + 2, 2) - 1 hist, hist_bins = np.histogram(mean_int, bins=hist_bins) hist_bins_center = [(hist_bins[i] + hist_bins[i+1])/2.0 for i in range(len(hist_bins) - 1)] # -- plot #plt.figure() #plt.plot(hist_bins_center, hist) #plt.title('r.%d - mean intensity histogram'%args.run) #plt.xlabel('mean intensity [ADU]') #plt.ylabel('number of shots') #plt.savefig(file_folder+'%d_hist.png'%args.run) # -- plot title = 'r.%d - average %d dark shots'%(args.run,num_im) i = img_class(im_avg, title) plt.savefig(file_folder+'%d_dark.png'%args.run) i.draw_img()
chtyim/cdap
cdap-docs/faqs/source/conf.py
Python
apache-2.0
603
0.008292
# -*- coding: utf-8 -*- import sys import os # Import the common config file # Note that paths in the common config are interpreted as if they were # in the location of this file sys.path.insert(0, os.path.
abspath('../../_common')) from common_conf import * # Override the common config html_short_title_toc = manuals_dict["faqs"] html_short_title = u'CDAP %s' % html_short_title_toc html_context = {"html_short_title_toc":ht
ml_short_title_toc} # Remove this guide from the mapping as it will fail as it has been deleted by clean intersphinx_mapping.pop("faqs", None) html_theme = 'cdap-faqs'
Eksmo/calibre
src/calibre/ebooks/rb/rbml.py
Python
gpl-3.0
7,383
0.002844
# -*- coding: utf-8 -*- __license__ = 'GPL 3' __copyright__ = '2009, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' ''' Transform OEB content into RB compatible markup. ''' import re from calibre import prepare_string_for_xml from calibre.ebooks.rb import unique_name TAGS = [ 'b', 'big', 'blockquote', 'br', 'center', 'code', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'li', 'ol', 'p', 'pre', 'small', 'sub', 'sup', 'ul', ] LINK_TAGS = [ 'a', ] IMAGE_TAGS = [ 'img', ] STYLES = [ ('font-weight', {'bold' : 'b', 'bolder' : 'b'}), ('font-style', {'italic' : 'i'}), ('text-align', {'center' : 'center'}), ] class RBMLizer(object): def __init__(self, log, name_map={}): self.log = log self.name_map = name_map self.link_hrefs = {} def extract_content(self, oeb_book, opts): self.log.info('Converting XHTML to RB markup...') self.oeb_book = oeb_book self.opts = opts return self.mlize_spine() def mlize_spine(self): self.link_hrefs = {} output = [u'<HTML><HEAD><TITLE></TITLE></HEAD><BODY>'] output.append(self.get_cover_page()) output.append(u'ghji87yhjko0Caliblre-toc-placeholder-for-insertion-later8ujko0987yjk') output.append(self.get_text()) output.append(u'</BODY></HTML>') output = ''.join(output).replace(u'ghji87yhjko0Caliblre-toc-placeholder-for-insertion-later8ujko0987yjk', self.get_toc()) output = self.clean_text(output) return output def get_cover_page(self): from calibre.ebooks.oeb.stylizer import Stylizer from calibre.ebooks.oeb.base import XHTML output = u'' if 'cover' in self.oeb_book.guide: if self.name_map.get(self.oeb_book.guide['cover'].href, None): output += '<IMG SRC="%s">' % self.name_map[self.oeb_book.guide['cover'].href] if 'titlepage' in self.oeb_book.guide: self.log.debug('Generating cover page...') href = self.oeb_book.guide['titlepage'].href item = self.oeb_book.manifest.hrefs[href] if item.spine_position is None: stylizer = Stylizer(item.data, item.href, self.oeb_book, self.opts, self.opts.output_profile) output += ''.join(self.dump_text(item.data.find(XHTML('body')), stylizer, item)) return output def get_toc(self): toc = [u''] if self.opts.inline_toc: self.log.debug('Generating table of contents...') toc.append(u'<H1>%s</H1><UL>\n' % _('Table of Contents:')) for item in self.oeb_book.toc: if item.href in self.link_hrefs.keys(): toc.append('<LI><A HREF="#%s">%s</A></LI>\n' % (self.link_hrefs[item.href], item.title)) else: self.oeb.warn('Ignoring toc item: %s not found in document.' % item) toc.append('</UL>') return ''.join(toc) def get_text(self): from calibre.ebooks.oeb.stylizer import St
ylizer from calibre.ebooks.oeb.base import XHTML output = [u''] for item in self.oeb_book.spine: self.log.deb
ug('Converting %s to RocketBook HTML...' % item.href) stylizer = Stylizer(item.data, item.href, self.oeb_book, self.opts, self.opts.output_profile) output.append(self.add_page_anchor(item)) output += self.dump_text(item.data.find(XHTML('body')), stylizer, item) return ''.join(output) def add_page_anchor(self, page): return self.get_anchor(page, '') def get_anchor(self, page, aid): aid = '%s#%s' % (page.href, aid) if aid not in self.link_hrefs.keys(): self.link_hrefs[aid] = 'calibre_link-%s' % len(self.link_hrefs.keys()) aid = self.link_hrefs[aid] return u'<A NAME="%s"></A>' % aid def clean_text(self, text): # Remove anchors that do not have links anchors = set(re.findall(r'(?<=<A NAME=").+?(?="></A>)', text)) links = set(re.findall(r'(?<=<A HREF="#).+?(?=">)', text)) for unused in anchors.difference(links): text = text.replace('<A NAME="%s"></A>' % unused, '') return text def dump_text(self, elem, stylizer, page, tag_stack=[]): from calibre.ebooks.oeb.base import XHTML_NS, barename, namespace if not isinstance(elem.tag, basestring) \ or namespace(elem.tag) != XHTML_NS: return [u''] text = [u''] style = stylizer.style(elem) if style['display'] in ('none', 'oeb-page-head', 'oeb-page-foot') \ or style['visibility'] == 'hidden': return [u''] tag = barename(elem.tag) tag_count = 0 # Process tags that need special processing and that do not have inner # text. Usually these require an argument if tag in IMAGE_TAGS: if elem.attrib.get('src', None): if page.abshref(elem.attrib['src']) not in self.name_map.keys(): self.name_map[page.abshref(elem.attrib['src'])] = unique_name('%s' % len(self.name_map.keys()), self.name_map.keys()) text.append('<IMG SRC="%s">' % self.name_map[page.abshref(elem.attrib['src'])]) rb_tag = tag.upper() if tag in TAGS else None if rb_tag: tag_count += 1 text.append('<%s>' % rb_tag) tag_stack.append(rb_tag) # Anchors links if tag in LINK_TAGS: href = elem.get('href') if href: href = page.abshref(href) if '://' not in href: if '#' not in href: href += '#' if href not in self.link_hrefs.keys(): self.link_hrefs[href] = 'calibre_link-%s' % len(self.link_hrefs.keys()) href = self.link_hrefs[href] text.append('<A HREF="#%s">' % href) tag_count += 1 tag_stack.append('A') # Anchor ids id_name = elem.get('id') if id_name: text.append(self.get_anchor(page, id_name)) # Processes style information for s in STYLES: style_tag = s[1].get(style[s[0]], None) if style_tag: style_tag = style_tag.upper() tag_count += 1 text.append('<%s>' % style_tag) tag_stack.append(style_tag) # Proccess tags that contain text. if hasattr(elem, 'text') and elem.text: text.append(prepare_string_for_xml(elem.text)) for item in elem: text += self.dump_text(item, stylizer, page, tag_stack) close_tag_list = [] for i in range(0, tag_count): close_tag_list.insert(0, tag_stack.pop()) text += self.close_tags(close_tag_list) if hasattr(elem, 'tail') and elem.tail: text.append(prepare_string_for_xml(elem.tail)) return text def close_tags(self, tags): text = [u''] for i in range(0, len(tags)): tag = tags.pop() text.append('</%s>' % tag) return text
tihlde/TIHLDEscripts
userscripts/lan_users_ipa.py
Python
apache-2.0
1,614
0.001239
# coding: utf-8 import os import sys import time import tihldelib.userlib as lib __author__ = 'Harald Floor Wilhelmsen' def get_useramount(): formatstring =
'Format: python lan_users.py useramount' # Checking if there are sufficient arguments, if not exit if len(sys.argv) != 2: sys.exit('Invaild number of arguments. ' + formatstring) user_amount = sys.argv[1].strip() if not user_amount.isdigit(): sys.exit('Wrong number-format. ' + formatstring) return user_amount, int(input('Start id of user id')) def create_lan_users(): user_amount, start_id = get_useram
ount() response = str(input(str(user_amount) + ' users to add. Continue? [y/N]')) if response.replace('\n', '').strip() != 'y': return 'User called exit before adding users' api = lib.get_ipa_api() username_format = 'lan-{}' credentials_file_path = '/root/lan_users{}.txt'.format(time.time()) with open(credentials_file_path, 'a') as credentials_file: for i in range(start_id, start_id + user_amount): username = username_format.format(i) user_info = lib.add_user_ipa(username=username, firstname='Lan', lastname='Lanesen', groupid=1002, homedir_base='/home/lan/', api=api) credentials_file.write('Brukernavn: {0}\nPassord: {1}\n\n'.format(username, user_info[1])) def main(): euid = os.geteuid() if euid != 0: print('Needs to be run as root. Re-run with sudo') return msg = create_lan_users() if msg: print(msg) return main()
ct-23/home-assistant
homeassistant/components/binary_sensor/mystrom.py
Python
apache-2.0
3,028
0
""" Support for the myStrom buttons. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.mystrom/ """ import asyncio import logging from homeassistant.components.binary_sensor import (BinarySensorDevice, DOMAIN) from homeassistant.components.http import HomeAssistantView from homeassistant.const import HTTP_UNPROCESSABLE_ENTITY _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['http'] @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up myStrom Binary Sensor.""" hass.http.register_view(MyStromView(async_add_devices)) return True class MyStromView(HomeAssistantView): """View to handle requests from myStrom buttons.""" url = '/api/mystrom' name = 'api:mystrom' def __init__(self, add_devices): """Initialize the myStrom URL endpoint.""" self.buttons = {} self.add_devices = add_devices @asyncio.coroutine def get(self, request): """The GET request received from a myStrom
button.""" res = yield from self._handle(reques
t.app['hass'], request.query) return res @asyncio.coroutine def _handle(self, hass, data): """Handle requests to the myStrom endpoint.""" button_action = list(data.keys())[0] button_id = data[button_action] entity_id = '{}.{}_{}'.format(DOMAIN, button_id, button_action) if button_action not in ['single', 'double', 'long', 'touch']: _LOGGER.error( "Received unidentified message from myStrom button: %s", data) return ("Received unidentified message: {}".format(data), HTTP_UNPROCESSABLE_ENTITY) if entity_id not in self.buttons: _LOGGER.info("New myStrom button/action detected: %s/%s", button_id, button_action) self.buttons[entity_id] = MyStromBinarySensor( '{}_{}'.format(button_id, button_action)) hass.async_add_job(self.add_devices, [self.buttons[entity_id]]) else: new_state = True if self.buttons[entity_id].state == 'off' \ else False self.buttons[entity_id].async_on_update(new_state) class MyStromBinarySensor(BinarySensorDevice): """Representation of a myStrom button.""" def __init__(self, button_id): """Initialize the myStrom Binary sensor.""" self._button_id = button_id self._state = None @property def name(self): """Return the name of the sensor.""" return self._button_id @property def should_poll(self): """No polling needed.""" return False @property def is_on(self): """Return true if the binary sensor is on.""" return self._state def async_on_update(self, value): """Receive an update.""" self._state = value self.hass.async_add_job(self.async_update_ha_state())
vritant/subscription-manager
src/subscription_manager/gui/firstboot/rhsm_login.py
Python
gpl-2.0
19,013
0.001788
import gettext import socket import sys import logging _ = lambda x: gettext.ldgettext("rhsm", x) import gtk gtk.gdk.threads_init() import rhsm sys.path.append("/usr/share/rhsm") # enable logging for firstboot from subscription_manager import logutil logutil.init_logger() log = logging.getLogger("rhsm-app." + __name__) # neuter linkify in firstboot from subscription_manager.gui.utils import running_as_firstboot running_as_firstboot() from subscription_manager.injectioninit import init_dep_injection init_dep_injection() from subscription_manager.injection import PLUGIN_MANAGER, IDENTITY, require from subscription_manager.facts import Facts from subscription_manager.hwprobe import Hardware from subscription_manager.gui.firstboot_base import RhsmFirstbootModule from subscription_manager.gui import managergui from subscription_manager.gui import registergui from subscription_manager.gui.utils import handle_gui_exception from subscription_manager.gui.autobind import \ ServiceLevelNotSupportedException, NoProductsException, \ AllProductsCoveredException from subscription_manager import managerlib from rhsm.connection import RestlibException from rhsm.utils import remove_scheme sys.path.append("/usr/share/rhn") rhn_config = None try: from up2date_client import config as rhn_config except ImportError: log.debug("no rhn-client-tools modules could be imported") MANUALLY_SUBSCRIBE_PAGE = 11 class SelectSLAScreen(registergui.SelectSLAScreen): """ override the default SelectSLAScreen to jump to the manual subscribe page. """ def _on_get_service_levels_cb(self, result, error=None): if error is not None: if isinstance(error[1], ServiceLevelNotSupportedException): message = _("Unable to auto-attach, server does not support " "service levels. Please run 'Subscription Manager' " "to manually attach a subscription.") self._parent.manual_message = message self._parent.pre_done(MANUALLY_SUBSCRIBE_PAGE) elif isinstance(error[1], NoProductsException): message = _("No installed products on system. No need to " "update subscriptions at this time.") self._parent.manual_message = message self._parent.pre_done(
MANUALLY_SUBSCRIBE_PAGE) elif isinstance(error[1], AllProductsCoveredException): message = _("All installed products are fully subscribed.") self._parent.manual_message = message self._parent.pre_done(MANUALLY_SUBSCRIBE_PAGE) else: handle_gui_exception(error, _("Error subscribing"), self._parent.window) self._parent.finish_registration(failed=True
) return (current_sla, unentitled_products, sla_data_map) = result self._parent.current_sla = current_sla if len(sla_data_map) == 1: # If system already had a service level, we can hit this point # when we cannot fix any unentitled products: if current_sla is not None and \ not self._can_add_more_subs(current_sla, sla_data_map): message = _("Unable to attach any additional subscriptions at " "current service level: %s") % current_sla self._parent.manual_message = message self._parent.pre_done(MANUALLY_SUBSCRIBE_PAGE) return self._dry_run_result = sla_data_map.values()[0] self._parent.pre_done(registergui.CONFIRM_SUBS_PAGE) elif len(sla_data_map) > 1: self._sla_data_map = sla_data_map self.set_model(unentitled_products, sla_data_map) self._parent.pre_done(registergui.DONT_CHANGE) else: message = _("No service levels will cover all installed products. " "Please run 'Subscription Manager' to manually " "attach subscriptions.") self._parent.manual_message = message self._parent.pre_done(MANUALLY_SUBSCRIBE_PAGE) class PerformRegisterScreen(registergui.PerformRegisterScreen): def _on_registration_finished_cb(self, new_account, error=None): if error is not None: handle_gui_exception(error, registergui.REGISTER_ERROR, self._parent.window) self._parent.finish_registration(failed=True) return try: managerlib.persist_consumer_cert(new_account) self._parent.backend.cs.force_cert_check() # Ensure there isn't much wait time if self._parent.activation_keys: self._parent.pre_done(registergui.REFRESH_SUBSCRIPTIONS_PAGE) elif self._parent.skip_auto_bind: message = _("You have opted to skip auto-attach.") self._parent.manual_message = message self._parent.pre_done(MANUALLY_SUBSCRIBE_PAGE) else: self._parent.pre_done(registergui.SELECT_SLA_PAGE) # If we get errors related to consumer name on register, # go back to the credentials screen where we set the # consumer name. See bz#865954 except RestlibException, e: handle_gui_exception(e, registergui.REGISTER_ERROR, self._parent.window) if e.code == 404 and self._parent.activation_keys: self._parent.pre_done(registergui.ACTIVATION_KEY_PAGE) if e.code == 400: self._parent.pre_done(registergui.CREDENTIALS_PAGE) except Exception, e: handle_gui_exception(e, registergui.REGISTER_ERROR, self._parent.window) self._parent.finish_registration(failed=True) def pre(self): # TODO: this looks like it needs updating now that we run # firstboot without rhn client tools. # Because the RHN client tools check if certs exist and bypass our # firstboot module if so, we know that if we reach this point and # identity certs exist, someone must have hit the back button. # TODO: i'd like this call to be inside the async progress stuff, # since it does take some time identity = require(IDENTITY) if identity.is_valid(): try: managerlib.unregister(self._parent.backend.cp_provider.get_consumer_auth_cp(), self._parent.identity.uuid) except socket.error, e: handle_gui_exception(e, e, self._parent.window) self._parent._registration_finished = False return registergui.PerformRegisterScreen.pre(self) class ManuallySubscribeScreen(registergui.Screen): widget_names = registergui.Screen.widget_names + ['title'] gui_file = "manually_subscribe" def __init__(self, parent, backend): super(ManuallySubscribeScreen, self).__init__(parent, backend) self.button_label = _("Finish") def apply(self): return registergui.FINISH def pre(self): if self._parent.manual_message: self.title.set_label(self._parent.manual_message) # XXX set message here. return False class moduleClass(RhsmFirstbootModule, registergui.RegisterScreen): def __init__(self): """ Create a new firstboot Module for the 'register' screen. """ RhsmFirstbootModule.__init__(self, # Firstboot module title # Note: translated title needs to be unique across all # firstboot modules, not just the rhsm ones. See bz #828042 _("Subscription Management Registration"), _("Subscription Registration"), 200.1, 109.10) backend = managergui.Backend() self.plugin_manager = require(PLUGIN_MANAGER) registergui.RegisterScreen.__init__(self, backend, Facts()) #insert our new screens screen = SelectSLAScreen(self, backend) screen.index = self._screens[regi
ATIX-AG/ansible
lib/ansible/modules/cloud/ovirt/ovirt_vms.py
Python
gpl-3.0
93,016
0.002795
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ovirt_vms short_description: Module to manage Virtual Machines in oVirt/RHV version_added: "2.2" author: - Ondra Machacek (@machacekondra) description: - This module manages whole lifecycle of the Virtual Machine(VM) in oVirt/RHV. - Since VM can hold many states in oVirt/RHV, this see notes to see how the states of the VM are handled. options: name: description: - Name of the Virtual Machine to manage. - If VM don't exists C(name) is required. Otherwise C(id) or C(name) can be used. id: description: - ID of the Virtual Machine to manage. state: description: - Should the Virtual Machine be running/stopped/present/absent/suspended/next_run/registered. When C(state) is I(registered) and the unregistered VM's name belongs to an already registered in engine VM in the same DC then we fail to register the unregistered template. - I(present) state will create/update VM and don't change its state if it already exists. - I(running) state will create/update VM and start it. - I(next_run) state updates the VM and if the VM has next run configuration it will be rebooted. - Please check I(notes) to more detailed description of states. - I(registered) is supported since 2.4. choices: [ absent, next_run, present, registered, running, stopped, suspended ] default: present cluster: description: - Name of the cluster, where Virtual Machine should be created. - Required if creating VM. allow_partial_import: description: - Boolean indication whether to allow partial registration of Virtual Machine when C(state) is registered. version_added: "2.4" vnic_profile_mappings: description:
- "Mapper which maps an external virtual NIC profile to one that exists in the engine when C(state) is registered. vnic_profile is described by the following dictionary:" - "C(sourc
e_network_name): The network name of the source network." - "C(source_profile_name): The prfile name related to the source network." - "C(target_profile_id): The id of the target profile id to be mapped to in the engine." version_added: "2.5" cluster_mappings: description: - "Mapper which maps cluster name between VM's OVF and the destination cluster this VM should be registered to, relevant when C(state) is registered. Cluster mapping is described by the following dictionary:" - "C(source_name): The name of the source cluster." - "C(dest_name): The name of the destination cluster." version_added: "2.5" role_mappings: description: - "Mapper which maps role name between VM's OVF and the destination role this VM should be registered to, relevant when C(state) is registered. Role mapping is described by the following dictionary:" - "C(source_name): The name of the source role." - "C(dest_name): The name of the destination role." version_added: "2.5" domain_mappings: description: - "Mapper which maps aaa domain name between VM's OVF and the destination aaa domain this VM should be registered to, relevant when C(state) is registered. The aaa domain mapping is described by the following dictionary:" - "C(source_name): The name of the source aaa domain." - "C(dest_name): The name of the destination aaa domain." version_added: "2.5" affinity_group_mappings: description: - "Mapper which maps affinty name between VM's OVF and the destination affinity this VM should be registered to, relevant when C(state) is registered." version_added: "2.5" affinity_label_mappings: description: - "Mappper which maps affinity label name between VM's OVF and the destination label this VM should be registered to, relevant when C(state) is registered." version_added: "2.5" lun_mappings: description: - "Mapper which maps lun between VM's OVF and the destination lun this VM should contain, relevant when C(state) is registered. lun_mappings is described by the following dictionary: - C(logical_unit_id): The logical unit number to identify a logical unit, - C(logical_unit_port): The port being used to connect with the LUN disk. - C(logical_unit_portal): The portal being used to connect with the LUN disk. - C(logical_unit_address): The address of the block storage host. - C(logical_unit_target): The iSCSI specification located on an iSCSI server - C(logical_unit_username): Username to be used to connect to the block storage host. - C(logical_unit_password): Password to be used to connect to the block storage host. - C(storage_type): The storage type which the LUN reside on (iscsi or fcp)" version_added: "2.5" reassign_bad_macs: description: - "Boolean indication whether to reassign bad macs when C(state) is registered." version_added: "2.5" template: description: - Name of the template, which should be used to create Virtual Machine. - Required if creating VM. - If template is not specified and VM doesn't exist, VM will be created from I(Blank) template. template_version: description: - Version number of the template to be used for VM. - By default the latest available version of the template is used. version_added: "2.3" use_latest_template_version: description: - Specify if latest template version should be used, when running a stateless VM. - If this parameter is set to I(yes) stateless VM is created. type: bool version_added: "2.3" storage_domain: description: - Name of the storage domain where all template disks should be created. - This parameter is considered only when C(template) is provided. - IMPORTANT - This parameter is not idempotent, if the VM exists and you specfiy different storage domain, disk won't move. version_added: "2.4" disk_format: description: - Specify format of the disk. - If C(cow) format is used, disk will by created as sparse, so space will be allocated for the volume as needed, also known as I(thin provision). - If C(raw) format is used, disk storage will be allocated right away, also known as I(preallocated). - Note that this option isn't idempotent as it's not currently possible to change format of the disk via API. - This parameter is considered only when C(template) and C(storage domain) is provided. choices: [ cow, raw ] default: cow version_added: "2.4" memory: description: - Amount of memory of the Virtual Machine. Prefix uses IEC 60027-2 standard (for example 1GiB, 1024MiB). - Default value is set by engine. memory_guaranteed: description: - Amount of minimal guaranteed memory of the Virtual Machine. Prefix uses IEC 60027-2 standard (for example 1GiB, 1024MiB). - C(memory_guaranteed) parameter can't be lower than C(memory) parameter. - Default value is set by engine. memory_max: description: - Upper bound of virtual machine mem
bblacey/FreeCAD-MacOS-CI
src/Mod/Path/PathScripts/PathStop.py
Python
lgpl-2.1
5,748
0.00174
# -*- coding: utf-8 -*- # *************************************************************************** # * * # * Copyright (c) 2015 Dan Falck <ddfalck@gmail.com> * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * 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 Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** ''' Used for CNC machine Stops for Path module. Create an Optional or Mandatory Stop.''' import FreeCAD import FreeCADGui import Path from PySide import QtCore, QtGui # Qt tanslation handling try: _encoding = QtGui.QApplication.UnicodeUTF8 def translate(context, text, disambig=None): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def translate(context, text, disambig=None): return QtGui.QApplication.translate(context, text, disambig) class Stop: def __init__(self,obj): obj.addProperty("App::PropertyEnumeration", "Stop", "Path", QtCore.QT_TRANSL
ATE_NOOP("App::Property","Add Optional or Manda
tory Stop to the program")) obj.Stop=['Optional', 'Mandatory'] obj.Proxy = self mode = 2 obj.setEditorMode('Placement', mode) def __getstate__(self): return None def __setstate__(self, state): return None def onChanged(self, obj, prop): pass # FreeCAD.ActiveDocument.recompute() def execute(self, obj): if obj.Stop == 'Optional': word = 'M1' else: word = 'M0' output = "" output = word + '\n' path = Path.Path(output) obj.Path = path class _ViewProviderStop: def __init__(self, vobj): # mandatory # obj.addProperty("App::PropertyFloat","SomePropertyName","PropertyGroup","Description of this property") vobj.Proxy = self mode = 2 vobj.setEditorMode('LineWidth', mode) vobj.setEditorMode('MarkerColor', mode) vobj.setEditorMode('NormalColor', mode) vobj.setEditorMode('ShowFirstRapid', mode) vobj.setEditorMode('DisplayMode', mode) vobj.setEditorMode('BoundingBox', mode) vobj.setEditorMode('Selectable', mode) vobj.setEditorMode('ShapeColor', mode) vobj.setEditorMode('Transparency', mode) vobj.setEditorMode('Visibility', mode) def __getstate__(self): # mandatory return None def __setstate__(self, state): # mandatory return None def getIcon(self): # optional return ":/icons/Path-Stop.svg" def onChanged(self, vobj, prop): # optional mode = 2 vobj.setEditorMode('LineWidth', mode) vobj.setEditorMode('MarkerColor', mode) vobj.setEditorMode('NormalColor', mode) vobj.setEditorMode('ShowFirstRapid', mode) vobj.setEditorMode('DisplayMode', mode) vobj.setEditorMode('BoundingBox', mode) vobj.setEditorMode('Selectable', mode) vobj.setEditorMode('ShapeColor', mode) vobj.setEditorMode('Transparency', mode) vobj.setEditorMode('Visibility', mode) class CommandPathStop: def GetResources(self): return {'Pixmap': 'Path-Stop', 'MenuText': QtCore.QT_TRANSLATE_NOOP("Path_Stop", "Stop"), 'Accel': "P, C", 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Path_Stop", "Add Optional or Mandatory Stop to the program")} def IsActive(self): if FreeCAD.ActiveDocument is not None: for o in FreeCAD.ActiveDocument.Objects: if o.Name[:3] == "Job": return True return False def Activated(self): FreeCAD.ActiveDocument.openTransaction( translate("Path_Stop", "Add Optional or Mandatory Stop to the program")) FreeCADGui.addModule("PathScripts.PathStop") snippet = ''' import Path import PathScripts from PathScripts import PathUtils prjexists = False obj = FreeCAD.ActiveDocument.addObject("Path::FeaturePython","Stop") PathScripts.PathStop.Stop(obj) PathScripts.PathStop._ViewProviderStop(obj.ViewObject) PathUtils.addToJob(obj) ''' FreeCADGui.doCommand(snippet) FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute() if FreeCAD.GuiUp: # register the FreeCAD command FreeCADGui.addCommand('Path_Stop', CommandPathStop()) FreeCAD.Console.PrintLog("Loading PathStop... done\n")
v-iam/azure-sdk-for-python
azure-servicefabric/azure/servicefabric/models/deployed_stateful_service_replica_info.py
Python
mit
3,502
0.001142
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .deployed_service_replica_info import DeployedServiceReplicaInfo class DeployedStatefulServiceReplicaInfo(DeployedServiceReplicaInfo): """Information about a stateful service replica deployed on a node. :param service_name: Full hierarchical name of the service in URI format starting with `fabric:`. :type service_name: str :param service_type_name: Name of the service type as specified in the service manifest. :type service_type_name: str :param service_manifest_name: The name of the service manifest in which this service type is defined. :type service_manifest_name: str :param code_package_name: The name of the code package that hosts this replica. :type code_package_name: str :param partition_id: :type partition_id: str :param replica_status: Possible values include: 'Invalid', 'I
nBuild', 'Standby', 'Ready', 'Down', 'Dropped' :type replica_status: str :param address: The last address returned by the replica in Open or ChangeRole. :type ad
dress: str :param service_package_activation_id: :type service_package_activation_id: str :param ServiceKind: Polymorphic Discriminator :type ServiceKind: str :param replica_id: Id of the stateful service replica. :type replica_id: str :param replica_role: Possible values include: 'Unknown', 'None', 'Primary', 'IdleSecondary', 'ActiveSecondary' :type replica_role: str """ _validation = { 'ServiceKind': {'required': True}, } _attribute_map = { 'service_name': {'key': 'ServiceName', 'type': 'str'}, 'service_type_name': {'key': 'ServiceTypeName', 'type': 'str'}, 'service_manifest_name': {'key': 'ServiceManifestName', 'type': 'str'}, 'code_package_name': {'key': 'CodePackageName', 'type': 'str'}, 'partition_id': {'key': 'PartitionID', 'type': 'str'}, 'replica_status': {'key': 'ReplicaStatus', 'type': 'str'}, 'address': {'key': 'Address', 'type': 'str'}, 'service_package_activation_id': {'key': 'ServicePackageActivationId', 'type': 'str'}, 'ServiceKind': {'key': 'ServiceKind', 'type': 'str'}, 'replica_id': {'key': 'ReplicaId', 'type': 'str'}, 'replica_role': {'key': 'ReplicaRole', 'type': 'str'}, } def __init__(self, service_name=None, service_type_name=None, service_manifest_name=None, code_package_name=None, partition_id=None, replica_status=None, address=None, service_package_activation_id=None, replica_id=None, replica_role=None): super(DeployedStatefulServiceReplicaInfo, self).__init__(service_name=service_name, service_type_name=service_type_name, service_manifest_name=service_manifest_name, code_package_name=code_package_name, partition_id=partition_id, replica_status=replica_status, address=address, service_package_activation_id=service_package_activation_id) self.replica_id = replica_id self.replica_role = replica_role self.ServiceKind = 'Stateful'
sanguinariojoe/FreeCAD
src/Mod/Path/PathScripts/PathHop.py
Python
lgpl-2.1
5,422
0.001844
# -*- coding: utf-8 -*- # *************************************************************************** # * Copyright (c) 2014 Yorik van Havre <yorik@uncreated.net> * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * 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 Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** import FreeCAD import FreeCADGui import Path from PySide import QtCore __doc__ = """Path Hop object and FreeCAD command""" # Qt translation handling def translate(context, text, disambig=None): return QtCore.QCoreApplication.translate(context, text, disambig) class ObjectHop: def __init__(self, obj): obj.addProperty("App::PropertyLink", "NextObject", "Path", QtCore.QT_TRANSLATE_NOOP("App::Property","The object to be reached by this hop")) obj.addProperty("App::PropertyDistance", "HopHeight", "Path", QtCore.QT_TRANSLATE_NOOP("App::Property","The Z height of the hop")) obj.Proxy = self def __getstate__(self): return None def __setstate__(self
, state): return None def execute(self, obj): nextpoint = FreeCAD.Vector() if obj.NextObject: if o
bj.NextObject.isDerivedFrom("Path::Feature"): # look for the first position of the next path for c in obj.NextObject.Path.Commands: if c.Name in ["G0", "G00", "G1", "G01", "G2", "G02", "G3", "G03"]: nextpoint = c.Placement.Base break # absolute coords, millimeters, cancel offsets output = "G90\nG21\nG40\n" # go up to the given height output += "G0 Z" + str(obj.HopHeight.Value) + "\n" # go horizontally to the position of nextpoint output += "G0 X" + str(nextpoint.x) + " Y" + str(nextpoint.y) + "\n" # print output path = Path.Path(output) obj.Path = path class ViewProviderPathHop: def __init__(self, vobj): self.Object = vobj.Object vobj.Proxy = self def attach(self, vobj): self.Object = vobj.Object def getIcon(self): return ":/icons/Path_Hop.svg" def __getstate__(self): return None def __setstate__(self, state): return None class CommandPathHop: def GetResources(self): return {'Pixmap': 'Path_Hop', 'MenuText': QtCore.QT_TRANSLATE_NOOP("Path_Hop", "Hop"), 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Path_Hop", "Creates a Path Hop object")} def IsActive(self): if FreeCAD.ActiveDocument is not None: for o in FreeCAD.ActiveDocument.Objects: if o.Name[:3] == "Job": return True return False def Activated(self): # check that the selection contains exactly what we want selection = FreeCADGui.Selection.getSelection() if len(selection) != 1: FreeCAD.Console.PrintError( translate("Path_Hop", "Please select one path object")+"\n") return if not selection[0].isDerivedFrom("Path::Feature"): FreeCAD.Console.PrintError( translate("Path_Hop", "The selected object is not a path")+"\n") return FreeCAD.ActiveDocument.openTransaction( translate("Path_Hop", "Create Hop")) FreeCADGui.addModule("PathScripts.PathHop") FreeCADGui.addModule("PathScripts.PathUtils") FreeCADGui.doCommand( 'obj = FreeCAD.ActiveDocument.addObject("Path::FeaturePython","Hop")') FreeCADGui.doCommand('PathScripts.PathHop.ObjectHop(obj)') FreeCADGui.doCommand( 'PathScripts.PathHop.ViewProviderPathHop(obj.ViewObject)') FreeCADGui.doCommand( 'obj.NextObject = FreeCAD.ActiveDocument.' + selection[0].Name) FreeCADGui.doCommand('PathScripts.PathUtils.addToJob(obj)') FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute() if FreeCAD.GuiUp: # register the FreeCAD command FreeCADGui.addCommand('Path_Hop', CommandPathHop()) FreeCAD.Console.PrintLog("Loading PathHop... done\n")
NaohiroTamura/python-ironicclient
ironicclient/tests/functional/test_help_msg.py
Python
apache-2.0
2,193
0
# Copyright (c) 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless 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. from ironicclient.tests.functional import base class IronicClientHelp(base.FunctionalTestBase): """Test for python-ironicclient help messages.""" def test_ironic_help(self): """Check Ironic client main help message contents.""" caption = ("Command-line interface to the " "OpenStack Bare Metal Provisioning API.") subcommands = { 'bash-completion', 'chassis-create', 'chassis-delete', 'chassis-list', 'chassis-node-list', 'chassis-show', 'chassis-update', 'driver-list', 'driver-properties', 'driver-show', 'driver-vendor-passthru', 'help', 'node-create', 'node-delete', 'node-get-boot-device', 'node-g
et-console', 'node-
get-supported-boot-devices', 'node-list', 'node-port-list', 'node-set-boot-device', 'node-set-console-mode', 'node-set-maintenance', 'node-set-power-state', 'node-set-provision-state', 'node-show', 'node-show-states', 'node-update', 'node-validate', 'node-vendor-passthru', 'port-create', 'port-delete', 'port-list', 'port-show', 'port-update' } output = self._ironic('help', flags='', params='') self.assertIn(caption, output) for string in subcommands: self.assertIn(string, output)
bitmovin/bitmovin-python
bitmovin/resources/models/encodings/live/auto_restart_configuration.py
Python
unlicense
785
0.003822
from bitmovin.utils import Serializable class AutoRestartConfiguration(Serializable): def __init__(self, segments_written_timeout: float = None, bytes_written_timeout: float = None, frames_written_timeout: float = None, hls_manifests_update_timeout: float = None, dash_manifests_update_timeout: float = None, schedule_expression: str = None): super().__init__() self.segmentsWrittenTimeout = segments_written_timeout self.bytesWrittenTimeout = bytes_writte
n_timeout self.framesWrittenTimeout = frames_written_timeout self.hlsManifestsUpdateTimeout = hls_manifests_update_timeout self.dashManifestsUpdateTimeout = dash_manifests_update_timeout self.scheduleExpression = schedule_expression
adexin/Python-Machine-Learning-Samples
Other_samples/Gradient_check/gradient_check.py
Python
mit
7,033
0.002702
import numpy as np from Other_samples.testCases import * from Other_samples.Gradient_check.gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, \ gradients_to_vector def forward_propagation(x, theta): """ Implement the linear forward propagation (compute J) presented in Figure 1 (J(theta) = theta * x) Arguments: x -- a real-valued input theta -- our parameter, a real number as well Returns: J -- the value of function J, computed using the formula J(theta) = theta * x """ J = theta * x return J x, theta = 2, 4 J = forward_propagation(x, theta) print("J = " + str(J)) def backward_propagation(x, theta): """ Computes the derivative of J with respect to theta (see Figure 1). Arguments: x -- a real-valued input theta -- our parameter, a real number as well Returns: dtheta -- the gradient of the cost with respect to theta """ dtheta = x return dtheta x, theta = 2, 4 dtheta = backward_propagation(x, theta) print("dtheta = " + str(dtheta)) def gradient_check(x, theta, epsilon=1e-7): """ Implement the backward propagation presented in Figure 1. Arguments: x -- a real-valued input theta -- our parameter, a real number as well epsilon -- tiny shift to the input to compute approximated gradient with formula(1) Returns: difference -- difference (2) between the approximated gradient and the backward propagation gradient """ thetaplus = theta + epsilon # Step 1 thetaminus = theta - epsilon # Step 2 J_plus = forward_propagation(x, thetaplus) # Step 3 J_minus = forward_propagation(x, thetaminus) # Step 4 gradapprox = (J_plus - J_minus) / (2 * epsilon) # Step 5 grad = backward_propagation(x, gradapprox) numerator = np.linalg.norm(grad - gradapprox) # Step 1' denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox) # Step 2' difference = numerator / denominator # Step 3' if difference < 1e-7: print("The gradient is correct!") else: print("The gradient is wrong!") return difference x, theta = 2, 4 difference = gradient_check(x, theta) print("difference = " + str(difference)) def forward_propagation_n(X, Y, parameters): """ Implements the forward propagation (and computes the cost) presented in Figure 3. Arguments: X -- training set for m examples Y -- labels for m examples parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "
b3": W1 -- weight matrix of shape (5, 4) b1 -- bias vector of shape (5, 1) W2 -- weight matrix of shape (3, 5) b2 -- bias vector of shape (3, 1) W3 -- weight matrix of shape (1, 3) b3 -- bias vector of shape (1, 1) Returns: cost -- the cost function (logistic cost
for one example) """ # retrieve parameters m = X.shape[1] W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] W3 = parameters["W3"] b3 = parameters["b3"] # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID Z1 = np.dot(W1, X) + b1 A1 = relu(Z1) Z2 = np.dot(W2, A1) + b2 A2 = relu(Z2) Z3 = np.dot(W3, A2) + b3 A3 = sigmoid(Z3) # Cost logprobs = np.multiply(-np.log(A3), Y) + np.multiply(-np.log(1 - A3), 1 - Y) cost = 1. / m * np.sum(logprobs) cache = (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) return cost, cache def backward_propagation_n(X, Y, cache): """ Implement the backward propagation presented in figure 2. Arguments: X -- input datapoint, of shape (input size, 1) Y -- true "label" cache -- cache output from forward_propagation_n() Returns: gradients -- A dictionary with the gradients of the cost with respect to each parameter, activation and pre-activation variables. """ m = X.shape[1] (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache dZ3 = A3 - Y dW3 = 1. / m * np.dot(dZ3, A2.T) db3 = 1. / m * np.sum(dZ3, axis=1, keepdims=True) dA2 = np.dot(W3.T, dZ3) dZ2 = np.multiply(dA2, np.int64(A2 > 0)) dW2 = 1. / m * np.dot(dZ2, A1.T) db2 = 1. / m * np.sum(dZ2, axis=1, keepdims=True) dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, np.int64(A1 > 0)) dW1 = 1. / m * np.dot(dZ1, X.T) db1 = 1. / m * np.sum(dZ1, axis=1, keepdims=True) gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3, "dA2": dA2, "dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1, "dZ1": dZ1, "dW1": dW1, "db1": db1} return gradients def gradient_check_n(parameters, gradients, X, Y, epsilon=1e-7): """ Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_n Arguments: parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3": grad -- output of backward_propagation_n, contains gradients of the cost with respect to the parameters. x -- input datapoint, of shape (input size, 1) y -- true "label" epsilon -- tiny shift to the input to compute approximated gradient with formula(1) Returns: difference -- difference (2) between the approximated gradient and the backward propagation gradient """ # Set-up variables parameters_values, _ = dictionary_to_vector(parameters) grad = gradients_to_vector(gradients) num_parameters = parameters_values.shape[0] J_plus = np.zeros((num_parameters, 1)) J_minus = np.zeros((num_parameters, 1)) gradapprox = np.zeros((num_parameters, 1)) # Compute gradapprox for i in range(num_parameters): thetaplus = np.copy(parameters_values) # Step 1 thetaplus[i][0] = thetaplus[i] + epsilon # Step 2 J_plus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaplus)) # Step 3 thetaminus = np.copy(parameters_values) # Step 1 thetaminus[i][0] = thetaminus[i] - epsilon # Step 2 J_minus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaminus)) # Step 3 gradapprox[i] = (J_plus[i] - J_minus[i]) / (2 * epsilon) numerator = np.linalg.norm(grad - gradapprox) # Step 1' denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox) # Step 2' difference = numerator / denominator # Step 3' if difference > 1e-7: print( "\033[93m" + "There is a mistake in the backward propagation! difference = " + str(difference) + "\033[0m") else: print( "\033[92m" + "Your backward propagation works perfectly fine! difference = " + str(difference) + "\033[0m") return difference X, Y, parameters = gradient_check_n_test_case() cost, cache = forward_propagation_n(X, Y, parameters) gradients = backward_propagation_n(X, Y, cache) difference = gradient_check_n(parameters, gradients, X, Y)
saintdragon2/python-3-lecture-2015
civil_mid_final/알았조/tetris a.py
Python
mit
15,222
0.004222
import random, time, pygame, sys from pygame.locals import * FPS = 25 WINDOWWIDTH = 640 WINDOWHEIGHT = 480 BOXSIZE = 20 BOARDWIDTH = 10 BOARDHEIGHT = 20 BLANK = '.' MOVESIDEWAYSFREQ = 0.15 MOVEDOWNFREQ = 0.1 XMARGIN = int((WINDOWWIDTH - BOARDWIDTH * BOXSIZE) / 2) TOPMARGIN = WINDOWHEIGHT - (BOARDHEIGHT * BOXSIZE) - 5 WHITE = (255, 255, 255) GRAY = (185, 185, 185) BLACK = ( 0, 0, 0) RED = (155, 0, 0) LIGHTRED = (175, 20, 20) GREEN = ( 0, 155, 0) LIGHTGREEN = ( 20, 175, 20) BLUE = ( 0, 0, 155) LIGHTBLUE = ( 20, 20, 175) YELLOW = (155, 155, 0) LIGHTYELLOW = (175, 175, 20) PURPLE = (160, 32, 240) LIGHTPURPLE = (188, 100, 104) BORDERCOLOR = WHITE BGCOLOR = GRAY TEXTCOLOR = WHITE TEXTSHADOWCOLOR = BLACK COLORS = ( BLUE, GREEN, RED, YELLOW, PURPLE) LIGHTCOLORS = (LIGHTBLUE, LIGHTGREEN, LIGHTRED, LIGHTYELLOW, LIGHTPURPLE) assert len(COLORS) == len(LIGHTCOLORS) TEMPLATEWIDTH = 5 TEMPLATEHEIGHT = 5 tetris_img = pygame.image.load('tetris_00.jpg') tetris = pygame.transform.scale(tetris_img, (WINDOWWIDTH, WINDOWHEIGHT)) S_SHAPE_TEMPLATE = [['.....', '.....', '..OO.', '.OO..', '.....'], ['.....', '..O..', '..OO.', '...O.', '.....']] Z_SHAPE_TEMPLATE = [['.....', '.....', '.OO..', '..OO.', '.....'], ['.....', '..O..', '.OO..', '.O...', '.....']] I_SHAPE_TEMPLATE = [['..O..', '..O..', '..O..', '..O..', '.....'], ['.....', '.....', 'OOOO.', '.....', '.....']] O_SHAPE_TEMPLATE = [['.....', '.....', '.OO..', '.OO..', '.....']] J_SHAPE_TEMPLATE = [['.....', '.O...', '.OOO.', '.....', '.....'], ['.....', '..OO.', '..O..', '..O..', '.....'], ['.....', '.....', '.OOO.', '...O.', '.....'], ['.....', '..O..', '..O..', '.OO..', '.....']] L_SHAPE_TEMPLATE = [['.....', '...O.', '.OOO.', '.....', '.....'], ['.....', '..O..', '..O..', '..OO.', '.....'], ['.....', '.....', '.OOO.', '.O...', '.....'], ['.....', '.OO..', '..O..', '..O..', '.....']] T_SHAPE_TEMPLATE = [['.....', '..O..', '.OOO.', '.....', '.....'], ['.....', '..O..', '..OO.', '..O..', '.....'], ['.....', '.....', '.OOO.', '..O..', '.....'], ['.....', '..O..', '.OO..', '..O..', '.....']] PIECES = {'S': S_SHAPE_TEMPLATE, 'Z': Z_SHAPE_TEMPLATE, 'J': J_SHAPE_TEMPLATE, 'L': L_SHAPE_TEMPLATE, 'I': I_SHAPE_TEMPLATE, 'O': O_SHAPE_TEMPLATE, 'T': T_SHAPE_TEMPLATE} def main(): global FPSCLOCK, DISPLAYSURF, BASICFONT, BIGFONT pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) BASICFONT = pygame.font.Font('aa.ttf', 18) BIGFONT = pygame.font.Font('aa.ttf', 100) pygame.display.set_caption('OK! 테트리스') DISPLAYSURF.blit(tetris, (0,0)) showTextScreen('OK! 테트리스') while True: if random.randint(0, 1) == 0: pygame.mixer.music.load('summer.mp3') else: pygame.mixer.music.load('summer.mp3') pygame.mixer.music.play(-1, 0.0) runGame() pygame.mixer.music.stop() showTextScreen('죽었죠!') def runGame(): board = getBlankBoard() lastMoveDownTime = time.time() lastMoveSidewaysTime = time.time() lastFallTime = time.time() movingDown = False movingLeft = False movingRight = False score = 0 level, fallFreq = calculateLevelAndFallFreq(score) fallingPiece = getNewPiece() nextPiece = getNewPiece() while True: if fallingPiece == None: fallingPiece = nextPiece nextPiece = getNewPiece() lastFallTime = time.time() if not isValidPosition(board, fallingPiece): return checkForQuit() for event in pygame.event.get(): if event.type == KEYUP: if (event.key == K_p): DISPLAYSURF.fill(BGCOLOR) pygame.mixer.music.stop() showTextScreen('중지') pygame.mixer.music.play(-1, 0.0) lastFallTime = time.time() lastMoveDownTime = time.time() lastMoveSidewaysTime = time.time() elif (event.key == K_LEFT or event.key == K_a): movingLeft = False elif (event.key == K_RIGHT or event.key == K_d): movingRight = False elif (event.key == K_DOWN or event.key == K_s): movingDown = False elif event.type == KEYDOWN: if (event.key == K_LEFT or event.key == K_a) and isValidPosition(board, fallingPiece, adjX=-1): fallingPiece['x'] -= 1 movingLeft = True movingRight = False lastMoveSidewaysTime = time.time() elif (event.key == K_RIGHT or event.key == K_d) and isValidPosition(board, fallingPiece, adjX=1): fallingPiece['x'] += 1 movingRight = True movingLeft = False lastMoveSidewaysTime = time.time() elif (event.key == K_UP or event.key == K_w): fallingPiece['rotation'] = (fallingPiece['rotation'] + 1) % len(PIECES[fallingPiece['shape']]) if not isValidPosition(board, fallingPiece): fallingPiece['rotation'] = (fallingPiece['rotation'] - 1) % len(PIECES[fallingPiece['shape']]) elif (event.key == K_q): fallingPiece['rotation'] = (fallingPiece['rotation'] - 1) % len(PIECES[fallingPiece['shape']]) if not isValidPosition(board, fallingPiece): falli
ngPiece['rot
ation'] = (fallingPiece['rotation'] + 1) % len(PIECES[fallingPiece['shape']]) elif (event.key == K_DOWN or event.key == K_s): movingDown = True if isValidPosition(board, fallingPiece, adjY=1): fallingPiece['y'] += 1 lastMoveDownTime = time.time() elif event.key == K_SPACE: movingDown = False movingLeft = False movingRight = False for i in range(1, BOARDHEIGHT): if not isValidPosition(board, f
normalnorway/normal.no
django/apps/cms/urls.py
Python
gpl-3.0
831
0.009627
from django.conf.urls import url from django.contrib.auth.decorators import permission_required from . import views urlpatterns = [ url (r'^file/select/$', views.FileSelect.as_view(), name='file-select'),
# raise_exception=True => 403 Forbidden instead of redirect to /admin url (r'^page/(?P<pk>\d+)/update/$', permission_required ('cms.change_page', raise_exception=True)( views.PageUpdate.as_view()), name='page-update'), url (r'^content/(?P<pk>\d+)/update/$', permission_required ('cms.change_content', raise_exception=True)( views.ContentUpdate.as_view()), name='content-update'), url (r'^info/$', views.InfoLi
st.as_view(), name='info-list'), url (r'^info/(?P<pk>\d+)/$', views.InfoDetail.as_view(), name='info-detail'), ]
buenrostrolab/proatac
tests/test_cli.py
Python
mit
575
0.015652
import pytest from click.testing import CliRunner from parkour im
port cli import md5 def file_checksums_equal(file1, file2): with open(file1
) as f: checksum1 = md5.new(f.read()).digest() with open(file2) as f: checksum2 = md5.new(f.read()).digest() return checksum1==checksum2 def test_trimmed_output(): runner = CliRunner() result = runner.invoke(cli.main, ['-a', 'fastq/s3_1.fastq.gz', '-b', 'fastq/s3_2.fastq.gz', '-u', 'trim']) print(result.output) assert file_checksums_equal('p.s3_1.trim.fastq', 'correct_output/p.s3_1.trim.fastq')
acutesoftware/rawdata
rawdata/gather.py
Python
mit
1,024
0.027344
#!/usr/bin/python3 # gather.py lookup_terms = [ {'program' :'email_outlook.py', 'known_as':['email', 'mail', 'outlook', 'messages', 'sent items', 'inbox', 'spam'] }, {'program' :'sys_PC_usage.py', 'known_as':['PC usage', 'Application logging'] }, {'program' :'sys_process_windows.py', 'known_as':['process'] }, #{'program' :'collect_bookmarks.py', # 'known_as':['chrome', 'bookmarks', 'browsing history', 'messages', # 'sent items', 'inbox', 'spam'] #}, ] def TEST(): """ This is the main function gather which defines what programs are setup to collect and the data around them - it doesnt store access details like passwords and where to save outputs but rather is a simple structure to let the calling module (such as AIKIF
, vais) know what is available and how to run it """ for l in lookup_terms: print(l['program'] + ' = ', ','.join([t for t in l['known_as']]))
TEST()
dgrat/ardupilot
Tools/autotest/autotest.py
Python
gpl-3.0
18,627
0.004832
#!/usr/bin/env python """ APM automatic test suite Andrew Tridgell, October 2011 """ from __future__ import print_function import atexit import fnmatch import glob import optparse import os import shutil import signal import sys import time import traceback import apmrover2 import arducopter import arduplane import quadplane import ardusub from pysim import util from pymavlink import mavutil from pymavlink.generator import mavtemplate def buildlogs_dirpath(): return os.getenv("BUILDLOGS", util.reltopdir("../buildlogs")) def buildlogs_path(path): '''return a string representing path in the buildlogs directory''' bits = [buildlogs_dirpath()] if isinstance(path, list): bits.extend(path) else: bits.append(path) return os.path.join(*bits) def get_default_params(atype, binary): """Get default parameters.""" # use rover simulator so SITL is not starved of input HOME = mavutil.location(40.071374969556928, -105.22978898137808, 1583.702759, 246) if "plane" in binary or "rover" in binary: frame = "rover" else: frame = "+" home = "%f,%f,%u,%u" % (HOME.lat, HOME.lng, HOME.alt, HOME.heading) sitl = util.start_SITL(binary, wipe=True, model=frame, home=home, speedup=10, unhide_parameters=True) mavproxy = util.start_MAVProxy_SITL(atype) print("Dumping defaults") idx = mavproxy.expect(['Please Run Setup', 'Saved [0-9]+ parameters to (\S+)']) if idx == 0: # we need to restart it after eeprom erase util.pexpect_close(mavproxy) util.pexpect_close(sitl) sitl = util.start_SITL(binary, model=frame, home=home, speedup=10) mavproxy = util.start_MAVProxy_SITL(atype) idx = mavproxy.expect('Saved [0-9]+ parameters to (\S+)') parmfile = mavproxy.match.group(1) dest = buildlogs_path('%s-defaults.parm' % atype) shutil.copy(parmfile, dest) util.pexpect_close(mavproxy) util.pexpect_close(sitl) print("Saved defaults for %s to %s" % (atype, dest)) return True def build_all(): """Run the build_all.sh script.""" print("Running build_all.sh") if util.run_cmd(util.reltopdir('Tools/scripts/build_all.sh'), directory=util.reltopdir('.')) != 0: print("Failed build_all.sh") return False return True def build_binaries(): """Run the build_binaries.py script.""" print("Running build_binaries.py") # copy the script as it changes git branch, which can change the script while running orig = util.reltopdir('Tools/scripts/build_binaries.py') copy = util.reltopdir('./build_binaries.py') shutil.copy2(orig, copy) # also copy generate_manifest library: orig_gm = util.reltopdir('Tools/scripts/generate_manifest.py') copy_gm = util.reltopdir('./generate_manifest.py') shutil.copy2(orig_gm, copy_gm) if util.run_cmd(copy, directory=util.reltopdir('.')) != 0: print("Failed build_binaries.py") return False return True def build_devrelease(): """Run the build_devrelease.sh script.""" print("Running build_devrelease.sh") # copy the script as it changes git branch, which can change the script while running orig = util.reltopdir('Tools/scripts/build_devrelease.sh') copy = util.reltopdir('./build_devrelease.sh') shutil.copy2(orig, copy) if util.run_cmd(copy, directory=util.reltopdir('.')) != 0: print("Failed build_devrelease.sh") return False return True def build_examples(): """Build examples.""" for target in 'px4-v2', 'navio': print("Running build.examples for %s" % target) try: util.build_examples(target) except Exception as e: print("Failed build_examples on board=%s" % target) print(str(e)) return False return True def build_parameters(): """Run the param_parse.py script.""" print("Running param_parse.py") for vehicle in 'ArduPlane', 'ArduCopter', 'ArduSub', 'APMrover2', 'AntennaTracker': if util.run_cmd([util.reltopdir('Tools/autotest/param_metadata/param_parse.py'), '--vehicle', vehicle], directory=util.reltopdir('.')) != 0: print("Failed param_parse.py (%s)" % vehicle) return False return True def convert_gpx(): """Convert any tlog files to GPX and KML.""" mavlog = glob.glob(buildlogs_path("*.tlog")) for m in mavlog: util.run_cmd(util.reltopdir("modules/mavlink/pymavlink/tools/mavtogpx.py") + " --nofixcheck " + m) gpx = m + '.gpx' kml = m + '.kml' util.run_cmd('gpsbabel -i gpx -f %s -o kml,units=m,floating=1,extrude=1 -F %s' % (gpx, kml), checkfail=False) util.run_cmd('zip %s.kmz %s.kml' % (m, m), checkfail=False) util.run_cmd("mavflightview.py --imagefile=%s.png %s" % (m, m)) return True def test_prerequisites(): """Check we have the right directories and tools to run tests.""" print("Testing prerequisites") util.mkdir_p(buildlogs_dirpath()) return True def alarm_handler(signum, frame): """Handle test timeout.""" global results, opts try: results.add('TIMEOUT', '<span class="failed-text">FAILED</span>', opts.timeout) util.pexpect_close_all() convert_gpx() write_fullresults() os.killpg(0, signal.SIGKILL) except Exception: pass sys.exit(1) def should_run_step(step): """See if a step should be skipped.""" for skip in skipsteps: if fnmatch.fnmatch(step.lower(), skip.lower()): return False return True __bin_names = { "ArduCopter" : "arducopter", "ArduPlane" : "arduplane", "APMrover2" : "ardurover", "AntennaTracker" : "antennatracker", "CopterAVC" : "arducopter-heli", "QuadPlane" : "arduplane", "ArduSub" : "ardusub" } def binary_path(step, debug=False): try: vehicle = step.split(".")[1] except Exception: return None if vehicle in __bin_names: binary_name = __bin_names[vehicle] else: # cope with builds that don't have a specific binary return None if debug: binary_basedir = "sitl-debug" else: binary_basedir = "sitl" binary = util.reltopdir(os.path.join('build', binary_basedir, 'bin', binary_name)) if not os.path.exists(binary): if os.path.exists(binary + ".exe"): binary += ".exe" else: raise ValueError("Binary
(%s) does not exist" % (binary,)) return binary def run_step(step): """Run one step.""" # remove old
logs util.run_cmd('/bin/rm -f logs/*.BIN logs/LASTLOG.TXT') if step == "prerequisites": return test_prerequisites() build_opts = { "j": opts.j, "debug": opts.debug, "clean": not opts.no_clean, "configure": not opts.no_configure, } if step == 'build.ArduPlane': return util.build_SITL('bin/arduplane', **build_opts) if step == 'build.APMrover2': return util.build_SITL('bin/ardurover', **build_opts) if step == 'build.ArduCopter': return util.build_SITL('bin/arducopter', **build_opts) if step == 'build.AntennaTracker': return util.build_SITL('bin/antennatracker', **build_opts) if step == 'build.Helicopter': return util.build_SITL('bin/arducopter-heli', **build_opts) if step == 'build.ArduSub': return util.build_SITL('bin/ardusub', **build_opts) binary = binary_path(step, debug=opts.debug) if step.startswith("default"): vehicle = step[8:] return get_default_params(vehicle, binary) fly_opts = { "viewerip": opts.viewerip, "use_map": opts.map, "valgrind": opts.valgrind, "gdb": opts.gdb, "gdbserver": opts.gdbserver, } if opts.speedup is not None: fly_opts["speedup"] = opts.speedup if step == 'fly.ArduCopter': return arducopter.fly_ArduCopter(binary, frame=opts.frame, **fly_opts) if step == 'fly.CopterAVC': return arducopter.fly_CopterAVC(binary, **fly_opts) if step == 'fly.ArduPlane': return arduplane.fly_ArduPlan
helixyte/TheLMA
thelma/entities/moleculetype.py
Python
mit
2,617
0.001146
""" This file is part of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. MoleculeType entity classes. """ from everest.entities.base import Entity from everest.entities.utils import slug_from_string __docformat__ = "reStructuredText en" __all__ = ['MoleculeType', 'MOLECULE_TYPE_IDS'] class MOLECULE_TYPE_IDS(object): """ Known molecule types. """ # FIXME: reconcile with `thelma.data.moleculetype` # pylint:disable=W0511 SSDNA = 'SSDNA' AMPLICON = 'AMPLICON' SIRNA = 'SIRNA' COMPOUND = 'COMPOUND' LONG_DSRNA = 'LONG_DSRNA' ANTI_MIR = 'ANTI_MIR' ESI_RNA = 'ESI_RNA' MIRNA_INHI = 'MIRNA_INHI' CLND_DSDNA = 'CLND_DSDNA' MIRNA_MIMI = 'MIRNA_MIMI' __ALL = [nm for nm in sorted(locals().keys()) if not nm.startswith('_')] @classmethod def is_known_type(cls, mol
ecule_type_name): """ Checks whether the given molecule type name is a known one. """ return molecule_type_name in cls.__ALL class MoleculeType(Entity): """ Instances
of this class describe molecule types, such as \'siRna\'. """ #: The name of the molecule type. name = None #: A more detailed description. description = None #: An number indicating the time it takes for molecules of this type to #: thaw. thaw_time = None #: A list of modification chemical structures #: (:class:`thelma.entities.chemicalstructure.ChemicalStructure`) #: that are associated with this molecule type. modifications = None #: The default stock concentration for this molecule type. default_stock_concentration = None def __init__(self, name, default_stock_concentration, description='', thaw_time=0, modifications=None, **kw): if not 'id' in kw: kw['id'] = name.lower() Entity.__init__(self, **kw) self.name = name self.default_stock_concentration = default_stock_concentration self.description = description self.thaw_time = thaw_time if modifications == None: self.modifications = [] @property def slug(self): #: For instances of this class, the slug is derived from the #: :attr:`name`. return slug_from_string(self.name) def __str__(self): return self.id def __repr__(self): str_format = '<%s id: %s, name: %s, thaw_time: %s>' params = (self.__class__.__name__, self.id, self.name, self.thaw_time) return str_format % params
dannyperry571/theapprentice
script.module.pydevd/lib/runfiles.py
Python
gpl-2.0
11,560
0.004325
import os def main(): import sys # Separate the nose params and the pydev params. pydev_params = [] other_test_framework_params = [] found_other_test_framework_param = None NOSE_PARAMS = '--nose-params' PY_TEST_PARAMS = '--py-test-params' for arg in sys.argv[1:]: if not found_other_test_framework_param and arg != NOSE_PARAMS and arg != PY_TEST_PARAMS: pydev_params.append(arg) else: if not found_other_test_framework_param: found_other_test_framework_param = arg else: other_test_framework_params.append(arg) # Here we'll run either with nose or with the pydev_runfiles. import pydev_runfiles import pydev_runfiles_xml_rpc import pydevd_constants from pydevd_file_utils import _NormFile DEBUG = 0 if DEBUG: sys.stdout.write('Received parameters: %s\n' % (sys.argv,)) sys.stdout.write('Params for pydev: %s\n' % (pydev_params,)) if found_other_test_framework_param: sys.stdout.write('Params for test framework: %s, %s\n' % (found_other_test_framework_param, other_test_framework_params)) try: configuration = pydev_runfiles.parse_cmdline([sys.argv[0]] + pydev_params) except: sys.stderr.write('Command line received: %s\n' % (sys.argv,)) raise pydev_runfiles_xml_rpc.InitializeServer(configuration.port) # Note that if the port is None, a Null server will be initialized. NOSE_FRAMEWORK = 1 PY_TEST_FRAMEWORK = 2 try: if found_other_test_framework_param: test_framework = 0 # Default (pydev) if found_other_test_framework_param == NOSE_PARAMS: import nose test_framework = NOSE_FRAMEWORK elif found_other_test_framework_param == PY_TEST_PARAMS: import pytest test_framework = PY_TEST_FRAMEWORK else: raise ImportError() else: raise ImportError() excep
t ImportError: if found_other_test_framework_param: sys.stderr.write('Warning: Could not import the test runner: %s. Running with the default pydev unittest runner instead.\n' % ( found_other_test_framework_param,)) test_framework = 0 # Clear any exception that may be there so that clients don't see it. # See: https://sourceforge.net/tracker/?func=detail&aid=3408057&group_id=85796&atid=577329 if h
asattr(sys, 'exc_clear'): sys.exc_clear() if test_framework == 0: return pydev_runfiles.main(configuration) # Note: still doesn't return a proper value. else: # We'll convert the parameters to what nose or py.test expects. # The supported parameters are: # runfiles.py --config-file|-t|--tests <Test.test1,Test2> dirs|files --nose-params xxx yyy zzz # (all after --nose-params should be passed directly to nose) # In java: # --tests = Constants.ATTR_UNITTEST_TESTS # --config-file = Constants.ATTR_UNITTEST_CONFIGURATION_FILE # The only thing actually handled here are the tests that we want to run, which we'll # handle and pass as what the test framework expects. py_test_accept_filter = {} files_to_tests = configuration.files_to_tests if files_to_tests: # Handling through the file contents (file where each line is a test) files_or_dirs = [] for file, tests in files_to_tests.items(): if test_framework == NOSE_FRAMEWORK: for test in tests: files_or_dirs.append(file + ':' + test) elif test_framework == PY_TEST_FRAMEWORK: file = _NormFile(file) py_test_accept_filter[file] = tests files_or_dirs.append(file) else: raise AssertionError('Cannot handle test framework: %s at this point.' % (test_framework,)) else: if configuration.tests: # Tests passed (works together with the files_or_dirs) files_or_dirs = [] for file in configuration.files_or_dirs: if test_framework == NOSE_FRAMEWORK: for t in configuration.tests: files_or_dirs.append(file + ':' + t) elif test_framework == PY_TEST_FRAMEWORK: file = _NormFile(file) py_test_accept_filter[file] = configuration.tests files_or_dirs.append(file) else: raise AssertionError('Cannot handle test framework: %s at this point.' % (test_framework,)) else: # Only files or dirs passed (let it do the test-loading based on those paths) files_or_dirs = configuration.files_or_dirs argv = other_test_framework_params + files_or_dirs if test_framework == NOSE_FRAMEWORK: # Nose usage: http://somethingaboutorange.com/mrl/projects/nose/0.11.2/usage.html # show_stdout_option = ['-s'] # processes_option = ['--processes=2'] argv.insert(0, sys.argv[0]) if DEBUG: sys.stdout.write('Final test framework args: %s\n' % (argv[1:],)) import pydev_runfiles_nose PYDEV_NOSE_PLUGIN_SINGLETON = pydev_runfiles_nose.StartPydevNosePluginSingleton(configuration) argv.append('--with-pydevplugin') # Return 'not' because it will return 'success' (so, exit == 0 if success) return not nose.run(argv=argv, addplugins=[PYDEV_NOSE_PLUGIN_SINGLETON]) elif test_framework == PY_TEST_FRAMEWORK: if DEBUG: sys.stdout.write('Final test framework args: %s\n' % (argv,)) sys.stdout.write('py_test_accept_filter: %s\n' % (py_test_accept_filter,)) import os try: xrange except: xrange = range def dotted(p): # Helper to convert path to have dots instead of slashes return os.path.normpath(p).replace(os.sep, "/").replace('/', '.') curr_dir = os.path.realpath('.') curr_dotted = dotted(curr_dir) + '.' # Overcome limitation on py.test: # When searching conftest if we have a structure as: # /my_package # /my_package/conftest.py # /my_package/tests # /my_package/tests/test_my_package.py # The test_my_package won't have access to the conftest contents from the # test_my_package.py file unless the working dir is set to /my_package. # # See related issue (for which we work-around below): # https://bitbucket.org/hpk42/pytest/issue/639/conftest-being-loaded-twice-giving for path in sys.path: path_dotted = dotted(path) if curr_dotted.startswith(path_dotted): os.chdir(path) break for i in xrange(len(argv)): arg = argv[i] # Workaround bug in py.test: if we pass the full path it ends up importing conftest # more than once (so, always work with relative paths). if os.path.isfile(arg) or os.path.isdir(arg): from pydev_imports import relpath try: # May fail if on different drives arg = relpath(arg) except ValueError: pass else: argv[i] = arg # To find our runfile helpers (i.e.: plugin)... d = os.path.dirname(__file__) if d not in sys.path: sys.path.insert(0, d) import pickle, zlib, base64 # Update environment PYTHONPATH so that it finds our plugin if using xdist. os.
arecarn/dploy
tests/utils.py
Python
mit
2,296
0
""" Contains utilities used during testing """ import os import stat import shutil def remove_tree(tree): """ reset the permission of a file and directory tree and remove it """ os.chmod(tree, 0o777) shutil.rmtree(tree) def remove_file(file_name): """ reset the permission of a file and remove it """ os.chmod(file_name, 0o777) os.remove(file_name) def create_file(file_name): """ create an file """ return open(file_name, "w").close() def create_d
irectory(directory_name): """ create an directory """ os.makedirs(directory_name) class ChangeDirectory: # pylint: disable=too-few-public-methods """ Context manager for changing the current working
directory """ def __init__(self, new_path): self.new_path = os.path.expanduser(new_path) self.saved_path = os.getcwd() def __enter__(self): os.chdir(self.new_path) def __exit__(self, etype, value, traceback): os.chdir(self.saved_path) def create_tree(tree): """ create an file and directory tree """ for branch in tree: if isinstance(branch, str): create_file(branch) elif isinstance(branch, dict): for directory, file_objs in branch.items(): create_directory(directory) with ChangeDirectory(directory): create_tree(file_objs) def remove_read_permission(path): """ change users permissions to a path to write only """ mode = os.stat(path)[stat.ST_MODE] os.chmod(path, mode & ~stat.S_IRUSR & ~stat.S_IRGRP & ~stat.S_IROTH) def add_read_permission(path): """ change users permissions to a path to write only """ mode = os.stat(path)[stat.ST_MODE] os.chmod(path, mode | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) def remove_write_permission(path): """ change users permissions to a path to read only """ mode = os.stat(path)[stat.ST_MODE] os.chmod(path, mode & ~stat.S_IWUSR & ~stat.S_IWGRP & ~stat.S_IWOTH) def remove_execute_permission(path): """ change users permissions to a path to read only """ mode = os.stat(path)[stat.ST_MODE] os.chmod(path, mode & ~stat.S_IXUSR & ~stat.S_IXGRP & ~stat.S_IXOTH)
jawilson/Flexget
flexget/plugins/operate/spy_headers.py
Python
mit
1,536
0.000651
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin import logging from flexget import plugin from flexget.event import event log = logging.getLogger('spy_headers') class PluginSpyHeaders(object): """ Logs all headers sent in http requests. Useful for resolving issues. WARNING: At the moment this modifies requests somehow! """ schema = {'type': 'boolean'} @staticmethod def log_requests_headers(response, **kwargs): log.info('Request : %s' % response.request.url) log.info('Response : %s (%s)' % (response.status_code, response.reason)) log.info('-- Headers: --------
------------------') for header, value in response.request.headers.items(): log.info('%s: %s' % (header, value)) log.info('--------------------------------------') return response def on_task_start(self, task, config): if not config:
return # Add our hook to the requests session task.requests.hooks['response'].append(self.log_requests_headers) def on_task_exit(self, task, config): """Task exiting, remove additions""" if not config: return task.requests.hooks['response'].remove(self.log_requests_headers) # remove also on abort on_task_abort = on_task_exit @event('plugin.register') def register_plugin(): plugin.register(PluginSpyHeaders, 'spy_headers', api_ver=2)
toumorokoshi/vcver-python
vcver/version.py
Python
mit
2,963
0.000337
import os import re import logging from packaging.version import parse from .scm.git import Git from .scm.base import DEFAULT_TAG_VERSION from .exception import VersionerError from .version_string import make_string_pep440_compatible SCM_TYPES = [Git] LOG = logging.getLogger(__name__) RELEASE_FORMAT = "{main_version}" FORMAT = "{main_version}.dev{commit_count}+{branch}.{scm_change_id}" def get_version( path=os.curdir, is_release=False, version_format=FORMAT, release_version_format=RELEASE_FORMAT, version_file="VERSION", release_branch_regex=None, scm_type=None, ): """ return the version. """ path = os.path.abspath(path) version_file_path = os.path.join(path, version_file) scm = _get_scm(scm_type, path) if not scm: existing_version = _read_version_file(version_file_path) if existing_version: return existing_version if scm_type is None: msg = "unable to detect scm type." else: msg = "scm
type {0} not found, or is not a valid repo.".format( scm_type ) rais
e VersionerError(msg) version = determine_version( scm, version_format=version_format, release_version_format=release_version_format, release_branch_regex=release_branch_regex, is_release=is_release, ) _write_version_file(version_file_path, version) return version def determine_version( scm, version_format=FORMAT, release_version_format=RELEASE_FORMAT, release_branch_regex=None, is_release=False, ): props = scm.get_properties() release_branch_regex = release_branch_regex or scm.RELEASE_BRANCH_REGEX if not re.match(release_branch_regex, props["branch"]): LOG.info( "branch {0} does not match regex {1}. Using default tag version.".format( props["branch"], release_branch_regex ) ) props["main_version"] = DEFAULT_TAG_VERSION else: props["main_version"] = props["tag_version"] props["branch"] = make_string_pep440_compatible(props["branch"]) fmt_to_use = release_version_format if is_release else version_format try: return str(parse(fmt_to_use.format(**props))) except KeyError as ke: raise VersionerError( "key {0} was not provided by the scm type {1}".format( ke, scm.get_name() ) ) def _read_version_file(version_file): if not os.path.exists(version_file): return with open(version_file) as fh: return fh.read() def _get_scm(scm_type, path): for SCMType in SCM_TYPES: if scm_type is None or scm_type == SCMType.get_name(): if SCMType.is_repo(path): return SCMType(path) return None def _write_version_file(version_file, version): with open(version_file, "w+") as fh: fh.write(version)
edmorley/treeherder
treeherder/log_parser/parsers.py
Python
mpl-2.0
20,165
0.002628
import json import logging import re from html.parser import HTMLParser import jsonschema from django.conf import settings logger = logging.getLogger(__name__) class ParserBase: """ Base class for all parsers. """ def __init__(self, name): """Setup the artifact to hold the extracted data.""" self.name = name self.clear() def clear(self): """Reset this parser's values for another run.""" self.artifact = [] self.complete = False def parse_line(self, line, lineno): """Parse a single line of the log""" raise NotImplementedError # pragma no cover def finish_parse(self, last_lineno_seen): """Clean-up/summary tasks run at the end of parsing.""" pass def get_artifact(self): """By default, just return the artifact as-is.""" return self.artifact class StepParser(ParserBase): """ Parse out individual job steps within a log. Step format: "steps": [ { "errors": [], "name": "set props: master", # the name of the process on start line "started": "2013-06-05 12:39:57.838527", "started_linenumber": 8, "finished_linenumber": 10, "finished": "2013-06-05 12:39:57.839226", "result": 0 }, ... ] """ # Matches the half-dozen 'key: value' header lines printed at the start of each # Buildbot job log. The list of keys are taken from: # https://hg.mozilla.org/build/buildbotcustom/file/644c3860300a/bin/log_uploader.py#l126 RE_HEADER_LINE = re.compile(r'(?:builder|slave|starttime|results|buildid|builduid|revision): .*') # Step marker lines, eg: # ========= Started foo (results: 0, elapsed: 0 secs) (at 2015-08-17 02:33:56.353866) ========= # ========= Finished foo (results: 0, elapsed: 0 secs) (at 2015-08-17 02:33:56.354301) ========= RE_STEP_MARKER = re.compile(r'={9} (?P<marker_type>Started|Finished) (?P<name>.*?) ' r'\(results: (?P<result_code>\d+), elapsed: .*?\) ' r'\(at (?P<timestamp>.*?)\)') # Legacy result code to name mapping inherited from buildbot (duplicated in TextLogStep) # TODO: Likely remove this and step handling entirely now that Taskcluster doesn't have steps. RESULT_DICT = { 0: "success", 1: "testfailed", 2: "busted", 3: "skipped", 4: "exception", 5: "retry", 6: "usercancel", 7: "superseded", } STATES = { # The initial state until we record the first step. "awaiting_first_step": 0, # We've started a step, but not yet seen the end of it. "step_in_progress": 1, # We've seen the end of the previous step. "step_finished": 2, } # date format in a step started/finished header DATE_FORMAT = '%Y-%m-%d %H:%M:%S.%f' def __init__(self): """Setup the artifact to hold the header lines.""" super().__init__("step_data") self.stepnum = -1 self.artifact = { "steps": [], "errors_truncated": False } self.sub_parser = ErrorParser() self.state = self.STATES['awaiting_first_step'] def parse_line(self, line, lineno): """Parse a single line of the log. We have to handle both buildbot style logs as well as Taskcluster logs. The latter attempt to emulate the buildbot logs, but don't accurately do so, partly due to the way logs are generated in Taskcluster (ie: on the workers themselves). Buildbot logs: builder: ... slave: ... starttime: ... results: ... buildid: ... builduid: ... revision: ... ======= <step START marker> ======= <step log output> ======= <step FINISH marker> ======= ======= <step START marker> ======= <step log output> ======= <step FINISH marker> ======= Taskcluster logs (a worst-case example): <log output outside a step> ======= <step START marker> ======= <step log output> ======= <step FINISH marker> ======= <log output outside a step> ======= <step START marker> ======= <step log output with no following finish marker> As can
be seen above, Taskcluster logs can have (a) log output that falls between step markers, and (b) content at the end of the log, that is not followed by a final finish step marker. We handle this by creating generic placeholder steps to hold the log output that is not enclosed by step markers, and then by cleaning up the final step in finish_parse() once all line
s have been parsed. """ if not line.strip(): # Skip whitespace-only lines, since they will never contain an error line, # so are not of interest. This also avoids creating spurious unnamed steps # (which occurs when we find content outside of step markers) for the # newlines that separate the steps in Buildbot logs. return if self.state == self.STATES['awaiting_first_step'] and self.RE_HEADER_LINE.match(line): # The "key: value" job metadata header lines that appear at the top of # Buildbot logs would result in the creation of an unnamed step at the # start of the job, unless we skip them. (Which is not desired, since # the lines are metadata and not test/build output.) return step_marker_match = self.RE_STEP_MARKER.match(line) if not step_marker_match: # This is a normal log line, rather than a step marker. (The common case.) if self.state != self.STATES['step_in_progress']: # We don't have an in-progress step, so need to start one, even though this # isn't a "step started" marker line. We therefore create a new generic step, # since we have no way of finding out the step metadata. This case occurs # for the Taskcluster logs where content can fall between step markers. self.start_step(lineno) # Parse the line for errors, which if found, will be associated with the current step. self.sub_parser.parse_line(line, lineno) return # This is either a "step started" or "step finished" marker line, eg: # ========= Started foo (results: 0, elapsed: 0 secs) (at 2015-08-17 02:33:56.353866) ========= # ========= Finished foo (results: 0, elapsed: 0 secs) (at 2015-08-17 02:33:56.354301) ========= if step_marker_match.group('marker_type') == 'Started': if self.state == self.STATES['step_in_progress']: # We're partway through a step (ie: haven't seen a "step finished" marker line), # but have now reached the "step started" marker for the next step. Before we # can start the new step, we have to clean up the previous one - albeit using # generic step metadata, since there was no "step finished" marker. This occurs # in Taskcluster's logs when content falls between the step marker lines. self.end_step(lineno) # Start a new step using the extracted step metadata. self.start_step(lineno, name=step_marker_match.group('name'), timestamp=step_marker_match.group('timestamp')) return # This is a "step finished" marker line. if self.state != self.STATES['step_in_progress']: # We're not in the middle of a step, so can't finish one. Just ignore the marker line. return # Close out the current step using the extracted step metadata. self.end_step(lineno, timestamp=step_marker_match.group('timestamp'), result_code=int(step_marker_match.
pombreda/django-hotclub
libs/external_libs/ybrowserauth/setup.py
Python
mit
455
0.004396
# ybrowserauth installation script # from distutils.core import setup setup(name='ybrowserauth', version='1.2', py_modules=['ybrowserauth'], license='http://www.opensource.org/licenses/bsd-license.php
', url='http://developer.yahoo.com/auth', description='Lets you add Yahoo! Browser-Based authentication to your applications', author='Jason Levitt', contact='http://develo
per.yahoo.com/blog', )
specify/specify7
specifyweb/specify/autonumbering.py
Python
gpl-2.0
1,532
0.004569
from typing import List, Tuple, Sequence import logging logger = logging.getLogger(__name__) from .lock_tables import lock_tables from .uiformatters import UIFormatter, get_uiformatters, AutonumberOverflowException def autonumber_and_save(collection, user, obj) -> None: uiformatters = get_uiformatters(collection, user, obj.__class__.__name__) autonumber_fields = [(formatter, vals) for formatter in uiformatters for value in [getattr(obj, formatter.field_name.lower())] if value is not None for vals in [formatter.parse(value)] if formatter.needs_autonumber(vals)] if len(autonumber_fields) > 0: do_autonumbering(collection, obj, autonumber_fields) else: logger.debug("no fields to autonumber for %s", obj) obj.save() def do_autonumbering(collection, obj, fields: List[Tuple[UIFormatter, Sequence[str]]]) -> None: logger.debug("autonumbering
%s fields: %s", obj, fields) # The autonumber action is prepared and thunked outside the locked table # context since it looks at other tables and that is
not allowed by mysql # if those tables are not also locked. thunks = [ formatter.prepare_autonumber_thunk(collection, obj.__class__, vals) for formatter, vals in fields ] with lock_tables(obj._meta.db_table): for apply_autonumbering_to in thunks: apply_autonumbering_to(obj) obj.save()
timj/scons
test/D/HSTeoh/sconstest-singleStringCannotBeMultipleOptions_dmd.py
Python
mit
1,396
0
""" Test compiling and executing using the dmd tool. """ # # __COPYRIGHT__ # # 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 followi
ng conditions: # # The above copyright notice and this permission noti
ce 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. # __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" from Common.singleStringCannotBeMultipleOptions import testForTool testForTool('dmd') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
jcabdala/fades
tests/test_file_options.py
Python
gpl-3.0
6,427
0.000778
# Copyright 2016 Facundo Batista, Nicolás Demarchi # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General 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 warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. # # For further info, check https://github.com/PyAr/fades """Tests for file_options.""" import argparse import unittest from configparser import ConfigParser from unittest.mock import patch from fades import file_options class OptionsFileTestCase(unittest.TestCase): """Check file_options.options_from_file().""" def setUp(self): self.argparser = argparse.ArgumentParser() self.argparser.add_argument self.argparser.add_argument('-f', '--foo', action='store_true') self.argparser.add_argument('-b', '--bar', action='store') self.argparser.add_argument('-d', '--dependency', action='append') self.argparser.add_argument('positional', nargs='?', default=None) def build_parser(self, args): config_parser = ConfigParser() config_parser['fades'] = args return config_parser @patch("fades.file_options.CONFIG_FILES", ('/foo/none', '/dev/null')) def test_no_config_files(self): args = self.argparser.parse_args([]) result = file_options.options_from_file(args) self.assertEqual(args, result) self.assertIsInstance(args, argparse.Namespace) @patch("fades.file_options.CONFIG_FILES", ('mock.ini',)) @patch("configparser.ConfigParser.items") def test_single_config_file_no_cli(self, mocked_parser): mocked_parser.return_value = [('foo', 'true'), ('bar', 'hux')] args = self.argparser.parse_args(['positional']) result = file_options.options_from_file(args) self.assertTrue(result.foo) self.assertEqual(result.bar, 'hux') self.assertIsInstance(args, argparse.Namespace) @patch("fades.file_options.CONFIG_FILES", ('mock.ini',)) @patch("configparser.ConfigParser.items") def test_single_config_file_with
_cli(self, mocked_parser): mocked_parser.return_value = [('foo', 'false'), ('bar', 'hux'), ('no_in_cli', 'testing')] args = self.argparser.parse_args(['--foo', '--bar
', 'other', 'positional']) result = file_options.options_from_file(args) self.assertTrue(result.foo) self.assertEqual(result.bar, 'other') self.assertEqual(result.no_in_cli, 'testing') self.assertIsInstance(args, argparse.Namespace) @patch("fades.file_options.CONFIG_FILES", ('mock.ini',)) @patch("configparser.ConfigParser.items") def test_single_config_file_with_mergeable(self, mocked_parser): mocked_parser.return_value = [('dependency', 'two')] args = self.argparser.parse_args( ['--foo', '--bar', 'other', '--dependency', 'one', 'positional']) result = file_options.options_from_file(args) self.assertTrue(result.foo) self.assertEqual(result.bar, 'other') self.assertEqual(result.dependency, ['one', 'two']) self.assertIsInstance(args, argparse.Namespace) @patch("fades.file_options.CONFIG_FILES", ('mock.ini',)) @patch("configparser.ConfigParser.items") def test_single_config_file_complex_mergeable(self, mocked_parser): mocked_parser.return_value = [('dependency', 'requests>=2.1,<2.8,!=2.6.5')] args = self.argparser.parse_args( ['--foo', '--bar', 'other', '--dependency', 'one', 'positional']) result = file_options.options_from_file(args) self.assertTrue(result.foo) self.assertEqual(result.bar, 'other') self.assertEqual(result.dependency, ['one', 'requests>=2.1,<2.8,!=2.6.5']) self.assertIsInstance(args, argparse.Namespace) @patch("fades.file_options.CONFIG_FILES", ('mock.ini', 'mock2.ini')) @patch("configparser.ConfigParser.items") def test_two_config_file_with_mergeable(self, mocked_parser): mocked_parser.side_effect = [ [('dependency', 'two')], [('dependency', 'three')], ] args = self.argparser.parse_args( ['--foo', '--bar', 'other', '--dependency', 'one', 'positional']) result = file_options.options_from_file(args) self.assertTrue(result.foo) self.assertEqual(result.bar, 'other') self.assertEqual(result.dependency, ['one', 'two', 'three']) self.assertIsInstance(args, argparse.Namespace) @patch("fades.file_options.CONFIG_FILES", ('mock.ini', 'mock2.ini')) @patch("configparser.ConfigParser.items") def test_two_config_file_with_booleans(self, mocked_parser): mocked_parser.side_effect = [ [('foo', 'true')], [('foo', 'false')], ] args = self.argparser.parse_args([]) result = file_options.options_from_file(args) self.assertFalse(result.foo) self.assertIsInstance(args, argparse.Namespace) @patch("fades.file_options.CONFIG_FILES", ('mock.ini', 'mock2.ini')) @patch("configparser.ConfigParser.items") def test_two_config_file_override_by_cli(self, mocked_parser): mocked_parser.side_effect = [ [('bar', 'no_this')], [('bar', 'no_this_b')], ] args = self.argparser.parse_args(['--bar', 'this']) result = file_options.options_from_file(args) self.assertEqual(result.bar, 'this') self.assertIsInstance(args, argparse.Namespace) @patch("fades.file_options.CONFIG_FILES", ('mock.ini', 'mock2.ini', 'mock3.ini')) @patch("configparser.ConfigParser.items") def test_three_config_file_override(self, mocked_parser): mocked_parser.side_effect = [ [('bar', 'no_this')], [('bar', 'neither_this')], [('bar', 'this')], ] args = self.argparser.parse_args([]) result = file_options.options_from_file(args) self.assertEqual(result.bar, 'this') self.assertIsInstance(args, argparse.Namespace)
elkingtowa/pyrake
tests/test_utils_datatypes.py
Python
mit
3,592
0.000557
import copy import unittest from pyrake.utils.datatypes import CaselessDict __doctests__ = ['pyrake.utils.datatypes'] class CaselessDictTest(unittest.TestCase): def test_init(self): seq = {'red': 1, 'black': 3} d = CaselessDict(seq) self.assertEqual(d['red'], 1) self.assertEqual(d['black'], 3) seq = (('red', 1), ('black', 3)) d = CaselessDict(seq) self.assertEqual(d['red'], 1) self.assertEqual(d['black'], 3) def test_caseless(self): d = CaselessDict() d['key_Lower'] = 1 self.assertEqual(d['KEy_loWer'], 1) self.assertEqual(d.get('KEy_loWer'), 1) d['KEY_LOWER'] = 3 self.assertEqual(d['key_Lower'], 3) self.assertEqual(d.get('key_Lower'), 3) def test_delete(self): d = CaselessDict({'key_lower': 1}) del d['key_LOWER'] self.assertRaises(KeyError, d.__getitem__, 'key_LOWER') self.assertRaises(KeyError, d.__getitem__, 'key_lower') def test_getdefault(self): d = CaselessDict() self.assertEqual(d.get('c', 5), 5) d['c'] = 10 self.assertEqual(d.get('c', 5), 10) def test_setdefault(self): d = CaselessDict({'a': 1, 'b': 2}) r = d.setdefault('A', 5) self.assertEqual(r, 1) self.assertEqual(d['A'], 1) r = d.setdefault('c', 5) self.assertEqual(r, 5) self.assertEqual(d['C'], 5) def test_fromkeys(self): keys = ('a', 'b') d = CaselessDict.fromkeys(keys) self.assertEqual(d['A'], None) self.assertEqual(d['B'], None) d = CaselessDict.fromkeys(keys, 1) self.assertEqual(d['A'], 1) self.assertEqual(d['B'], 1) instance = CaselessDict() d = instanc
e.fromkeys(keys)
self.assertEqual(d['A'], None) self.assertEqual(d['B'], None) d = instance.fromkeys(keys, 1) self.assertEqual(d['A'], 1) self.assertEqual(d['B'], 1) def test_contains(self): d = CaselessDict() d['a'] = 1 assert 'a' in d def test_pop(self): d = CaselessDict() d['a'] = 1 self.assertEqual(d.pop('A'), 1) self.assertRaises(KeyError, d.pop, 'A') def test_normkey(self): class MyDict(CaselessDict): def normkey(self, key): return key.title() d = MyDict() d['key-one'] = 2 self.assertEqual(list(d.keys()), ['Key-One']) def test_normvalue(self): class MyDict(CaselessDict): def normvalue(self, value): if value is not None: return value + 1 d = MyDict({'key': 1}) self.assertEqual(d['key'], 2) self.assertEqual(d.get('key'), 2) d = MyDict() d['key'] = 1 self.assertEqual(d['key'], 2) self.assertEqual(d.get('key'), 2) d = MyDict() d.setdefault('key', 1) self.assertEqual(d['key'], 2) self.assertEqual(d.get('key'), 2) d = MyDict() d.update({'key': 1}) self.assertEqual(d['key'], 2) self.assertEqual(d.get('key'), 2) d = MyDict.fromkeys(('key',), 1) self.assertEqual(d['key'], 2) self.assertEqual(d.get('key'), 2) def test_copy(self): h1 = CaselessDict({'header1': 'value'}) h2 = copy.copy(h1) self.assertEqual(h1, h2) self.assertEqual(h1.get('header1'), h2.get('header1')) assert isinstance(h2, CaselessDict) if __name__ == "__main__": unittest.main()
luciencd/astrophotograpython
library/offsetter.py
Python
mit
667
0.014993
''' offsets = [[[originalx,originaly], [511,709],[498,707]],\ [[522,711], [508,709],[493,706]],\ [[522,714], [503,708],[488,705]]] ''' def offsetter(length,dim,dx,dy,sx,sy,fx,fy): x = x0 = sx y = y0 = sy arr = [] for i in range(dim): arr.append([]) for j in range(length):
x = int(x0+dx*i+dx*(j+1)) y = int(y0+dy*i+dy*(j+1)) arr[i].append([x,y]) for i in range(dim): for j in range(len(arr)): arr[i][j][0] += int(fx*i) arr[i][j][1] += int(fy*i)
return arr #print offsetter(3,3,-4,-1,532,713)
leppa/home-assistant
script/hassfest/config_flow.py
Python
apache-2.0
2,621
0.000382
"""Generate config flow file.""" import json from typing import Dict from .model import Config, Integration BASE = """ \"\"\"Automatically generated by hassfest. To update, run python3 -m script.hassfest \"\"\" # fmt: off FLOWS = {} """.strip() def validate_integration(integration: Integration): """Validate we can load config flow without installing requirements.""" if not (integration.path / "config_flow.py").is_file(): integration.add_error( "config_flow", "Config flows need to be defined in the file config_flow.py" ) # Currently not require being able to load config flow without # installing requirements. # try: # integration.import_pkg('config_flow') # except ImportError as err: # integration.add_error( # 'config_flow', # "Unable to import config flow: {}. Config flows should be able " # "to be imported without installing requirements.".format(err)) # return # if integration.domain not in config_entries.HANDLERS: # integration.add_error( # 'config_flow', # "Importing the config flow platform did not register a config " # "flow handler.") def generate_and_validate(integrations: Dict[str, Integration]): """Validate and generate config flow data.""" domains = [] for domain in sorted(integrations): integration = integrations[domain] if not integration.manifest: continue config_flow = integration.manifest.get("config_flow") if not config_flow: continue validate_integration(integration) domains.append(domain) return BASE.format(json.dumps(domains, indent=4)) def validate(integrations: Dict[str, Integration], config: Config): """Validate config flow file.""" config_flow_path = config.root / "homeassistant/generated/config_flows.py" config.cache["config_flow"] = content = generate_and_validate(integrations) with open(str(config_flow_path), "r") as fp: if fp.read().stri
p() != content: config.add_error( "config_flow", "File config_flows.py is not up to date. " "Run python3 -m script.hassfest", fixable=True, ) return def generate(integrations: Dict[str, Integration], config: Config): """Generate config flow file.""" config_flow_path = config.root / "homeassistant/gen
erated/config_flows.py" with open(str(config_flow_path), "w") as fp: fp.write(config.cache["config_flow"] + "\n")
sirech/deliver
deliver/tests/test_send.py
Python
mit
852
0.004695
from test_base import BaseTest, load_msg from mock import patch from smtplib import SMTP from deliver.send import Sen
der class SendTest(BaseTest): def setUp(self)
: super(SendTest,self).setUp() self.sender = Sender(self.config) @patch('smtplib.SMTP') @patch.object(SMTP, 'sendmail') def test_send(self, smtp, sendmail): msg = load_msg('sample') self.sender.send(msg, u'email@address.com') self.assertEqual(sendmail.call_count, 1) self.assertEqual(msg['To'], u'email@address.com') self.assertEqual(msg['From'], self.sender.get_address()) self.assertEqual(msg['Reply-To'], self.sender.get_address()) self.assertEqual(msg['Subject'], u'[Test] BETA 2.0') def test_get_address(self): self.assertEqual(self.sender.get_address(),self.config['sender'])
swcarpentry/amy
amy/workshops/management/commands/instructors_activity.py
Python
mit
5,305
0
import os import logging from django.core.management.base import BaseCommand from django.core.mail import send_mail from django.template.loader import get_template from workshops.models import Badge, Person, Role logger = logging.getLogger() class Command(BaseCommand): help = 'Report instructors activity.' def add_arguments(self, parser): parser.add_argument( '--send-out-for-real', action='store_true', default=False, help='Send information to the instructors.', ) parser.add_argument( '--no-may-contact-only', action='store_true', default=False, help='Include instructors not willing to be contacted.', ) parser.add_argument( '--django-mailing', action='store_true', default=False, help='Use Django mailing system. This requires some environmental ' 'variables to be set, see `settings.py`.', ) parser.add_argument( '-s', '--sender', action='store', default='workshops@carpentries.org', help='E-mail used in "from:" field.', ) def foreign_tasks(self, tasks, person, roles): """List of other instructors' tasks, per event.""" return [ task.event.task_set.filter(role__in=roles) .exclude(person=person) .select_related('person') for task in tasks ] def fetch_activity(self, may_contact_only=True): roles = Role.objects.filter(name__in=['instructor', 'helper']) instructor_badges = Badge.objects.instructor_badges() instructors = Person.objects.filter(badges__in=instructor_badges) instructors = instructors.exclude(email__isnull=True) if may_contact_only: instructors = instructors.exclude(may_contact=False) # let's get some things faster instructors = instructors.select_related('airport') \ .prefetch_related('task_set', 'lessons', 'award_set', 'badges') # don't repeat the records instructors = instructors.distinct() result = [] for person in instructors: tasks = person.task_set.filter(role__in=roles) \ .select_related('event', 'role') record = { 'person': person, 'lessons': person.lessons.all(), 'instructor_awards': person.award_set.filter( badge__i
n=person.badges.instructor_badges() ), 'tasks': zip(tasks, self.foreign_tasks(tasks, person, roles)), } result.append(record) return result def make_message(self, record): tmplt = get_template('mailing/instructor_activity.txt') return tmplt.render(context=record) def subject(self
, record): # in future we can vary the subject depending on the record details return 'Updating your Software Carpentry information' def recipient(self, record): return record['person'].email def send_message(self, subject, message, sender, recipient, for_real=False, django_mailing=False): if for_real: if django_mailing: send_mail(subject, message, sender, [recipient]) else: command = 'mail -s "{subject}" -r {sender} {recipient}'.format( subject=subject, sender=sender, recipient=recipient, ) writer = os.popen(command, 'w') writer.write(message) writer.close() if self.verbosity >= 2: # write only a header self.stdout.write('-' * 40 + '\n') self.stdout.write('To: {}\n'.format(recipient)) self.stdout.write('Subject: {}\n'.format(subject)) self.stdout.write('From: {}\n'.format(sender)) if self.verbosity >= 3: # write whole message out self.stdout.write(message + '\n') def handle(self, *args, **options): # default is dummy run - only actually send mail if told to send_for_real = options['send_out_for_real'] # by default include only instructors who have `may_contact==True` no_may_contact_only = options['no_may_contact_only'] # use mailing options from settings.py or the `mail` system command? django_mailing = options['django_mailing'] # verbosity option is added by Django self.verbosity = int(options['verbosity']) sender = options['sender'] results = self.fetch_activity(not no_may_contact_only) for result in results: message = self.make_message(result) subject = self.subject(result) recipient = self.recipient(result) self.send_message(subject, message, sender, recipient, for_real=send_for_real, django_mailing=django_mailing) if self.verbosity >= 1: self.stdout.write('Sent {} emails.\n'.format(len(results)))
looopTools/sw9-source
.waf-1.9.8-6657823688b736c1d1a4e2c4e8e198b4/waflib/extras/wurf/store_lock_version_resolver.py
Python
mit
719
0.038943
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https:
//waf.io/book/index.html#_obtaining_the_waf_file import os import json import shutil from.error import Error class StoreLockVersionResolver(object): def __init__(self,resolver,lock_cache,dependency): self.resolver=resolver self.lock_cache=loc
k_cache self.dependency=dependency def resolve(self): path=self.resolver.resolve() checkout=None if self.dependency.git_tag: checkout=self.dependency.git_tag elif self.dependency.git_commit: checkout=self.dependency.git_commit else: raise Error('Not stable checkout information found.') self.lock_cache.add_checkout(dependency=self.dependency,checkout=checkout) return path
stephane-martin/salt-debian-packaging
salt-2016.3.2/tests/integration/states/git.py
Python
apache-2.0
8,866
0.001241
# -*- coding: utf-8 -*- ''' Tests for the Git state ''' # Import python libs from __future__ import absolute_import import os import shutil import socket import subprocess import tempfile # Import Salt Testing libs from salttesting.helpers import ensure_in_syspath, skip_if_binaries_missing ensure_in_syspath('../../') # Import salt libs import integration import salt.utils class GitTest(integration.ModuleCase, integration.SaltReturnAssertsMixIn): ''' Validate the git state ''' def setUp(self): super(GitTest, self).setUp() self.__domain = 'github.com' try: if hasattr(socket, 'setdefaulttimeout'): # 10 second dns timeout socket.setdefaulttimeout(10) socket.gethostbyname(self.__domain) except socket.error: msg = 'error resolving {0}, possible network issue?' self.skipTest(msg.format(self.__domain)) def test_latest(self): ''' git.latest ''' name = os.path.join(integration.TMP, 'salt_repo') try: ret = self.run_state( 'git.latest', name='https://{0}/saltstack/salt-test-repo.git'.format(self.__domain), target=name ) self.assertSaltTrueReturn(ret) self.assertTrue(os.path.isdir(os.path.join(name, '.git'))) finally: shutil.rmtree(name, ignore_errors=True) def test_latest_with_rev_and_submodules(self): ''' git.latest ''' name = os.path.join(integration.TMP, 'salt_repo') try: ret = self.run_state( 'git.latest', name='https://{0}/saltstack/salt-test-repo.git'.format(self.__domain), rev='develop', target=name, submodules=True ) self.assertSaltTrueReturn(ret) self.assertTrue(os.path.isdir(os.path.join(name, '.git'))) finally: shutil.rmtree(name, ignore_errors=True) def test_latest_failure(self): ''' git.latest ''' name = os.path.join(integration.TMP, 'salt_repo') try: ret = self.run_state( 'git.latest', name='https://youSpelledGitHubWrong.com/saltstack/salt-test-repo.git', rev='develop', target=name, submodules=True ) self.assertSaltFalseReturn(ret) self.assertFalse(os.path.isdir(os.path.join(name, '.git'))) finally: shutil.rmtree(name, ignore_errors=True) def test_latest_empty_dir(self): ''' git.latest ''' name = os.path.join(integration.TMP, 'salt_repo') if not os.path.isdir(name): os.mkdir(name) try: ret = self.run_state( 'git.latest', name='https://{0}/saltstack/salt-test-repo.git'.format(self.__domain), rev='develop', target=name, submodules=True ) self.assertSaltTrueReturn(ret) self.assertTrue(os.path.isdir(os.path.join(name, '.git'))) finally:
shutil.rmtree(name, ignore_errors=True) def test_latest_unless_no_cwd_issue_6800(self): ''' cwd=target was being passed to _run_check which blew up if target dir did not already exist. ''' name = os.path.join(integration.TMP, 'salt_repo') if os.path.isdir(name): shutil.rmtree(name)
try: ret = self.run_state( 'git.latest', name='https://{0}/saltstack/salt-test-repo.git'.format(self.__domain), rev='develop', target=name, unless='test -e {0}'.format(name), submodules=True ) self.assertSaltTrueReturn(ret) self.assertTrue(os.path.isdir(os.path.join(name, '.git'))) finally: shutil.rmtree(name, ignore_errors=True) def test_numeric_rev(self): ''' git.latest with numeric revision ''' name = os.path.join(integration.TMP, 'salt_repo') try: ret = self.run_state( 'git.latest', name='https://{0}/saltstack/salt-test-repo.git'.format(self.__domain), rev=0.11, target=name, submodules=True, timeout=120 ) self.assertSaltTrueReturn(ret) self.assertTrue(os.path.isdir(os.path.join(name, '.git'))) finally: shutil.rmtree(name, ignore_errors=True) def test_latest_with_local_changes(self): ''' Ensure that we fail the state when there are local changes and succeed when force_reset is True. ''' name = os.path.join(integration.TMP, 'salt_repo') try: # Clone repo ret = self.run_state( 'git.latest', name='https://{0}/saltstack/salt-test-repo.git'.format(self.__domain), target=name ) self.assertSaltTrueReturn(ret) self.assertTrue(os.path.isdir(os.path.join(name, '.git'))) # Make change to LICENSE file. with salt.utils.fopen(os.path.join(name, 'LICENSE'), 'a') as fp_: fp_.write('Lorem ipsum dolor blah blah blah....\n') # Make sure that we now have uncommitted changes self.assertTrue(self.run_function('git.diff', [name, 'HEAD'])) # Re-run state with force_reset=False, this should fail ret = self.run_state( 'git.latest', name='https://{0}/saltstack/salt-test-repo.git'.format(self.__domain), target=name, force_reset=False ) self.assertSaltFalseReturn(ret) # Now run the state with force_reset=True, this should succeed ret = self.run_state( 'git.latest', name='https://{0}/saltstack/salt-test-repo.git'.format(self.__domain), target=name, force_reset=True ) self.assertSaltTrueReturn(ret) # Make sure that we no longer have uncommitted changes self.assertFalse(self.run_function('git.diff', [name, 'HEAD'])) finally: shutil.rmtree(name, ignore_errors=True) def test_present(self): ''' git.present ''' name = os.path.join(integration.TMP, 'salt_repo') try: ret = self.run_state( 'git.present', name=name, bare=True ) self.assertSaltTrueReturn(ret) self.assertTrue(os.path.isfile(os.path.join(name, 'HEAD'))) finally: shutil.rmtree(name, ignore_errors=True) def test_present_failure(self): ''' git.present ''' name = os.path.join(integration.TMP, 'salt_repo') if not os.path.isdir(name): os.mkdir(name) try: fname = os.path.join(name, 'stoptheprocess') with salt.utils.fopen(fname, 'a') as fh_: fh_.write('') ret = self.run_state( 'git.present', name=name, bare=True ) self.assertSaltFalseReturn(ret) self.assertFalse(os.path.isfile(os.path.join(name, 'HEAD'))) finally: shutil.rmtree(name, ignore_errors=True) def test_present_empty_dir(self): ''' git.present ''' name = os.path.join(integration.TMP, 'salt_repo') if not os.path.isdir(name): os.mkdir(name) try: ret = self.run_state( 'git.present', name=name, bare=True ) self.assertSaltTrueReturn(ret) self.assertTrue(os.path.isfile(os.path.join(name, 'HEAD'))) f
brianmay/spud
spud/tests/a_unit/photos/test_models.py
Python
gpl-3.0
35
0
""" Ru
n tests on photo m
odels. """
andpe/minos
minos/sonos/__init__.py
Python
bsd-3-clause
3,903
0.003587
import soco from collections import namedtuple SonosTrack = namedtuple('SonosTrack', [ 'title', 'artist', 'album', 'album_art_uri', 'position', 'playlist_position', 'duration', 'uri', 'resources', 'album_art', 'metadata' ]) SonosTrack.__new__.__defaults__ = (None,) * len(SonosTrack._fields) class Track(SonosTrack): def get_unique_id(self): from hashlib import sha256 h = sha256() h.update(str(self.artist).encode('utf-8') + str(self.album).encode('utf-8') + str(self.title).encode('utf-8')) return h.hexdigest() Resources =
namedtuple('Resources', [ 'bitrate', 'bits_per_sample', 'color_depth', 'duration', 'import_uri', 'nr_audio_channels', 'protection', 'protocol_info', 'resolution', 'sample_frequency', 'size', 'uri' ]) Resources.__new__.__defaults__ = (None,)
* len(Resources._fields) class SonosWrapper(object): """ A wrapper around some SoCo calls to simplify things. """ debug = False speakers = None sonos = None def __init__(self, speakers): self.speakers = speakers def toggle_debug(self): self.debug = not(self.debug) def get_speakers(self): return self.speakers def get_current_track_info(self, ip): if self.debug: return Track(**{ 'title': '99', 'artist': 'Toto', 'album': 'The Essential Toto', 'album_art_uri': 'http://127.0.0.1:1400/getaa?s=1&u=x-sonos-spotify%3aspotify%253atrack%253a4oz7fKT4bJ04KCaMM7Sp03%3fsid%3d9%26flags%3d8224%26sn%3d1', 'position': '0:00:11', 'playlist_position': '0', 'duration': '0:05:12', 'resources': [Resources(uri='x-sonos-spotify:spotify%3atrack%3a4oz7fKT4bJ04KCaMM7Sp03?sid=9&flags=8224&sn=1')], }) else: return Track(**self.speakers[ip].get_current_track_info()) def get_queue(self, ip): songs = [] if self.debug: songs.extend([ Track(**{ 'title': '99', 'artist': 'Toto', 'album': 'The Essential Toto', 'album_art_uri': 'http://127.0.0.1:1400/getaa?s=1&u=x-sonos-spotify%3aspotify%253atrack%253a4oz7fKT4bJ04KCaMM7Sp03%3fsid%3d9%26flags%3d8224%26sn%3d1', 'position': '0:00:11', 'playlist_position': '0', 'duration': '0:05:12', 'resources': [ Resources(uri='x-sonos-spotify:spotify%3atrack%3a4oz7fKT4bJ04KCaMM7Sp03?sid=9&flags=8224&sn=1') ], }), Track(**{ 'title': 'Africa', 'artist': 'Toto', 'album': 'The Essential Toto', 'album_art_uri': 'http://127.0.0.1:1400/getaa?s=1&u=x-sonos-spotify%3aspotify%253atrack%253a5ob66YV6bJ04KCaMM7Sp03%3fsid%3d9%26flags%3d8224%26sn%3d1', 'position': '0:00:11', 'playlist_position': '2', 'duration': '0:05:12', 'resources': [Resources(uri='x-sonos-spotify:spotify%3atrack%3a5ob66YV6bJ04KCaMM7Sp03?sid=9&flags=8224&sn=1')], }) ]) else: sonos_songs = self.speakers[ip].get_queue() for song in sonos_songs: s = { 'title': song.title, 'artist': song.creator, 'album': song.album, 'album_art_uri': song.album_art_uri, 'resources': song.resources } songs.append(Track(**s)) return songs def __getattr__(self, name): def wrapper(*args, **kwargs): return getattr(self.sonos, name)(*args, **kwargs) return wrapper
liresearchgroup/submtr
submtr/lib/github3/search/code.py
Python
mit
1,087
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from github3.models import GitHubCore from github3.repos import Repository class CodeSearchResult(GitHubCore): def __init__(self, data, session=None): super(CodeSearchResult, self).__init__(data, session) self._api = data.get('url') #: Filename the match occurs in self.name = data.get('name') #: Path in the repository to the file self.path = data.g
et('path') #: SHA in which the code can be found self.sha = data.get('sha') #: URL to the Git blob endpoint se
lf.git_url = data.get('git_url') #: URL to the HTML view of the blob self.html_url = data.get('html_url') #: Repository the code snippet belongs to self.repository = Repository(data.get('repository', {}), self) #: Score of the result self.score = data.get('score') #: Text matches self.text_matches = data.get('text_matches', []) def _repr(self): return '<CodeSearchResult [{0}]>'.format(self.path)
Versatilus/dragonfly
dragonfly/test/test_log.py
Python
lgpl-3.0
4,558
0.000658
# # This file is part of Dragonfly. # (c) Copyright 2007, 2008 by Christo Butcher # Licensed under the LGPL. # # Dragonfly is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Dragonfly 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with Dragonfly. If not, see # <http://www.gnu.org/licenses/>. # """ Test cases for the logging framework ============================================================================ """ import sys import logging import logging.handlers import unittest import dragonfly.log as log #=========================================================================== class OutputCapturer(object): def __init__(self): self.blocks = [] def write(self, data): self.blocks.append(data) def flush(self): pass def clear(self): self.blocks = [] @property def lines(self, prefix=""): if not self.blocks: return () else: text = "".join(self.blocks).splitlines() text = prefix + ("\n" + prefix).join(text) return text.splitlines() #--------------------------------------------------------------------------- class LogTestCase(unittest.TestCase): """ Test behavior of logging system. """ def setUp(self): self._original_stdout = sys.stdout self._output = OutputCapturer() sys.stdout = self._output self._original_stderr = sys.stderr self._error = OutputCapturer() sys.stderr = self._error def tearDown(self): sys.stdout = self._original_stdout sys.stderr = self._original_stderr # if self._output.blocks: # prefix = "Output: " # output
= "".join(self._output.blocks
).splitlines() # output = prefix + ("\n" + prefix).join(output) # print output # if self._error.blocks: # prefix = "Error: " # text = "".join(self._error.blocks).splitlines() # text = prefix + ("\n" + prefix).join(text) # print text self._output = None self._error = None def test_filtering(self): """ Verify that log messages are filtered according to level. """ log.setup_log() logger = logging.getLogger("grammar") logger.debug("test_filtering - debug") logger.info("test_filtering - info") logger.warning("test_filtering - warning") logger.error("test_filtering - error") expected = ["grammar (WARNING): test_filtering - warning", "grammar (ERROR): test_filtering - error"] self.assertEqual(self._error.lines, expected) self._error.clear() logger = logging.getLogger("grammar.begin") logger.debug("test_filtering - debug") logger.info("test_filtering - info") logger.warning("test_filtering - warning") logger.error("test_filtering - error") expected = ["grammar.begin (INFO): test_filtering - info", "grammar.begin (WARNING): test_filtering - warning", "grammar.begin (ERROR): test_filtering - error"] self.assertEqual(self._error.lines, expected) self._error.clear() logger = logging.getLogger("grammar.load") logger.debug("test_filtering - debug") logger.info("test_filtering - info") logger.warning("test_filtering - warning") logger.error("test_filtering - error") expected = ["grammar.load (WARNING): test_filtering - warning", "grammar.load (ERROR): test_filtering - error"] self.assertEqual(self._error.lines, expected) def _new_lines(self): filename = None if not hasattr(self, "_previous_line_count"): self._previous_line_count = 0 lines = open(filename).readlines() new_lines = lines[self._previous_line_count:] self._previous_line_count = len(lines) return new_lines #=========================================================================== if __name__ == "__main__": unittest.main()
mumuwoyou/vnpy-master
vnpy/trader/gateway/tkproGateway/TradeApi/__init__.py
Python
mit
279
0
# encoding: utf-8 """ Core trade api for simulated and live trading. """ from __future__ import absolute_import from __future__ import division from __future__ import print_func
tion from
__future__ import unicode_literals from .trade_api import TradeApi __all__ = ['TradeApi']
adrianmoisey/cptdevops
flask/cli.py
Python
bsd-3-clause
18,141
0.00022
# -*- coding: utf-8 -*- """ flask.cli ~~~~~~~~~ A simple command line application to run flask apps. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import os import sys from threading import Lock, Thread from functools import update_wrapper import click from ._compat import iteritems, reraise from .helpers import get_debug_flag from . import __version__ class NoAppException(click.UsageError): """Raised if an application cannot be found or loaded.""" def find_best_app(module): """Given a module instance this tries to find the best possible application in the module or raises an exception. """ from . import Flask # Search for the most common names first. for attr_name in 'app', 'application': app = getattr(module, attr_name, None) if app is not None and isinstance(app, Flask): return app # Otherwise find the only object that is a Flask instance. matches = [v for k, v in iteritems(module.__dict__) if isinstance(v, Flask)] if len(matches) == 1: return matches[0] raise NoAppException('Failed to find application in module "%s". Are
' 'you sure it contains a Flask application? Maybe ' 'you wrapped it in a WSGI middleware or you are ' 'using a factory function.' % module.__name__)
def prepare_exec_for_file(filename): """Given a filename this will try to calculate the python path, add it to the search path and return the actual module name that is expected. """ module = [] # Chop off file extensions or package markers if os.path.split(filename)[1] == '__init__.py': filename = os.path.dirname(filename) elif filename.endswith('.py'): filename = filename[:-3] else: raise NoAppException('The file provided (%s) does exist but is not a ' 'valid Python file. This means that it cannot ' 'be used as application. Please change the ' 'extension to .py' % filename) filename = os.path.realpath(filename) dirpath = filename while 1: dirpath, extra = os.path.split(dirpath) module.append(extra) if not os.path.isfile(os.path.join(dirpath, '__init__.py')): break sys.path.insert(0, dirpath) return '.'.join(module[::-1]) def locate_app(app_id): """Attempts to locate the application.""" __traceback_hide__ = True if ':' in app_id: module, app_obj = app_id.split(':', 1) else: module = app_id app_obj = None try: __import__(module) except ImportError: raise NoAppException('The file/path provided (%s) does not appear to ' 'exist. Please verify the path is correct. If ' 'app is not on PYTHONPATH, ensure the extension ' 'is .py' % module) mod = sys.modules[module] if app_obj is None: app = find_best_app(mod) else: app = getattr(mod, app_obj, None) if app is None: raise RuntimeError('Failed to find application in module "%s"' % module) return app def find_default_import_path(): app = os.environ.get('FLASK_APP') if app is None: return if os.path.isfile(app): return prepare_exec_for_file(app) return app def get_version(ctx, param, value): if not value or ctx.resilient_parsing: return message = 'Flask %(version)s\nPython %(python_version)s' click.echo(message % { 'version': __version__, 'python_version': sys.version, }, color=ctx.color) ctx.exit() version_option = click.Option(['--version'], help='Show the flask version', expose_value=False, callback=get_version, is_flag=True, is_eager=True) class DispatchingApp(object): """Special application that dispatches to a flask application which is imported by name in a background thread. If an error happens it is is recorded and shows as part of the WSGI handling which in case of the Werkzeug debugger means that it shows up in the browser. """ def __init__(self, loader, use_eager_loading=False): self.loader = loader self._app = None self._lock = Lock() self._bg_loading_exc_info = None if use_eager_loading: self._load_unlocked() else: self._load_in_background() def _load_in_background(self): def _load_app(): __traceback_hide__ = True with self._lock: try: self._load_unlocked() except Exception: self._bg_loading_exc_info = sys.exc_info() t = Thread(target=_load_app, args=()) t.start() def _flush_bg_loading_exception(self): __traceback_hide__ = True exc_info = self._bg_loading_exc_info if exc_info is not None: self._bg_loading_exc_info = None reraise(*exc_info) def _load_unlocked(self): __traceback_hide__ = True self._app = rv = self.loader() self._bg_loading_exc_info = None return rv def __call__(self, environ, start_response): __traceback_hide__ = True if self._app is not None: return self._app(environ, start_response) self._flush_bg_loading_exception() with self._lock: if self._app is not None: rv = self._app else: rv = self._load_unlocked() return rv(environ, start_response) class ScriptInfo(object): """Help object to deal with Flask applications. This is usually not necessary to interface with as it's used internally in the dispatching to click. In future versions of Flask this object will most likely play a bigger role. Typically it's created automatically by the :class:`FlaskGroup` but you can also manually create it and pass it onwards as click object. """ def __init__(self, app_import_path=None, create_app=None): if create_app is None: if app_import_path is None: app_import_path = find_default_import_path() self.app_import_path = app_import_path else: app_import_path = None #: Optionally the import path for the Flask application. self.app_import_path = app_import_path #: Optionally a function that is passed the script info to create #: the instance of the application. self.create_app = create_app #: A dictionary with arbitrary data that can be associated with #: this script info. self.data = {} self._loaded_app = None def load_app(self): """Loads the Flask app (if not yet loaded) and returns it. Calling this multiple times will just result in the already loaded app to be returned. """ __traceback_hide__ = True if self._loaded_app is not None: return self._loaded_app if self.create_app is not None: rv = self.create_app(self) else: if not self.app_import_path: raise NoAppException( 'Could not locate Flask application. You did not provide ' 'the FLASK_APP environment variable.\n\nFor more ' 'information see ' 'http://flask.pocoo.org/docs/latest/quickstart/') rv = locate_app(self.app_import_path) debug = get_debug_flag() if debug is not None: rv.debug = debug self._loaded_app = rv return rv pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True) def with_appcontext(f): """Wraps a callback so that it's guaranteed to be executed with the script's application context. If
snudler6/time-travel
src/tests/utils.py
Python
mit
492
0
"""Utils for time travel testings.""" def _t(rel=0.0): """Return an absolute time from the relative time given. The minimal allowed time in windows is 86400 seconds, for some reason. In stead of doing the arithmetic in the tests themselves, this function should be used. The value `86400` is exported in `time_travel.MIN_START_TIME`, but I shant use it for it is forbidden to test the code using the code that is being tested. """
return 86400.0 + rel
FlorianWestphal/VMI-PL
front_end/client.py
Python
mit
2,163
0.039297
#!/usr/bin/python import argparse from vmipl_communication.network_connection import NetworkConnection def main(): parser = setup_options_parser() # parse given arguments args = parser.parse_args() validate_input(parser, args) port = args.port script_content = args.vmipl_script.read() args.vmipl_script.close() if args.description_file is not None: start_vm(args.description_file, script_content, port) elif args.vm_id is not
None: reconfigure_vm(args.vm_id, script_content, port) def setup_options_parser(): descr = ("Communicate with execution environment to start virtual" + " machine or reconfigure already running one") # initialize options parser parser = argparse.ArgumentParser(description=descr) parser.add_argument("-s", "--start", help= "start virtual machine given by <VM " + " description file> using the monitoring" + " configuration given in <VMI-PL script>", dest="descri
ption_file", metavar="<VM description file>") parser.add_argument("-r", "--reconfig", help= "reconfigure virtual machine given by <VM Id>"+ " using the monitoring configuration given in"+ " <VMI-PL script>", dest="vm_id", metavar="<VM Id>") parser.add_argument("vmipl_script", help="path to VMI-PL script", type=file, metavar="<VMI-PL script>") parser.add_argument("-p", "--port", type=int, default=5555, dest="port", help= "network port to connect to execution" + " environment (default: 5555)") return parser def validate_input(parser, args): if args.description_file is not None and args.vm_id is not None: parser.error("only one mode can be chosen at a time") if args.description_file is None and args.vm_id is None: parser.error("at least one mode has to be chosen") def start_vm(description_file_path, script_content, port): conn = NetworkConnection() conn.connect('127.0.0.1', port) conn.start_vm(description_file_path, script_content) response = conn.receive_server_response() print response conn.close() def reconfigure_vm(vm_id, script_content): raise NotImplementedError() if __name__ == '__main__': main()
nyaruka/django-hamlpy
hamlpy/test/test_parser.py
Python
mit
4,020
0.004764
import unittest from hamlpy.parser.core import ( ParseException, Stream, peek_indentation, read_line, read_number, read_quoted_string, read_symbol, read_whitespace, read_word, ) from hamlpy.parser.utils import html_escape class ParserTest(unittest.TestCase): def test_read_whitespace(self): stream = Stream(" \t foo \n bar ") assert read_whitespace(stream) == " \t " assert stream.text[stream.ptr :] == "foo \n bar " stream.ptr += 3 # skip over foo assert read_whitespace(stream) == " " assert stream.text[stream.ptr :] == "\n bar " assert read_whitespace(stream, include_newlines=True) == "\n " assert stream.text[stream.ptr :] == "bar " stream.ptr += 3 # skip over bar assert read_whitespace(stream) == " " assert stream.text[stream.ptr :] == "" def test_peek_indentation(self): assert peek_indentation(Stream("content")) == 0 assert peek_indentation(Stream(" content")) == 2 assert peek_indentation(Stream("\n")) is None assert peek_indentation(Stream(" \n")) is None def test_quoted_string(self): stream = Stream("'hello'---") assert read_quoted_string(stream) == "hello" assert stream.text[stream.ptr :] == "---" stream = Stream('"this don\'t \\"x\\" hmm" not in string') assert read_quoted_string(stream) == 'this don\'t "x" hmm' assert stream.text[stream.ptr :] == " not in string" self.assertRaises(ParseException, read_quoted_string, Stream('"no end quote...')) def test_read_line(self): stream = Stream("line1\n line2\n\nline4\n\n") assert read_line(stream) == "line1" assert read_line(stream) == " line2" assert read_line(stream) == "" assert read_line(stream) == "l
ine4" assert read_line(stream) == "" assert read_line(stream) is None assert read_line(Stream("last line ")) == "last line " def test_read_number(self): stream = Stream('123"') assert read_number(stream) == "123" assert stream.text[stream.ptr :] == '"' stream = Stream("123.4xx") assert read_number(stream) =
= "123.4" assert stream.text[stream.ptr :] == "xx" stream = Stream("0.0001 ") assert read_number(stream) == "0.0001" assert stream.text[stream.ptr :] == " " def test_read_symbol(self): stream = Stream("=> bar") assert read_symbol(stream, ["=>", ":"]) == "=>" assert stream.text[stream.ptr :] == " bar" self.assertRaises(ParseException, read_symbol, Stream("foo"), ["=>"]) def test_read_word(self): stream = Stream("foo_bar") assert read_word(stream) == "foo_bar" assert stream.text[stream.ptr :] == "" stream = Stream("foo_bar ") assert read_word(stream) == "foo_bar" assert stream.text[stream.ptr :] == " " stream = Stream("ng-repeat(") assert read_word(stream) == "ng" assert stream.text[stream.ptr :] == "-repeat(" stream = Stream("ng-repeat(") assert read_word(stream, ("-",)) == "ng-repeat" assert stream.text[stream.ptr :] == "(" stream = Stream("これはテストです...") assert read_word(stream) == "これはテストです" assert stream.text[stream.ptr :] == "..." class UtilsTest(unittest.TestCase): def test_html_escape(self): assert html_escape("") == "" assert html_escape("&<>\"'") == "&amp;&lt;&gt;&quot;&#39;" assert html_escape('{% trans "hello" %}') == '{% trans "hello" %}' assert html_escape('{{ foo|default:"hello" }}') == '{{ foo|default:"hello" }}' assert html_escape("{% }} & %}") == "{% }} & %}" result = html_escape('<>{% trans "hello" %}<>{{ foo|default:"hello" }}<>') assert result == '&lt;&gt;{% trans "hello" %}&lt;&gt;{{ foo|default:"hello" }}&lt;&gt;'
leriomaggio/pycon_site
p3/migrations/0004_auto__chg_field_p3talk_sub_community.py
Python
bsd-2-clause
21,667
0.008123
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'P3Talk.sub_community' db.alter_column(u'p3_p3talk', 'sub_community', self.gf('django.db.models.fields.CharField')(max_length=20)) def backwards(self, orm): # Changing field 'P3Talk.sub_community' db.alter_column(u'p3_p3talk', 'sub_community', self.gf('django.db.models.fields.TextField')()) models = { u'assopy.country': { 'Meta': {'ordering': "['name']", 'object_name': 'Country'}, 'iso': ('django.db.models.fields.CharField', [], {'max_length': '2', 'primary_key': 'True'}), 'iso3': ('django.db.models.fields.CharField', [], {'max_length': '3', 'null': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'numcode': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}), 'printable_name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'vat_company': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'vat_company_verify': ('django.db.models.fields.CharField', [], {'default': "'-'", 'max_length': '1'}), 'vat_person': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, u'assopy.user': { 'Meta': {'object_name': 'User'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '150', 'blank': 'True'}), 'assopy_id': ('django.db.models.fields.CharField', [], {'max_length': '22', 'unique': 'True', 'null': 'True'}), 'card_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}), 'cf_code': ('django.db.models.fields.CharField', [], {'max_length': '16', 'blank': 'True'}), 'country': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['assopy.Country']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'token': ('django.db.models.fields.CharField', [], {'max_length': '36', 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'assopy_user'", 'unique': 'True', 'to': u"orm['auth.User']"}), 'vat_number': ('django.db.models.fields.CharField', [], {'max_length': '22', 'blank': 'True'}) }, u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetr
ical': '
False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'conference.attendeeprofile': { 'Meta': {'object_name': 'AttendeeProfile'}, 'birthday': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'company': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'company_homepage': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}), 'job_title': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'location': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'personal_homepage': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.User']", 'unique': 'True', 'primary_key': 'True'}), 'uuid': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '6'}), 'visibility': ('django.db.models.fields.CharField', [], {'default': "'x'", 'max_length': '1'}) }, u'conference.conference': { 'Meta': {'object_name': 'Conference'}, 'cfp_end': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'cfp_start': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'code': ('django.db.models.fields.CharField', [], {'max_length': '10', 'primary_key': 'True'}), 'conference_end': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'conference_start': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'voting_end': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'voting_start': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}) }, u'conference.conferencetag': { 'Meta': {'object_name': 'ConferenceTag'}, 'category': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '50', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}) }, u'conference.conferencetaggeditem': { 'Meta': {'object_name': 'ConferenceTaggedItem'}, 'content_
abhinavp13/IITBX-edx-platform-dev
common/lib/xmodule/xmodule/modulestore/search.py
Python
agpl-3.0
4,563
0.001096
from itertools import repeat from xmodule.course_module import CourseDescriptor from .exceptions import (ItemNotFoundError, NoPathToItem) from . import Location def path_to_location(modulestore, course_id, location): ''' Try to find a course_id/chapter/section[/position] path to location in modulestore. The courseware insists that the first level in the course is chapter, but any kind of module can be a "section". location: something that can be passed to Location course_id: Search for paths in this course. raise ItemNotFoundError if the location doesn't exist. raise NoPathToItem if the location exists, but isn't accessible via a chapter/section path in the course(s) being searched. Return a tuple (course_id, chapter, section, position) suitable for the courseware index view. A location may be accessible via many paths. This method may return any valid path. If the section is a sequential or vertical, position will be the position of this location in that sequence. Otherwise, position will be None. TODO (vshnayder): Not true yet. ''' def flatten(xs): '''Convert lisp-style (a, (b, (c, ()))) list into a python list. Not a general flatten function. ''' p = [] while xs != (): p.append(xs[0]) xs = xs[1] return p def find_path_to_course(): '''Find a path up the location graph to a node with the specified category. If no path exists, return None. If a path exists, return it as a list with target location first, and the starting location last. ''' # Standard DFS # To keep track of where we came from, the work queue has # tuples (location, path-so-far). To avoid lots of # copying, the path-so-far is stored as a lisp-style # list--nested hd::tl tuples, and flattened at the end. queue = [(location, ())] while len(queue) > 0: (loc, path) = queue.pop() # Takes from the end loc = Location(loc) # get_parent_locations should raise ItemNotFoundError if location # isn't found so we don't have to do it explicitly. Call this # first to make sure the location is there (even if it's a course, and # we would otherwise immediately exit). parents = modulestore.get_parent_locations(loc, course_id) # print 'Processing loc={0}, path={1}'.format(loc, path) if loc.category == "course": # confirm that this is the right course if course_id == CourseDescriptor.location_to_id(loc): # Found it! path = (loc, path) return flatten(path) # otherwise, add parent locations at the end newpath = (loc, path) queue.extend(zip(parents, repeat(newpath))) # If we're here, there is no path return None if not modulestore.has_item(location): raise ItemNotFoundError path = find_path_to_course() if path is None: raise NoPathToItem(location) n = len(path) course_id = CourseDescriptor.location_to_id(path[0]) # pull out the location names chapter = path[1].name if n > 1 else None section = path[2].name if n > 2 else None # Figure out the position position = None # This block of code will find the position of a module within a nested tree # of modules. If a problem is on tab 2 of a sequ
ence that's on tab 3 of a # sequence, the resulting position is 3_2. However, no positional modules # (e.g. sequential and videosequence) currently deal with this form of # representing nested positions. This needs to happen before jumping to a # module nested in more than one positional module will work. if n > 3:
position_list = [] for path_index in range(2, n - 1): category = path[path_index].category if category == 'sequential' or category == 'videosequence': section_desc = modulestore.get_instance(course_id, path[path_index]) child_locs = [c.location for c in section_desc.get_children()] # positions are 1-indexed, and should be strings to be consistent with # url parsing. position_list.append(str(child_locs.index(path[path_index + 1]) + 1)) position = "_".join(position_list) return (course_id, chapter, section, position)
x2Ident/x2Ident_test
mitmproxy/mitmproxy/models/__init__.py
Python
gpl-3.0
753
0.001328
from __future__ import absolute_import, print_function, division from netlib.http import decoded from .connections import ClientConnection, ServerConnection from .flow import Flow, Error from .http import ( HTTPFlow, HTTPRequest, HTTPResponse, Headers, make_
error_response, make_connect_request, make_connect_response, expect_continue_response ) from .tcp import TCPFlow FLOW_TYPES = dict( http=HTTPFlow, tcp=TCPFlow, ) __all__ = [ "HTTPFlow", "HTTPRequest", "HTTPResponse", "Headers", "decoded", "make_error_response", "make_connect_request", "make_connect_response", "expect_continue_response", "ClientCo
nnection", "ServerConnection", "Flow", "Error", "TCPFlow", "FLOW_TYPES", ]
ecliu110/SpotifyApp
welcome.py
Python
apache-2.0
8,683
0.004607
# Copyright 2015 IBM Corp. 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 # # 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. from flask import Flask, abort, request, render_template, redirect, url_for from uuid import uuid4 import requests import requests.auth import urllib import json import operator import string import random import os SPOTIFY_APP_ID = '9bf2a8a4ade04e6f83b1f80b6f671fff' SPOTIFY_REDIRECT_URI = 'http://TopSpotifyApp.mybluemix.net/callback' SPOTI
FY_CLIENT_SECRET = 'fbe3a1d865e04fefa7e31b87dab6f04b' ALL_GENRES = ['acoustic', 'afrobeat', 'alt-rock', '
alternative', 'ambient', 'black-metal', 'bluegrass', 'blues', 'british', 'chill', 'classical', 'club', 'country', 'dance', 'deep-house', 'disco', 'disney', 'dubstep', 'edm', 'electro', 'electronic', 'folk', 'french', 'grunge', 'happy', 'hard-rock', 'heavy-metal', 'hip-hop', 'holidays', 'house', 'indie', 'indie-pop', 'jazz', 'k-pop', 'latin', 'metal', 'minimal-techno', 'new-age', 'new-release', 'party', 'piano', 'pop', 'progressive-house', 'psych-rock', 'punk', 'rainy-day', 'reggae','road-trip', 'rock', 'salsa', 'sleep', 'soul', 'soundtracks', 'spanish', 'study', 'summer', 'synth-pop', 'techno', 'trance', 'work-out'] TOKEN = '' RANDOM_STATE = '' SEEDS = '' RECS = [] app = Flask(__name__) # Main page: prompt Spotify login @app.route('/') def homepage(): text = '<a href="%s">Authenticate with spotify</a>' return render_template("index.html", requestURL=make_authorization_url()) # Callback page @app.route('/callback') def callback(): code = request.args.get('code') state = request.args.get('state', '') # Check state, get access token if valid if state == RANDOM_STATE: # Request access and refresh tokens token_json = get_token(code) global TOKEN TOKEN = token_json['access_token'] return redirect(url_for('profile')) # invalid state, abort else: abort(403) @app.route('/profile') def profile(): resp_json = get_userInfo(TOKEN) # Get user info, top artists, number top artists with access tokens user_info = resp_json[0] top_json = resp_json[1]['items'] profile_img = user_info['images'] # Extract name, links, pictures, ids, top_genres artists = extract_artist(top_json) rec_artists = get_recommendations(artists[3]) artist_recs = rec_artists[0] artist_recs_info = rec_artists[1] return render_template("profile.html", user_json=user_info, artists=artists,profile_img=profile_img, top_json=top_json, artist_recs=artist_recs, artist_recs_info=artist_recs_info,all_genres=ALL_GENRES) # Browser Genre page @app.route('/genre/<genre>') def genre(genre): headers = {'Authorization': 'Bearer ' + TOKEN} genre_str = 'genre:' + '"' + genre + '"' params = {"q":genre_str, "market":"from_token", "type":"artist"} url = "https://api.spotify.com/v1/search?" + urllib.urlencode(params) response = requests.get(url, headers=headers) artists = response.json()['artists']['items'] return render_template("genres.html",genre=genre, artists=artists) @app.route('/hipster', methods=['POST']) def hipster(): data = request.form.to_dict() genres = data.keys() seed_genres = '' for ind, genre in enumerate(genres): newstr = genre if ind != (len(genres)-1): newstr += ',' seed_genres += newstr # Retrieve tracks with seed_genres max popularity 50 headers = {'Authorization': 'Bearer ' + TOKEN} params = {"seed_genres":seed_genres, "min_popularity":20, "max_popularity":50, "market":"US"} url = "https://api.spotify.com/v1/recommendations?" + urllib.urlencode(params) response = requests.get(url, headers=headers) recs_json = response.json()['tracks'] global SEEDS, RECS SEEDS = seed_genres RECS = recs_json return render_template("hipster.html", seed_genres=SEEDS, recs_json=RECS) @app.route('/hipster', methods=['GET']) def hipster2(): return render_template("hipster.html", seed_genres=SEEDS, recs_json=RECS) # Create request authorzation url def make_authorization_url(): global RANDOM_STATE RANDOM_STATE = generateRandomString(16) params = {"client_id": SPOTIFY_APP_ID, "response_type": "code", "redirect_uri": SPOTIFY_REDIRECT_URI, "state": RANDOM_STATE, "scope":"user-top-read" } url = "https://accounts.spotify.com/authorize?" + urllib.urlencode(params) return url # Return random string for state def generateRandomString(len): return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(len)) # Extract name, link, pic, id, and top genres from user top artist data def extract_artist(artists): names = [] links = [] pics = [] ids = [] top_genres = {} for i in range(0, len(artists)): names.append(artists[i]['name']) links.append(artists[i]['external_urls']['spotify']) pics.append(artists[i]['images'][0]['url']) ids.append(artists[i]['id']) genres = artists[i]['genres'] for genre in genres: if genre in top_genres.keys(): top_genres[genre] = top_genres[genre]+1 else: top_genres[genre] = 1 sorted_x = sorted(top_genres.items(), key=operator.itemgetter(1), reverse=True) return names, links, pics, ids, sorted_x # Find top_related artists using user's top artist data # Input artists_ids def get_recommendations(artist_ids): # key artist_name, value: num time recommended rec_artists = {} # Key artist_name, value: (spotify_url, image link) rec_artists_info = {} for i in range(0,len(artist_ids)): rec_url = "https://api.spotify.com/v1/artists/" + artist_ids[i] + "/related-artists" rec_response = requests.get(rec_url) rec_json = rec_response.json()['artists'] for j in range(0,len(rec_json)): artist = rec_json[j] artist_name = artist['name'] artist_id = artist['id'] # Add recommended artist if artist_id not in artist_ids: if artist_name in rec_artists.keys(): rec_artists[artist_name] = rec_artists[artist_name]+1 else: artist_imgages = artist['images'] artist_spotify_url = artist['external_urls']['spotify'] if len(artist_imgages) == 0: rec_artists_info[artist_name] = 'NA' else: rec_artists_info[artist_name] = (artist_spotify_url, artist_imgages[0]['url']) rec_artists[artist_name] = 1 sorted_x = sorted(rec_artists.items(), key=operator.itemgetter(1), reverse=True) if len(sorted_x) < 20: return sorted_x, rec_artists_info else: return sorted_x[:20], rec_artists_info # Use code to obtain access token, refresh token def get_token(code): client_auth = requests.auth.HTTPBasicAuth(SPOTIFY_APP_ID, SPOTIFY_CLIENT_SECRET) headers = {'Authorization': 'Basic '} post_data = {"grant_type": "authorization_code", "code": code, "redirect_uri": SPOTIFY_REDIRECT_URI} response = requests.post("https://accounts.spotify.com/api/token", auth=client_auth, headers=headers, data=post_data) token_json = response.json() return token_json # Use access token to get user info # Return user info, top artists, number top artists def get_userInfo(access_token): headers = {'Authorization': 'Bearer ' + access_token} respons
linusluotsinen/RPiAntiTheft
util/gps_handler/gps_controller.py
Python
mit
1,812
0.007174
f
rom gps import * import time import threading import math class GpsController(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info self.running = False def run(self): self.running = True while self.running: # grab EACH set
of gpsd info to clear the buffer self.gpsd.next() def stopController(self): self.running = False @property def fix(self): return self.gpsd.fix @property def utc(self): return self.gpsd.utc @property def satellites(self): return self.gpsd.satellites if __name__ == '__main__': # create the controller gpsc = GpsController() try: # start controller gpsc.start() while True: print "latitude ", gpsc.fix.latitude print "longitude ", gpsc.fix.longitude print "time utc ", gpsc.utc, " + ", gpsc.fix.time print "altitude (m)", gpsc.fix.altitude print "eps ", gpsc.fix.eps print "epx ", gpsc.fix.epx print "epv ", gpsc.fix.epv print "ept ", gpsc.gpsd.fix.ept print "speed (m/s) ", gpsc.fix.speed print "climb ", gpsc.fix.climb print "track ", gpsc.fix.track print "mode ", gpsc.fix.mode print "sats ", gpsc.satellites time.sleep(0.5) #Ctrl C except KeyboardInterrupt: print "User cancelled" #Error except: print "Unexpected error:", sys.exc_info()[0] raise finally: print "Stopping gps controller" gpsc.stopController() #wait for the tread to finish gpsc.join() print "Done"
BlackstoneEngineering/yotta
yotta/lib/settings.py
Python
apache-2.0
5,218
0.003066
# Copyright 2014 ARM Limited # # Licensed under the Apache License, Version 2.0 # See LICENSE file for details. # standard library modules, , , import logging import os import threading from collections import OrderedDict # fsutils, , misc filesystem utils, internal import fsutils # Ordered JSON, , read & write json, internal import ordered_json # folders, , get places to install things, internal import folders # # yotta's settings always written to ~/.yotta/config.json, but are read, in # order from: # # 1. environment variables (YOTTA_{section_name.upper()}_{variable_name.upper()}) # 2. ~/.yotta/config.json # 3. /usr/local/etc/yottaconfig.json # 4. /etc/yottaconfig.json # # As
soon as a value is found for a variable, the search is stopped. # # # constants user_config_file = os.path.join(folders.userSettingsDirectory(), 'config.json') dir_config_file = os.path.join('.','.yotta.json') config_files = [ dir_config_file, user_config_file, ] if os.name == 'nt': config_files += [ os.
path.expanduser(os.path.join(folders.prefix(),'yotta.json')) ] else: config_files += [ os.path.expanduser(os.path.join(folders.prefix(),'etc','yotta.json')), os.path.join('etc','yotta.json') ] # private state parser = None parser_lock = threading.Lock() # private API # class for reading JSON config files, class _JSONConfigParser(object): def __init__(self): self.configs = OrderedDict() def read(self, filenames): '''' Read a list of files. Their configuration values are merged, with preference to values from files earlier in the list. ''' for fn in filenames: try: self.configs[fn] = ordered_json.load(fn) except IOError: self.configs[fn] = OrderedDict() def get(self, path): ''' return a configuration value usage: get('section.property') Note that currently array indexes are not supported. You must get the whole array. returns None if any path element or the property is missing ''' path = _splitPath([path]) for config in self.configs.values(): cur = config for el in path: if el in cur: cur = cur[el] else: cur = None break if cur is not None: return cur return None def set(self, path, value=None, filename=None): ''' Set a configuration value. If no filename is specified, the property is set in the first configuration file. Note that if a filename is specified and the property path is present in an earlier filename then set property will be hidden. usage: set('section.property', value='somevalue') Note that currently array indexes are not supported. You must set the whole array. ''' if filename is None: config = self._firstConfig()[1] else: config = self.configs[filename] path = _splitPath([path]) for el in path[:-1]: if el in config: config = config[el] else: config[el] = OrderedDict() config = config[el] config[path[-1]] = value def write(self, filename=None): if filename is None: filename, data = self._firstConfig() elif filename in self.configs: data = self.configs[filename] else: raise ValueError('No such file.') dirname = os.path.dirname(filename) fsutils.mkDirP(dirname) ordered_json.dump(filename, data) def _firstConfig(self): for fn, data in self.configs.items(): return fn, data raise ValueError('No configs available.') def _splitPath(path): r = [] for p in path: r += p.split('.') if not len(p): raise ValueError('A path must be specified.') return r def _ensureParser(): global parser with parser_lock: if not parser: parser = _JSONConfigParser() parser.read(config_files) def _checkEnv(path): env_key = '_'.join(['YOTTA'] + [x.upper() for x in _splitPath(path)]) try: return os.environ[env_key] except KeyError: return None # public API def get(path): value = _checkEnv(path) if value: logging.debug('read property from environment: %s', path) return value _ensureParser() with parser_lock: return parser.get(path) def getProperty(section, name): return get(section + '.' + name) def set(path, value, save_locally=False): if save_locally: filename = dir_config_file else: filename = user_config_file logging.debug('setProperty: %s %s:%s', path, type(value), value) _ensureParser() with parser_lock: parser.set(path, value=value, filename=filename) parser.write(filename) def setProperty(section, name, value, save_locally=False): set(section+'.'+name, value, save_locally)
dantebarba/docker-media-server
plex/Sub-Zero.bundle/Contents/Libraries/Shared/subliminal_patch/providers/legendastv.py
Python
gpl-3.0
10,819
0.003697
# coding=utf-8 import logging import rarfile import os from subliminal.exceptions import ConfigurationError from subliminal.providers.legendastv import LegendasTVSubtitle as _LegendasTVSubtitle, \ LegendasTVProvider as _LegendasTVProvider, Episode, Movie, guess_matches, guessit, sanitize, region, type_map, \ raise_for_status, json, SHOW_EXPIRATION_TIME, title_re, season_re, datetime, pytz, NO_VALUE, releases_key, \ SUBTITLE_EXTENSIONS, language_converters from subzero.language import Language logger = logging.getLogger(__name__) class LegendasTVSubtitle(_LegendasTVSubtitle): def __init__(self, language, type, title, year, imdb_id, season, archive, name): super(LegendasTVSubtitle, self).__init__(language, type, title, year, imdb_id, season, archive, name) self.archive.content = None self.release_info = archive.name self.page_link = archive.link def make_picklable(self): self.archive.content = None return self def get_matches(self, video, hearing_impaired=False): matches = set() # episode if isinstance(video, Episode) and self.type == 'episode': # se
ries if video.series and (sanitize(self.title) in ( sanitize(name) for name in [video.series] + video.alternative_series)): matches.add('series') # year if video.original_series and self.year is None or video.year and video.year == self.year: matches.add('year') # imdb_id if video.series_imdb_id and self.imdb_id == vid
eo.series_imdb_id: matches.add('series_imdb_id') # movie elif isinstance(video, Movie) and self.type == 'movie': # title if video.title and (sanitize(self.title) in ( sanitize(name) for name in [video.title] + video.alternative_titles)): matches.add('title') # year if video.year and self.year == video.year: matches.add('year') # imdb_id if video.imdb_id and self.imdb_id == video.imdb_id: matches.add('imdb_id') # name matches |= guess_matches(video, guessit(self.name, {'type': self.type, 'single_value': True})) return matches class LegendasTVProvider(_LegendasTVProvider): languages = {Language(*l) for l in language_converters['legendastv'].to_legendastv.keys()} subtitle_class = LegendasTVSubtitle def __init__(self, username=None, password=None): # Provider needs UNRAR installed. If not available raise ConfigurationError try: rarfile.custom_check([rarfile.UNRAR_TOOL], True) except rarfile.RarExecError: raise ConfigurationError('UNRAR tool not available') if any((username, password)) and not all((username, password)): raise ConfigurationError('Username and password must be specified') self.username = username self.password = password self.logged_in = False self.session = None @staticmethod def is_valid_title(title, title_id, sanitized_title, season, year, imdb_id): """Check if is a valid title.""" if title["imdb_id"] and title["imdb_id"] == imdb_id: logger.debug(u'Matched title "%s" as IMDB ID %s', sanitized_title, title["imdb_id"]) return True if title["title2"] and sanitize(title['title2']) == sanitized_title: logger.debug(u'Matched title "%s" as "%s"', sanitized_title, title["title2"]) return True return _LegendasTVProvider.is_valid_title(title, title_id, sanitized_title, season, year) @region.cache_on_arguments(expiration_time=SHOW_EXPIRATION_TIME, should_cache_fn=lambda value: value) def search_titles(self, title, season, title_year, imdb_id): """Search for titles matching the `title`. For episodes, each season has it own title :param str title: the title to search for. :param int season: season of the title :param int title_year: year of the title :return: found titles. :rtype: dict """ titles = {} sanitized_titles = [sanitize(title)] ignore_characters = {'\'', '.'} if any(c in title for c in ignore_characters): sanitized_titles.append(sanitize(title, ignore_characters=ignore_characters)) for sanitized_title in sanitized_titles: # make the query if season: logger.info('Searching episode title %r for season %r', sanitized_title, season) else: logger.info('Searching movie title %r', sanitized_title) r = self.session.get(self.server_url + 'legenda/sugestao/{}'.format(sanitized_title), timeout=10) raise_for_status(r) results = json.loads(r.text) # loop over results for result in results: source = result['_source'] # extract id title_id = int(source['id_filme']) # extract type title = {'type': type_map[source['tipo']], 'title2': None, 'imdb_id': None} # extract title, year and country name, year, country = title_re.match(source['dsc_nome']).groups() title['title'] = name if "dsc_nome_br" in source: name2, ommit1, ommit2 = title_re.match(source['dsc_nome_br']).groups() title['title2'] = name2 # extract imdb_id if source['id_imdb'] != '0': if not source['id_imdb'].startswith('tt'): title['imdb_id'] = 'tt' + source['id_imdb'].zfill(7) else: title['imdb_id'] = source['id_imdb'] # extract season if title['type'] == 'episode': if source['temporada'] and source['temporada'].isdigit(): title['season'] = int(source['temporada']) else: match = season_re.search(source['dsc_nome_br']) if match: title['season'] = int(match.group('season')) else: logger.debug('No season detected for title %d (%s)', title_id, name) # extract year if year: title['year'] = int(year) elif source['dsc_data_lancamento'] and source['dsc_data_lancamento'].isdigit(): # year is based on season air date hence the adjustment title['year'] = int(source['dsc_data_lancamento']) - title.get('season', 1) + 1 # add title only if is valid # Check against title without ignored chars if self.is_valid_title(title, title_id, sanitized_titles[0], season, title_year, imdb_id): logger.debug(u'Found title: %s', title) titles[title_id] = title logger.debug('Found %d titles', len(titles)) return titles def query(self, language, title, season=None, episode=None, year=None, imdb_id=None): # search for titles titles = self.search_titles(title, season, year, imdb_id) subtitles = [] # iterate over titles for title_id, t in titles.items(): logger.info('Getting archives for title %d and language %d', title_id, language.legendastv) archives = self.get_archives(title_id, language.legendastv, t['type'], season, episode) if not archives: logger.info('No archives found for title %d and language %d', title_id, language.legendastv) # iterate over title's archives for a in archives: # compute an expiration time based on the archive timestamp expiration_time = (datetime.utcnow().replace(tzinfo=pytz.utc) - a.timestamp).total_seconds() # attempt to get the r
oVirt/vdsm
lib/vdsm/storage/volumemetadata.py
Python
gpl-2.0
11,350
0
# # Copyright 2016 Red Hat, Inc. # # 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 2 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import import logging import time import six from vdsm.storage import constants as sc from vdsm.storage import exception # SIZE property was deprecated in metadata v5, but we still need this key to # read and write legacy metadata. To make sure no other code use it and it's # used only by metadata code, move it here and make it private. _SIZE = "SIZE" ATTRIBUTES = { sc.DOMAIN: ("domain", str), sc.IMAGE: ("image", str), sc.PUUID: ("parent", str), sc.CAPACITY: ("capacity", int), sc.FORMAT: ("format", str), sc.TYPE: ("type", str), sc.VOLTYPE: ("voltype", str), sc.DISKTYPE: ("disktype", str), sc.DESCRIPTION: ("description", str), sc.LEGALITY: ("legality", str), sc.CTIME: ("ctime", int), sc.GENERATION: ("generation", int), sc.SEQUENCE: ("sequence", int), } def _lines_to_dict(lines): md = {} errors = [] for line in lines: # Skip a line if there is invalid value. try: line = line.decode("utf-8") except UnicodeDecodeError as e: errors.append("Invalid line '{}': {}".format(line, e)) continue if line.startswith("EOF"): break if '=' not in line: continue key, value = line.split('=', 1) md[key.strip()] = value.strip() return md, errors def parse(lines): md, errors = _lines_to_dict(lines) metadata = {} if "NONE" in md: # Before 4.20.34-1 (ovirt 4.2.5) volume metadata could be # cleared by writing invalid metadata when deleting a volume. # See https://bugzilla.redhat.com/1574631. errors.append(str(exception.MetadataCleared())) return {}, errors # We work internally in bytes, even if old format store # value in blocks, we will read SIZE instead of CAPACITY # from non-converted volumes and use it if _SIZE in md and sc.CAPACITY not in md: try: md[sc.CAPACITY] = int(md[_SIZE]) * sc.BLOCK_SIZE_512 except ValueError as e: errors.append(str(e)) if sc.GENERATION not in md: md[sc.GENERATION] = sc.DEFAULT_GENERATION if sc.SEQUENCE not in md: md[sc.SEQUENCE] = sc.DEFAULT_SEQUENCE for key, (name, validate) in ATTRIBUTES.items(): try: # FIXME: remove pylint skip when bug fixed: # https://github.com/PyCQA/pylint/issues/5113 metadata[name] = validate(md[key]) # pylint: disable=not-callable except KeyError: errors.append("Required key '{}' is missing.".format(name)) except ValueError as e: errors.append("Invalid '{}' value: {}".format(name, str(e))) return metadata, errors def dump(lines): md, errors = parse(lines) if errors: logging.warning( "Invalid metadata found errors=%s", errors) md["status"] = sc.VOL_STATUS_INVALID else: md["status"] = sc.VOL_STATUS_OK # Do not include domain in dump output. md.pop("domain", None) return md class VolumeMetadata(object): log = logging.getLogger('storage.volumemetadata') def __init__(self, domain, image, parent, capacity, format, type, voltype, disktype, description="", legality=sc.ILLEGAL_VOL, ctime=None, generation=sc.DEFAULT_GENERATION, sequence=sc.DEFAULT_SEQUENCE): # Storage domain UUID self.domain = domain # Image UUID self.image = image # UUID of the parent volume or BLANK_UUID self.parent = parent # Volume capacity in bytes self.capacity = capacity # Format (RAW or COW) self.format = format # Allocation policy (PREALLOCATED or SPARSE) self.type = type # Relationship to other volumes (LEAF, INTERNAL or SHARED) self.voltype = voltype # Intended usage of this volume (unused) self.disktype = disktype # Free-form description and may be used to store extra metadata self.description = description # Indicates if the v
olume contents should be considered valid self.legality = legality # Volume creation time (in seconds since the epoch) self.ctime = int(time.time()) if ctime is None else ctime # Generation increments each time certain operations complete self.generation = generation # Sequence number of the volume, increased every time a
new volume is # created in an image. self.sequence = sequence @classmethod def from_lines(cls, lines): ''' Instantiates a VolumeMetadata object from storage read bytes. Args: lines: list of key=value entries given as bytes read from storage metadata section. "EOF" entry terminates parsing. ''' metadata, errors = parse(lines) if errors: raise exception.InvalidMetadata( "lines={} errors={}".format(lines, errors)) return cls(**metadata) @property def description(self): return self._description @description.setter def description(self, desc): self._description = self.validate_description(desc) @property def capacity(self): return self._capacity @capacity.setter def capacity(self, value): self._capacity = self._validate_integer("capacity", value) @property def ctime(self): return self._ctime @ctime.setter def ctime(self, value): self._ctime = self._validate_integer("ctime", value) @property def generation(self): return self._generation @generation.setter def generation(self, value): self._generation = self._validate_integer("generation", value) @property def sequence(self): return self._sequence @sequence.setter def sequence(self, value): self._sequence = self._validate_integer("sequence", value) @classmethod def _validate_integer(cls, property, value): if not isinstance(value, six.integer_types): raise AssertionError( "Invalid value for metadata property {!r}: {!r}".format( property, value)) return value @classmethod def validate_description(cls, desc): desc = str(desc) # We cannot fail when the description is too long, since we must # support older engine that may send such values, or old disks # with long description. if len(desc) > sc.DESCRIPTION_SIZE: cls.log.warning("Description is too long, truncating to %d bytes", sc.DESCRIPTION_SIZE) desc = desc[:sc.DESCRIPTION_SIZE] return desc def storage_format(self, domain_version, **overrides): """ Format metadata parameters into storage format bytes. VolumeMetadata is quite restrictive and does not allow you to make an invalid metadata, but sometimes, for example for a format conversion, you need some additional fields to be written to the storage. Those fields can be added using overrides dict. Raises MetadataOverflowError if formatted metadata is too long. """ info = { sc.CTIME: str(self.ctime
NREL/glmgen
glmgen/run_gridlabd_batch_file.py
Python
gpl-2.0
850
0.04
# This function runs a .bat file that job handles mu
ltiple GridLAB-D files import subprocess #C:\Projects\GridLAB-D_Builds\trunk\test\input\batch test\13_node_fault2.glm def create_batch_file(glm_folder,batch_name): ba
tch_file = open('{:s}'.format(batch_name),'w') batch_file.write('gridlabd.exe -T 0 --job\n') #batch_file.write('pause\n') batch_file.close() return None def run_batch_file(glm_folder,batch_name): p = subprocess.Popen('{:s}'.format(batch_name),cwd=glm_folder) code = p.wait() #print(code) return None def main(): #tests here glm_folder = 'C:\\Projects\\GridLAB-D_Builds\\trunk\\test\\input\\batch_test' batch_name = 'C:\\Projects\\GridLAB-D_Builds\\trunk\\test\\input\\batch_test\\calibration_batch_file.bat' create_batch_file(glm_folder,batch_name) run_batch_file(batch_name) if __name__ == '__main__': main()
csc8630Spring2014/Clusterizer
ete2/treeview/_open_newick.py
Python
mit
2,493
0.006418
# -*- coding: utf-8 -*- # #START_LICENSE########################################################### # # # This file is part of the Environment for Tree Exploration program # (ETE). http://ete.cgenomics.org # # ETE 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. # # ETE 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 ETE. If not, see <http://www.gnu.org/licenses/>. # # # ABOUT THE ETE PACKAGE # ===================== # # ETE is distributed under the GPL copyleft license (2008-2011). # # If you make use of ETE in published work, please cite: # # Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. # ETE: a python Environment for Tree Exploration. Jaime BMC # Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 # # Note that extra references to the specific methods implemented in # the toolkit are available in the documentation. # # More info at http://ete.cgenomics.org # # # #END_LICENSE############################################################# __VERSION__="ete2-2.2rev1056" # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'open_newick.ui' # # Created: Tue Jan 10 15:56:56 2012 # by: PyQt4 UI code generator 4.7.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_OpenNewick(object): def setupUi(self, OpenNewick): OpenNewick.setObjectName("OpenNewick") OpenNewick.resize(569, 353) self.comboBox = QtGui.QComboBox(OpenNewick) self.comboBox.setGeometry(QtCore.QRect(460, 300, 81, 23)) self.comboBox.setObjectName("comboBox") self.widget = QtGui.QWidget(OpenNewick) self.widget.setGeometry(QtCore.QRect(30, 10, 371, 321)) self.widget.setObjectName("widget") self.retranslateUi(OpenNewick) QtCo
re.QMetaObject.connectSlotsByName(OpenNewick) def retranslateUi(self, OpenNewick): OpenNewick.setWindowTitle(QtGui.QApplication.translate("OpenNewick", "Dialog", None, QtGui.QApplication.Uni
codeUTF8))
docusign/docusign-python-client
docusign_esign/models/document_html_collapsible_display_settings.py
Python
mit
11,943
0.000084
# coding: utf-8 """ DocuSign REST API The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501 OpenAPI spec version: v2.1 Contact: devcenter@docusign.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class DocumentHtmlCollapsibleDisplaySettings(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'arrow_closed': 'str', 'arrow_color': 'str', 'arrow_location': 'str', 'arrow_open': 'str', 'arrow_size': 'str', 'arrow_style': 'str', 'container_style': 'str', 'label_style': 'str', 'only_arrow_is_clickable': 'bool', 'outer_label_and_arrow_style': 'str' } attribute_map = { 'arrow_closed': 'arrowClosed', 'arrow_color': 'arrowColor', 'arrow_location': 'arrowLocation', 'arrow_open': 'arrowOpen', 'arrow_size': 'arrowSize', 'arrow_style': 'arrowStyle', 'container_style': 'containerStyle', 'label_style': 'labelStyle', 'only_arrow_is_clickable': 'onlyArrowIsClickable', 'outer_label_and_arrow_style': 'outerLabelAndArrowStyle' } def __init__(self, arrow_closed=None, arrow_color=None, arrow_location=None, arrow_open=None, arrow_size=None, arrow_style=None, container_style=None, label_style=None, only_arrow_is_clickable=None, outer_label_and_arrow_style=None): # noqa: E501 """DocumentHtmlCollapsibleDisplaySettings - a model defined in Swagger""" # noqa: E501 self._arrow_closed = None self._arrow_color = None self._arrow_location = None self._arrow_open = None self._arrow_size = None self._arrow_style = None self._container_style = None self._label_style = None self._only_arrow_is_clickable = None self._outer_label_and_arrow_style = None self.discriminator = None if arrow_closed is not None: self.arrow_closed = arrow_closed if arrow_color is not None: self.arrow_color = arrow_color if arrow_location is not None: self.arrow_location = arrow_location if arrow_open is not None: self.arrow_open = arrow_open if arrow_size is not None: self.arrow_size = arrow_size if arrow_style is not None: self.arrow_style = arrow_style if container_style is not None: self.container_style = container_style if label_style is not None: self.label_style = label_style if only_arrow_is_clickable is not None: self.only_arrow_is_clickable = only_arrow_is_clickable if outer_label_and_arrow_style is not None: self.outer_label_and_arrow_style = outer_label_and_arrow_style @property def arrow_closed(self): """Gets the arrow_closed of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 # noqa: E501 :return: The arrow_closed of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :rtype: str """ return self._arrow_closed @arrow_closed.setter def arrow_closed(self, arrow_closed): """Sets the arrow_closed of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :param arrow_closed: The arrow_closed of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :type: str """ self._arrow_closed = arrow_closed @property def arrow_color(self): """Gets the arrow_color of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 # noqa: E501 :return: The arrow_color of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :rtype: str """ return self._arrow_color @arrow_color.setter def arrow_color(self, arrow_color): """Sets the arrow_color of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :param arrow_color: The arrow_color of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :type: str """ self._arrow_color = arrow_color @property def arrow_location(self): """Gets the arrow_location of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 # noqa: E501 :return: The arrow_location of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :rtype: str """ return self._arrow_location @arrow_location.setter def arrow_location(self, arrow_location): """Sets the arrow_location of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :param arrow_location: The arrow_location of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :type: str """ self._arrow_location = arrow_location @property def arrow_open(self): """Gets the arrow_open of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501
# noqa: E501 :return: The arrow_open of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :rtype: str """ return self._arrow_open @arrow_open.setter
def arrow_open(self, arrow_open): """Sets the arrow_open of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :param arrow_open: The arrow_open of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :type: str """ self._arrow_open = arrow_open @property def arrow_size(self): """Gets the arrow_size of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 # noqa: E501 :return: The arrow_size of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :rtype: str """ return self._arrow_size @arrow_size.setter def arrow_size(self, arrow_size): """Sets the arrow_size of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :param arrow_size: The arrow_size of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :type: str """ self._arrow_size = arrow_size @property def arrow_style(self): """Gets the arrow_style of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 # noqa: E501 :return: The arrow_style of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :rtype: str """ return self._arrow_style @arrow_style.setter def arrow_style(self, arrow_style): """Sets the arrow_style of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :param arrow_style: The arrow_style of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :type: str """ self._arrow_style = arrow_style @property def container_style(self): """Gets the container_style of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 # noqa: E501 :return: The container_style of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :rtype: str """ return self._container_style @container_style.setter def container_style(self, container_style): """Sets the container_style of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :param container_style: The container_style of this DocumentHtmlCollapsibleDisplaySettings. # noqa: E501 :type: str """ self._container_style = container_style @property def label_style(self): """Gets the label_style of this DocumentHtmlCollapsibleDisplaySettings. # noqa:
mozilla/relman-auto-nag
auto_nag/cache.py
Python
bsd-3-clause
1,902
0.000526
# 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/. import json import os from libmozdata import utils as lmdutils from auto_nag import utils class Cache(object): def __init__(self, name, max_days, add_once=True): super(Cache, self).__init__() self.name = name self.max_days = max_days self.add_once = add_once self.added = False self.dryrun = True self.data = None def set_dry_run(self, dryrun): self.dryrun = dryrun or self.max_days < 1 def get_path(self): cache_path = utils.get_config("common", "cache") if not os.path.exists(cache_path): os.mkdir(cache_path) return "{}/{}.json".format(cache_path, self.name) def get_data(self): if self.data is None: path = self.get_path() self.data = {} if os.path.exists(path): with open(path, "r") as In: data = json.load(In) for bugid, date in data.it
ems(): delta = lmdutils.get_date_ymd("today") - lmdutils.get_date_ymd( date ) if delta.days < self.max_days: self.data[str(bugid)] = date r
eturn self.data def add(self, bugids): if self.dryrun or (self.add_once and self.added): return data = self.get_data() today = lmdutils.get_today() for bugid in bugids: data[str(bugid)] = today with open(self.get_path(), "w") as Out: json.dump(data, Out) self.added = True def __contains__(self, key): return not self.dryrun and str(key) in self.get_data()
MungoRae/home-assistant
homeassistant/components/mailbox/__init__.py
Python
apache-2.0
7,809
0
""" Provides functionality for mailboxes. For more details about this component, please refer to the documentation at https://home-assistant.io/components/mailbox/ """ import asyncio import logging from contextlib import suppress from datetime import timedelta import async_timeout from aiohttp import web from aiohttp.web_exceptions import HTTPNotFound from homeassistant.core import callback from homeassistant.helpers import config_per_platform, discovery from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.entity import Entity from homeassistant.components.http import HomeAssistantView from homeassistant.exceptions import HomeAssistantError from homeassistant.setup import async_prepare_setup_platform DEPENDENCIES = ['http'] DOMAIN = 'mailbox' EVENT = 'mailbox_updated' CONTENT_TYPE_MPEG = 'audio/mpeg' SCAN_INTERVAL = timedelta(seconds=30) _LOGGER = logging.getLogger(__name__) @asyncio.coroutine def async_setup(hass, config): """Track states and offer events for mailboxes.""" mailboxes = [] hass.components.frontend.register_built_in_panel( 'mailbox', 'Mailbox', 'mdi:mailbox') hass.http.register_view(MailboxPlatformsView(mailboxes)) hass.http.register_view(MailboxMessageView(mailboxes)) hass.http.register_view(MailboxMediaView(mailboxes)) hass.http.register_view(MailboxDeleteView(mailboxes)) @asyncio.coroutine def async_setup_platform(p_type, p_config=None, discovery_info=None): """Set up a mailbox platform.""" if p_config is None: p_config = {} if discovery_info is None: discovery_info = {} platform = yield from async_prepare_setup_platform( hass, config, DOMAIN, p_type) if platform is None: _LOGGER.error("Unknown mailbox platform specified") return _LOGGER.info("Setting up %s.%s", DOMAIN, p_type) mailbox = None try: if hasattr(platform, 'async_get_handler'): mailbox = yield from \ platform.async_get_handler(hass, p_config, discovery_info) elif hasattr(platform, 'get_handler'): mailbox = yield from hass.async_add_job( platform.get_handler, hass, p_config, discovery_info) else: raise HomeAssistantError("Invalid mailbox platform.") if mailbox is None: _LOGGER.error( "Failed to initialize mailbox platform %s", p_type) return except Exception: # pylint: disable=broad-except _LOGGER.exception('Error setting up platform %s', p_type) return mailboxes.append(mailbox) mailbox_entity = MailboxEntity(hass, mailbox) component = EntityComponent( logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL) yield from component.async_add_entity(mailbox_entity) setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN)] if setup_tasks: yield from asyncio.wait(setup_tasks, loop=hass.loop) @asyncio.coroutine def async_platform_discovered(platform, info): """Handle for discovered platform.""" yield from async_setup_platform(platform, discovery_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) return True class MailboxEntity(Entity): """Entity for each mailbox platform.""" def __init__(self, hass, mailbox): """Initialize mailbox entity.""" self.mailbox = mailbox self.hass = hass self.message_count = 0 @callback def _mailbox_updated(event): self.hass.async_add_job(self.async_update_ha_state(True)) hass.bus.async_listen(EVENT, _mailbox_updated) @property def state(self): """Return the state of the binary sensor.""" return str(self.message_count) @property def name(self): """Return the name of the entity.""" return self.mailbox.name @asyncio.coroutine def async_update(self): """Retrieve messages from platform.""" messages = yield from self.mailbox.async_get_messages() self.message_count = len(messages) class Mailbox(object): """Represent an mailbox device.""" def __init__(self, hass, name): """Initialize mailbox object.""" self.hass = hass self.name = name def async_update(self): """Send event notification of updated mailbox.""" self.hass.bus.async_fire(EVENT) @property def media_type(self): """Return the supported media type.""" raise NotImplementedError() @asyncio.coroutine def async_get_media(self, msgid
): """Return the media blob for the msgid.""" raise NotImplementedError() @asyncio.coroutine
def async_get_messages(self): """Return a list of the current messages.""" raise NotImplementedError() def async_delete(self, msgid): """Delete the specified messages.""" raise NotImplementedError() class StreamError(Exception): """Media streaming exception.""" pass class MailboxView(HomeAssistantView): """Base mailbox view.""" def __init__(self, mailboxes): """Initialize a basic mailbox view.""" self.mailboxes = mailboxes def get_mailbox(self, platform): """Retrieve the specified mailbox.""" for mailbox in self.mailboxes: if mailbox.name == platform: return mailbox raise HTTPNotFound class MailboxPlatformsView(MailboxView): """View to return the list of mailbox platforms.""" url = "/api/mailbox/platforms" name = "api:mailbox:platforms" @asyncio.coroutine def get(self, request): """Retrieve list of platforms.""" platforms = [] for mailbox in self.mailboxes: platforms.append(mailbox.name) return self.json(platforms) class MailboxMessageView(MailboxView): """View to return the list of messages.""" url = "/api/mailbox/messages/{platform}" name = "api:mailbox:messages" @asyncio.coroutine def get(self, request, platform): """Retrieve messages.""" mailbox = self.get_mailbox(platform) messages = yield from mailbox.async_get_messages() return self.json(messages) class MailboxDeleteView(MailboxView): """View to delete selected messages.""" url = "/api/mailbox/delete/{platform}/{msgid}" name = "api:mailbox:delete" @asyncio.coroutine def delete(self, request, platform, msgid): """Delete items.""" mailbox = self.get_mailbox(platform) mailbox.async_delete(msgid) class MailboxMediaView(MailboxView): """View to return a media file.""" url = r"/api/mailbox/media/{platform}/{msgid}" name = "api:asteriskmbox:media" @asyncio.coroutine def get(self, request, platform, msgid): """Retrieve media.""" mailbox = self.get_mailbox(platform) hass = request.app['hass'] with suppress(asyncio.CancelledError, asyncio.TimeoutError): with async_timeout.timeout(10, loop=hass.loop): try: stream = yield from mailbox.async_get_media(msgid) except StreamError as err: error_msg = "Error getting media: %s" % (err) _LOGGER.error(error_msg) return web.Response(status=500) if stream: return web.Response(body=stream, content_type=mailbox.media_type) return web.Response(status=500)
felipecorrea/python-pocket
examples/batch_actions.py
Python
apache-2.0
1,253
0.03352
#!/usr/bin/env python '''Batch se
veral changes to Pocket''' __author__ = 'Felipe Borges' import sys sys.path.append("..") import getopt impo
rt pocket USAGE = '''Usage: batch_actions [options] array_of_actions This script adds an Item to Pocket. Options: -h --help: print this help --consumer_key : the Pocket API consumer key --access_token : the user's Pocket Access Token ''' def print_usage_and_exit(): print USAGE sys.exit(2) def main(): try: shortflags = 'h' longflags = ['help', 'consumer_key=', 'access_token='] opts, args = getopt.gnu_getopt(sys.argv[1:], shortflags, longflags) except getopt.GetoptError: print_usage_and_exit() consumer_key = None access_token = None for o, a in opts: if o in ('-h', '--help'): print_usage_and_exit() if o in ('--consumer_key'): consumer_key = a if o in ('--access_token'): access_token = a actions = ' '.join(args) if not actions or not consumer_key or not access_token: print_usage_and_exit() api = pocket.Api(consumer_key = consumer_key, access_token = access_token) try: actionsResult = api.send(actions) for result in actionsResult: print (result), except Exception, e: print e sys.exit(2) if __name__ == "__main__": main()
pawl/Chinese-RFID-Access-Control-Library
rfid.py
Python
mit
9,417
0.000212
import binascii import socket import struct import sys def ten_digit_to_comma_format(badge): """Returns the comma-format RFID number (without the comma) from the 10-digit RFID number. Explanation: *On an EM4100/4001 spec RFID card, there will generally be two sets of numbers like this: 0015362878 234,27454 *The part of the number before the comma represents the first hex byte of the "10 digit" number, and the second part is the last 2 hex bytes of the "10 digit" card number. *15362878 = EA6B3E *Splitting EA and 6B3E and converting them to decimal numbers will give you 234 and 27454 (the number with the comma on the card). *The comma is excluded in the return value because the controller does not need the comma. :param badge: 10-digit RFID card number, must be integer """ # only the last 8 digits are the ID # the 8 digits correspond to only 6 hex values, so the max is FFFFFF if badge > 16777215: raise Exception("Error: Invalid RFID Number") formatted_id = str("{0:x}".format(badge)).zfill(6) # converts to hex # splits the hex at first two and last 4, converts to dec, # then combines into string id_section_1 = str(int(formatted_id[:2], 16)).zfill(3) id_section_2 = str(int(formatted_id[-4:], 16)).zfill(5) return int(id_section_1 + id_section_2) def comma_format_to_ten_digit(badge): """Returns the 10-digit number from the comma-format RFID number (without the comma) Explanation: *On an EM4100/4001 spec RFID card, there will generally be two sets of numbers like this: 0015362878 234,27454 *This function turns the number with the comma (but excluding the comma) into the 10-digit number which is generally next to it. *The part of the number before the comma represents the first hex byte of the "10 digit" number, and the second part is the last 2 hex bytes of the "10 digit" card number. **234 = EA **27454 = 6B3E **Combining EA and 6B3E and converting it to a decimal number will give you 15362878 (the first 10-digit number on the card). :param badge: comma-format RFID card number, must be integer with the comma removed """ # the 8 digits correspond to a set of two and four hex values, # so the max is the decimal version of FF and FFFF concatenated if badge > 25565535: raise Exception("Error: Invalid RFID Number") badge = str(badge).zfill(8) # splits dec at last 5 digits and everything except last 5, # converts each section to hex, then combines id_section_1 = "{0:x}".format(int(badge[:-5])).zfill(2) id_section_2 = "{0:x}".format(int(badge[-5:])).zfill(4) formatted_id = id_section_1 + id_section_2 # convert combined hex string to int return int(formatted_id, 16) class RFIDClient(object): # part of the byte string replaced by the CRC, not required to be valid source_port = "0000" # these bytes form the packet that starts a transaction with the RFID controller start_transaction = ( b"\r\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" ) def __init__(self, ip, serial): """ :param ip: IP address of the controller. :param serial: Serial number written on the controller, also "Device NO" on the web interface's configuration page. """ self.check_valid_ipv4_address(ip) if not isinstance(serial, int): raise TypeError("Serial must be set to an integer") # pack controller serial as little endian integer self.controller_serial = self.little_endian_hex(serial) self.s = self.connect(ip) @staticmethod def little_endian_hex(val): """Convert integer to little-endian hex string.""" endian = struct.pack("<I", val) return binascii.hexlify(endian).decode("utf8") @staticmethod def check_valid_ipv4_address(ip): try: socket.inet_aton(ip) except socket.error: raise TypeError("IP Address is not valid") @staticmethod def connect(ip, timeout=5, port=60000):
""" :param ip: IP address
of the controller :param timeout: settimeout value for the sockets connection :param port: the destination port of the socket, should always be 60000 """ try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) s.connect((ip, port)) s.settimeout(timeout) except Exception as e: print(e) sys.exit(1) return s @staticmethod def crc_16_ibm(data): """Returns hex byte string with CRC values added to positions 4 through 8. This CRC value is required by the controller or it will not process the request. :param data: original hex string which needs the CRC values added to it """ hex_data = bytearray.fromhex(data) byte_list = list(hex_data) num1 = 0 for i in range(0, len(byte_list)): num2 = byte_list[i] if i == 2 or i == 3: num2 = 0 num1 ^= num2 for j in range(0, 8): if num1 & 1 > 0: num1 = (num1 >> 1) ^ 40961 else: num1 >>= 1 code = num1 & 65535 # integer returned from CRC function # change hex string to list to support assignment data_list = list(data) # switch order to little endian and return unsigned short, then # replace characters in list with the CRC values endian = struct.pack("<H", code) data_list[4:8] = binascii.hexlify(endian).decode("utf8") return bytearray.fromhex("".join(data_list)) def add_user(self, badge, doors): if not isinstance(badge, int): raise TypeError("RFID number must be set to an integer") if not isinstance(doors, list): raise Exception("doors must be set to a list") # create a list of "01"'s (enabled) and "00"'s (disabled) # then later join to create "01000000" (which is only door 1 enabled) doors_enabled = "" for door in [1, 2, 3, 4]: if door in doors: doors_enabled += "01" else: doors_enabled += "00" # pack badge number as little endian integer badge = self.little_endian_hex(badge) add_packet1 = self.crc_16_ibm( "2010" + self.source_port + "2800000000000000" + self.controller_serial + "00000200ffffffff" ) self.s.send(self.start_transaction) self.s.send(add_packet1) binary_response_1 = self.s.recv(1024) if binary_response_1[:2] != b" \x11": msg = "Unexpected Result Received: {}".format(binary_response_1) raise Exception(msg) add_packet2 = self.crc_16_ibm( "2320" + self.source_port + "2900000000000000" + self.controller_serial + "00000200" + badge + "00000000a04e4605" + "87" + "1c9f3b" + doors_enabled + "00000000" ) self.s.send(self.start_transaction) self.s.send(add_packet2) binary_response_2 = self.s.recv(1024) if binary_response_2[:2] != b"#!": msg = "Unexpected Result Received: {}".format(binary_response_2) raise Exception(msg) def remove_user(self, badge): if not isinstance(badge, int): raise TypeError("RFID number must be set to an integer") # pack badge number as little endian integer badge = self.little_endian_hex(badge) remove_packet = self.crc_16_ibm( "2320" + self.source_port + "2200000000000000" + self.controller_serial + "00000200" + badge + "00000000204e460521149f3b0000000000000000" ) self.s.s
saaros/pghoard
pghoard/rohmu/object_storage/google.py
Python
apache-2.0
11,184
0.002414
""" rohmu - google cloud object store interface Copyright (c) 2016 Ohmu Ltd See LICENSE for details """ # pylint: disable=import-error, no-name-in-module # NOTE: this import is not needed per-se, but it's imported here first to point the # user to the most important possible missing dependency import googleapiclient # noqa pylint: disable=unused-import from contextlib import contextmanager from io import BytesIO, FileIO import dateutil.parser import httplib2 import json import logging import os import time from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload, MediaIoBaseUpload, MediaIoBaseDownload from oauth2client import GOOGLE_TOKEN_URI from oauth2client.client import GoogleCredentials try: from oauth2client.service_account import ServiceAccountCredentials except ImportError: from oauth2client.service_account import _ServiceAccountCredentials as ServiceAccountCredentials from ..errors import FileNotFoundFromStorageError, InvalidConfigurationError from .base import BaseTransfer logging.getLogger("googleapiclient").setLevel(logging.WARNING) logging.getLogger("oauth2client").setLevel(logging.WARNING) CHUNK_SIZE = 1024 * 1024 * 5 def unpaginate(domain, initial_op): """Iterate thru the request pages until all items have been processed""" request = initial_op(domain) while request is not None: result = request.execute() for item in result.get("items", []): yield item request = domain.list_next(request, result) def get_credentials(credential_file=None, credentials=None): if credential_file: return GoogleCredentials.from_stream(credential_file) if credentials and credentials["type"] == "service_account": return ServiceAccountCredentials( service_account_id=credentials["client_id"], service_account_email=credentials["client_email"], private_key_id=credentials["private_key_id"], private_key_pkcs8_text=credentials["private_key"], scopes=[]) if credentials and credentials["type"] == "authorized_user": return GoogleCredentials( access_token=None, client_id=credentials["client_id"], client_secret=credentials["client_secret"], refresh_token=credentials["refresh_token"], token_expiry=None, token_uri=GOOGLE_TOKEN_URI, user_agent="pghoard") return GoogleCredentials.get_application_default() class GoogleTransfer(BaseTransfer): def __init__(self, project_id, bucket_name, credential_file=None, credentials=None, prefix=None): super().__init__(prefix=prefix) self.project_id = project_id self.google_creds = get_credentials(credential_file=credential_file, credentials=credentials) self.gs = self._init_google_client() self.gs_object_client = None self.bucket_name = self.get_or_create_bucket(bucket_name) self.log.debug("GoogleTransfer initialized") def _init_google_client(self): start_time = time.monotonic() while True: try: # sometimes fails: httplib2.ServerNotFoundError: Unable to find the server at www.googleapis.com return build("storage", "v1", credentials=self.google_creds) except httplib2.ServerNotFoundError: if time.monotonic() - start_time > 40.0: raise # retry on DNS issues time.sleep(1.0) @contextmanager def _object_client(self, *, not_found=None): """(Re-)initialize object client if required, handle 404 errors gracefully and reset the client on server errors. Server errors have been shown to be caused by invalid state in the client and do not seem to be resolved without resetting.""" if self.gs_object_client is None: if self.gs is None: self.gs = self._init_google_client() self.gs_object_client = self.gs.objects() # pylint: disable=no-member try: yield self.gs_object_client except HttpError as ex: if ex.resp["status"] == "404" and not_found is not None: raise FileNotFoundFromStorageError(not_found) if ex.resp["status"] >= "500" and ex.resp["status"] <= "599": self.log.error("Received server error %r, resetting Google API client", ex.resp["status"]) self.gs = None self.gs_object_client = None raise def get_metadata_for_key(self, key): key = self.format_key_for_backend(key) with self._object_client(not_found=key) as clob: return self._metadata_for_key(clob, key) def _metadata_for_key(self, clob, key): req = clob.get(bucket=self.bucket_name, object=key) obj = req.execute() return obj.get("metadata", {}) def list_path(self, key): path = self.format_key_for_backend(key, trailing_slash=True) self.log.debug("Listing path %r", path) return_list = [] with self._object_client() as clob: for item in unpaginate(clob, lambda o: o.list(bucket=self.bucket_name, delimiter="/", prefix=path)): if item["name"].endswith("/"): continue # skip directory level objects return_list.append({ "name": self.format_key_from_backend(item["name"]), "size": int(item["size"]), "last_modified": dateutil.parser.parse(item["updated"]), "metadata": item.get("metadata", {}), }) return return_list def delete_key(self, key): key = self.format_key_for_backend(key) self.log.debug("Deleting key: %r", key) with self._object_client(not_found=key) as clob: req = clob.delete(bucket=self.bucket_name, object=key) req.execute() def get_contents_to_file(self, key, filepath_to_store_to): fileobj = FileIO(filepath_to_store_to, mode="wb") done = False metadata = {} try: metadata = self.get_contents_to_fileobj(key, fileobj) done = True finally: fileobj.close() if not done: os.unlink(filepath_to_store_to) return metadata def get_contents_to_fileobj(self, key, fileobj_to_store_to): key = self.format_key_for_backend(key) self.log.debug("Starting to fetch the contents of: %r to %r", key, fileobj_to_store_to) with self._object_client(not_found=key) as clob: req = clob.get_media(bucket=self.bucket_name, object=key) download = MediaIoBaseDownload(fileobj_to_store_to, req, chunksize=CHUNK_SIZE) done = False while not done: status, done = download.next_chunk() if status: self.log.debug("Download of %r: %d%%", key, status.progress() * 100) return self._metadata_for_key(clob, key) def get_contents_to_string(self, key): key = self.format_key_for_backend(key) self.log.debug("Starting to fetch the contents of: %r", key) with self._object_client(not_found=key) as clob: req = clob.get_media(bucket=self.bucket_name, object=key) data = req.execute()
return data, self._metadata_for_key(clob, key) def _upload(self, upload_type, local_object, key, metadata, extra_props): key = self.f
ormat_key_for_backend(key) self.log.debug("Starting to upload %r", key) upload = upload_type(local_object, mimetype="application/octet-stream", resumable=True, chunksize=CHUNK_SIZE) body = {"metadata": metadata} if extra_props: body.update(extra_props) with self._object_client() as clob: req = clob.insert(bucket=self.bucket_name, name=key, media_body=upload, body=body) response = None while response is None: status, resp
armenzg/build-mozharness
configs/single_locale/macosx64.py
Python
mpl-2.0
2,942
0.00136
import os config = { # mozconfig file to use, it depends on branch and platform names "platform": "macosx64", "update_platform": "Darwin_x86_64-gcc3", "mozconfig": "%(branch)s/browser/config/mozconfigs/macosx-universal/l10n-mozconfig", "bootstrap_env": { "SHELL": '/bin/bash', "MOZ_OBJDIR": "obj-l10n", "EN_US_BINARY_URL": "%(en_us_binary_url)s", "MOZ_UPDATE_CHANNEL": "%(update_channel)s", "MOZ_SYMBOLS_EXTRA_BUILDID": "macosx64", "MOZ_PKG_PLATFORM": "mac", # "IS_NIGHTLY": "yes", "DIST": "%(abs_objdir)s", "LOCALE_MERGEDIR": "%(abs_merge_dir)s/", "L10NBASEDIR": "../../l10n", "MOZ_MAKE_COMPLETE_MAR": "1", "LOCALE_MERGEDIR": "%(abs_merge_dir)s/", }, "ssh_key_dir": "~/.ssh", "log_name": "single_locale", "objdir": "obj-l10n", "js_src_dir": "js/src", "make_dirs": ['config'], "vcs_share_base": "/builds/hg-shared", "upload_env_extra": { "MOZ_PKG_PLATFORM": "mac", }, # tooltool 'tooltool_url': 'https://api.pub.build.mozilla.org/tooltool/', 'tooltool_script': ["/builds/tooltool.py"], 'tooltool_bootstrap': "setup.sh", 'tooltool_manifest_src': 'browser/config/tooltool-manifests/macosx64/releng.manifest', # balrog credential file: 'balrog_
credentials_file': 'oauth.txt', # l10n "ignore_locales": ["en-US"], "l10n_dir": "l10n", "locales_file": "%(branch)s/browser/locales/all-locales", "locales_dir": "browser/locales", "hg_l10n_base": "https://hg.mozilla.org/l10n-central", "hg_l10n_tag": "default", "merge_locales": True, # M
AR "previous_mar_dir": "dist/previous", "current_mar_dir": "dist/current", "update_mar_dir": "dist/update", # sure? "previous_mar_filename": "previous.mar", "current_work_mar_dir": "current.work", "package_base_dir": "dist/l10n-stage", "application_ini": "Contents/Resources/application.ini", "buildid_section": 'App', "buildid_option": "BuildID", "unpack_script": "tools/update-packaging/unwrap_full_update.pl", "incremental_update_script": "tools/update-packaging/make_incremental_update.sh", "balrog_release_pusher_script": "scripts/updates/balrog-release-pusher.py", "update_packaging_dir": "tools/update-packaging", "local_mar_tool_dir": "dist/host/bin", "mar": "mar", "mbsdiff": "mbsdiff", "current_mar_filename": "firefox-%(version)s.%(locale)s.mac.complete.mar", "complete_mar": "firefox-%(version)s.en-US.mac.complete.mar", "localized_mar": "firefox-%(version)s.%(locale)s.mac.complete.mar", "partial_mar": "firefox-%(version)s.%(locale)s.mac.partial.%(from_buildid)s-%(to_buildid)s.mar", 'installer_file': "firefox-%(version)s.en-US.mac.dmg", 'exes': { 'hgtool.py': os.path.join( os.getcwd(), 'build', 'tools', 'buildfarm', 'utils', 'hgtool.py' ), }, }
lkumar93/Deep_Learning_Crazyflie
src/deep_learning_crazyflie/src/lk_track.py
Python
mit
5,660
0.030035
#!/usr/bin/env python ''' Lucas-Kanade tracker ==================== Lucas-Kanade sparse optical flow demo. Uses goodFeaturesToTrack for track initialization and back-tracking for match verification between frames. Usage ----- lk_track.py [<video_source>] Keys ---- ESC - exit ''' # Python 2/3 compatibility from __future__ import print_function import numpy as np import numpy import cv2 import video import math from common import anorm2, draw_str from time import clock from mavros_msgs.msg import OpticalFlowRad import rospy lk_params = dict( winSize = (15, 15), maxLevel = 2, criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03)) feature_params = dict( maxCorners = 500, qualityLevel = 0.3, minDistance = 7, blockSize = 7 ) class App: def __init__(self, video_src): self.track_len = 10 self.detect_interval = 5 self.tracks = [] self.cam = video.create_capture(video_src) self.frame_idx = 0 self.DistanceTravelledX = 0 self.DistanceTravelledY = 0 self.pub = rospy.Publisher('OpticalFlowXY', OpticalFlowRad, queue_size=10) self.msg = OpticalFlowRad() rospy.init_node('OpticalFlowXYNode') self.rate = rospy.Rate(1000) def run(self): while True: TickCountBefore = cv2.getTickCount() ret, frame = self.cam.read() TimePeriod = 1/cv2.getTickFrequency() frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) dst = cv2.medianBlur(frame_gray, 5) abc = dst frame_gray = dst vis = frame.copy() VelocityX = 0 VelocityY = 0 if len(self.tracks) > 0: img0, img1 = self.prev_gray, frame_gray p0 = np.float32([tr[-1] for tr in self.tracks]).reshape(-1, 1, 2) p1, st, err = cv2.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params) p0r, st, err = cv2.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params) d = abs(p0-p0r).reshape(-1, 2).max(-1) good = d < 1 new_tracks = [] index = 0; distance = 10000; for tr, (x, y), good_flag in zip(self.tracks, p1.reshape(-1, 2), good): if not good_flag: continue tr.append((x, y)) if len(tr) > self.track_len: del tr[0] new_tracks.append(tr) cv2.circle(vis, (x, y), 2, (0, 255, 0), -1) cv2.circle(abc, (x, y), 2, (0, 255, 0), -1) for i in range(0,len(self.tracks)): localdistance = math.sqrt(math.pow((p0.item(i)-p0r.item(i)),2) + math.pow((p0.item(i+1)-p0r.item(i+1)),2)) if localdistance < distance : distance = localdistance index = i TickCountAfter = cv2.getTickCount() TimeElapsed = (TickCountAfter-TickCountBefore)*TimePeriod draw_str(vis, (20, 110), 'Time Elapsed %f' % TimeElapsed) draw_str(vis, (20, 130), 'TimePeriod %f' % TimePeriod) #VelocityX = (Average_X_Velocity_P1 - Average_X_Velocity_P0)/(TimeElapsed *379.05) #VelocityY = (Average_Y_Velocity_P1 - Average_Y_Velocity_P0)/(TimeElapsed *366.6) VelocityX = (p1.item(index) - p0.item(index))*100 /(TimeElapsed *379.05) VelocityY = (p1.item(index+1) - p0.item(index+1))*100/(TimeElapsed*366.6) self.msg.integrated_x = VelocityX; self.msg.integrated_y = VelocityY; self.msg.integration_time_us = TimeElapsed*1000000; self.msg.header.stamp = rospy.Time.now() self.pub.publish(self.msg) self.rate.sleep() self.DistanceTravelledX = self.DistanceTravelledX + (VelocityX*TimeElapsed) self.DistanceTravelledY = self.DistanceTravelledY + (VelocityY*TimeElapsed) index1 = " Item 1 x" + str(p1.item(index)) + " " + str(p1.item(index+1)) index2 = " Item 0 x " + str(p0.item(index)) + " " + str(p0.item(index+1)) index3 = " Item 0r x " + str(p0r.item(index)) + " " + str(p0r.item(index+1)) print(index1) print(index2) print(index3) self.tracks = new_tracks cv2.polylines(vis, [np.int32(tr) for tr in self.tracks], False, (0, 255, 0)) cv2.polylines(abc, [np.int32(tr) for tr in self.tracks], False, (0, 255, 0)) draw_str(vis, (20, 20), 'track count: %d' % len(self.tracks)) draw_str(vis, (20, 50), 'Distance x %f' % self.DistanceTravelledX) draw_str(vis, (20, 80), 'Distance y %f' % self.DistanceTravelledY) #draw_str(vis, (20, 50), 'Velocity x %f' % VelocityX) #draw_str(vis, (20, 80)
, 'Velocity y: %f' % VelocityY) if self.frame_idx % self.detect_interval == 0: mask = np.zeros_like(frame_gray) mask[:] = 255
for x, y in [np.int32(tr[-1]) for tr in self.tracks]: cv2.circle(mask, (x, y), 5, 0, -1) p = cv2.goodFeaturesToTrack(frame_gray, mask = mask, **feature_params) if p is not None: for x, y in np.float32(p).reshape(-1, 2): self.tracks.append([(x, y)]) self.frame_idx += 1 self.prev_gray = frame_gray cv2.imshow('lk_track', vis) cv2.imshow('lk_track2', abc) ch = 0xFF & cv2.waitKey(1) if ch == 27: break def main(): import sys try: video_src = sys.argv[1] except: video_src = 0 print(__doc__) App(video_src).run() cv2.destroyAllWindows() if __name__ == '__main__': main()
lanhel/pyzombie
test/pyzombie/handlers/HandlerInstanceStdoutTestCase.py
Python
apache-2.0
2,987
0.005022
#!/usr/bin/env python # -*- coding: UTF-8 -*- #-----------------------------------------------------------------------
-------- """pyzombie HTTP RESTful handler test cases.""" __author__ = ('Lance Finn Helsten',) __version__ = '1.0.1' __copyright__ = """Copyright 2009 Lance Finn Helsten (helsten@acm.org)""" __license__ = """ Lic
ensed 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. """ __docformat__ = "reStructuredText en" import sys import os import io import re import random import threading import unittest from time import sleep import http.client from pyzombie.Executable import Executable from pyzombie.Instance import Instance, DELTA_T from pyzombie.handlers import HandlerInstanceStdout from MockRequest import MockRequest from HTTPResponse import HTTPResponse import TestSourceCopy BUFFER = [random.randint(ord(' '), ord('~')) for i in range(4096)] BUFFER = [chr(i) for i in BUFFER] BUFFER = ''.join(BUFFER) class StdinFeeder(): def __call__(self, *args, **kwargs): test = kwargs["Test"] test.inst.stdin.write(BUFFER.encode("UTF-8")) sleep(0.01) test.inst.stdin.close() class HandlerInstanceStdoutGetTest(unittest.TestCase): def setUp(self): self.ex = Executable.getcached(__name__, mediatype="text/x-python") self.ex.writeimage(open(TestSourceCopy.__file__, "r")) self.inst = Instance(self.ex, self.__class__.__name__) self.thread = threading.Thread(target=StdinFeeder(), kwargs={"Test":self}) self.daemon = True self.thread.start() def tearDown(self): self.thread.join(0.5) # self.ex.delete() def makeRequest(self, chunked=False): req = MockRequest() req.headers["Accept"] = "spam/eggs; q=1.0, application/json; q=0.5, text/html;q=0.1, text/plain" hndlr = HandlerInstanceStdout(req, {'execname':__name__, 'instname':self.__class__.__name__}) self.assertEqual(hndlr.executable, self.ex) urlself = hndlr.serverurl(path="{0}/instances/{1}/stdout".format(__name__, self.__class__.__name__)) hndlr.get() resp = HTTPResponse(req.wfile.getvalue()) self.assertEqual(resp.protocol, "HTTP/1.1") self.assertEqual(resp.code, str(http.client.OK)) self.assertEqual(resp.header["Content-Type"], "text/plain;UTF-8") self.assertEqual(resp.md5, resp.header["ETag"]) return resp def runTest(self): resp = self.makeRequest() self.assertEqual(resp.body, BUFFER)
Abi1ity/uniclust2.0
SQLAlchemy-0.9.9/test/dialect/mysql/test_types.py
Python
bsd-3-clause
32,246
0.004626
# coding: utf-8 from sqlalchemy.testing import eq_, assert_raises from sqlalchemy import * from sqlalchemy import sql, exc, schema from sqlalchemy.util import u from sqlalchemy import util from sqlalchemy.dialects.mysql import base as mysql from sqlalchemy.testing import fixtures, AssertsCompiledSQL, AssertsExecutionResults from sqlalchemy import testing import datetime import decimal
class TypesTest(fixtures.TestBase, AssertsExecutionResults, AssertsCompiledSQL): "Test MySQL column types" __dialect__ = mysql.dialect() __only_on__ = 'mysql' __backend__ = True def test_numeric(self): "E
xercise type specification and options for numeric types." columns = [ # column type, args, kwargs, expected ddl # e.g. Column(Integer(10, unsigned=True)) == # 'INTEGER(10) UNSIGNED' (mysql.MSNumeric, [], {}, 'NUMERIC'), (mysql.MSNumeric, [None], {}, 'NUMERIC'), (mysql.MSNumeric, [12], {}, 'NUMERIC(12)'), (mysql.MSNumeric, [12, 4], {'unsigned':True}, 'NUMERIC(12, 4) UNSIGNED'), (mysql.MSNumeric, [12, 4], {'zerofill':True}, 'NUMERIC(12, 4) ZEROFILL'), (mysql.MSNumeric, [12, 4], {'zerofill':True, 'unsigned':True}, 'NUMERIC(12, 4) UNSIGNED ZEROFILL'), (mysql.MSDecimal, [], {}, 'DECIMAL'), (mysql.MSDecimal, [None], {}, 'DECIMAL'), (mysql.MSDecimal, [12], {}, 'DECIMAL(12)'), (mysql.MSDecimal, [12, None], {}, 'DECIMAL(12)'), (mysql.MSDecimal, [12, 4], {'unsigned':True}, 'DECIMAL(12, 4) UNSIGNED'), (mysql.MSDecimal, [12, 4], {'zerofill':True}, 'DECIMAL(12, 4) ZEROFILL'), (mysql.MSDecimal, [12, 4], {'zerofill':True, 'unsigned':True}, 'DECIMAL(12, 4) UNSIGNED ZEROFILL'), (mysql.MSDouble, [None, None], {}, 'DOUBLE'), (mysql.MSDouble, [12, 4], {'unsigned':True}, 'DOUBLE(12, 4) UNSIGNED'), (mysql.MSDouble, [12, 4], {'zerofill':True}, 'DOUBLE(12, 4) ZEROFILL'), (mysql.MSDouble, [12, 4], {'zerofill':True, 'unsigned':True}, 'DOUBLE(12, 4) UNSIGNED ZEROFILL'), (mysql.MSReal, [None, None], {}, 'REAL'), (mysql.MSReal, [12, 4], {'unsigned':True}, 'REAL(12, 4) UNSIGNED'), (mysql.MSReal, [12, 4], {'zerofill':True}, 'REAL(12, 4) ZEROFILL'), (mysql.MSReal, [12, 4], {'zerofill':True, 'unsigned':True}, 'REAL(12, 4) UNSIGNED ZEROFILL'), (mysql.MSFloat, [], {}, 'FLOAT'), (mysql.MSFloat, [None], {}, 'FLOAT'), (mysql.MSFloat, [12], {}, 'FLOAT(12)'), (mysql.MSFloat, [12, 4], {}, 'FLOAT(12, 4)'), (mysql.MSFloat, [12, 4], {'unsigned':True}, 'FLOAT(12, 4) UNSIGNED'), (mysql.MSFloat, [12, 4], {'zerofill':True}, 'FLOAT(12, 4) ZEROFILL'), (mysql.MSFloat, [12, 4], {'zerofill':True, 'unsigned':True}, 'FLOAT(12, 4) UNSIGNED ZEROFILL'), (mysql.MSInteger, [], {}, 'INTEGER'), (mysql.MSInteger, [4], {}, 'INTEGER(4)'), (mysql.MSInteger, [4], {'unsigned':True}, 'INTEGER(4) UNSIGNED'), (mysql.MSInteger, [4], {'zerofill':True}, 'INTEGER(4) ZEROFILL'), (mysql.MSInteger, [4], {'zerofill':True, 'unsigned':True}, 'INTEGER(4) UNSIGNED ZEROFILL'), (mysql.MSBigInteger, [], {}, 'BIGINT'), (mysql.MSBigInteger, [4], {}, 'BIGINT(4)'), (mysql.MSBigInteger, [4], {'unsigned':True}, 'BIGINT(4) UNSIGNED'), (mysql.MSBigInteger, [4], {'zerofill':True}, 'BIGINT(4) ZEROFILL'), (mysql.MSBigInteger, [4], {'zerofill':True, 'unsigned':True}, 'BIGINT(4) UNSIGNED ZEROFILL'), (mysql.MSMediumInteger, [], {}, 'MEDIUMINT'), (mysql.MSMediumInteger, [4], {}, 'MEDIUMINT(4)'), (mysql.MSMediumInteger, [4], {'unsigned':True}, 'MEDIUMINT(4) UNSIGNED'), (mysql.MSMediumInteger, [4], {'zerofill':True}, 'MEDIUMINT(4) ZEROFILL'), (mysql.MSMediumInteger, [4], {'zerofill':True, 'unsigned':True}, 'MEDIUMINT(4) UNSIGNED ZEROFILL'), (mysql.MSTinyInteger, [], {}, 'TINYINT'), (mysql.MSTinyInteger, [1], {}, 'TINYINT(1)'), (mysql.MSTinyInteger, [1], {'unsigned':True}, 'TINYINT(1) UNSIGNED'), (mysql.MSTinyInteger, [1], {'zerofill':True}, 'TINYINT(1) ZEROFILL'), (mysql.MSTinyInteger, [1], {'zerofill':True, 'unsigned':True}, 'TINYINT(1) UNSIGNED ZEROFILL'), (mysql.MSSmallInteger, [], {}, 'SMALLINT'), (mysql.MSSmallInteger, [4], {}, 'SMALLINT(4)'), (mysql.MSSmallInteger, [4], {'unsigned':True}, 'SMALLINT(4) UNSIGNED'), (mysql.MSSmallInteger, [4], {'zerofill':True}, 'SMALLINT(4) ZEROFILL'), (mysql.MSSmallInteger, [4], {'zerofill':True, 'unsigned':True}, 'SMALLINT(4) UNSIGNED ZEROFILL'), ] for type_, args, kw, res in columns: type_inst = type_(*args, **kw) self.assert_compile( type_inst, res ) # test that repr() copies out all arguments self.assert_compile( eval("mysql.%r" % type_inst), res ) # fixed in mysql-connector as of 2.0.1, # see http://bugs.mysql.com/bug.php?id=73266 @testing.provide_metadata def test_precision_float_roundtrip(self): t = Table('t', self.metadata, Column('scale_value', mysql.DOUBLE( precision=15, scale=12, asdecimal=True)), Column('unscale_value', mysql.DOUBLE( decimal_return_scale=12, asdecimal=True)) ) t.create(testing.db) testing.db.execute( t.insert(), scale_value=45.768392065789, unscale_value=45.768392065789 ) result = testing.db.scalar(select([t.c.scale_value])) eq_(result, decimal.Decimal("45.768392065789")) result = testing.db.scalar(select([t.c.unscale_value])) eq_(result, decimal.Decimal("45.768392065789")) @testing.exclude('mysql', '<', (4, 1, 1), 'no charset support') def test_charset(self): """Exercise CHARACTER SET and COLLATE-ish options on string types.""" columns = [ (mysql.MSChar, [1], {}, 'CHAR(1)'), (mysql.NCHAR, [1], {}, 'NATIONAL CHAR(1)'), (mysql.MSChar, [1], {'binary':True}, 'CHAR(1) BINARY'), (mysql.MSChar, [1], {'ascii':True}, 'CHAR(1) ASCII'), (mysql.MSChar, [1], {'unicode':True}, 'CHAR(1) UNICODE'), (mysql.MSChar, [1], {'ascii':True, 'binary':True}, 'CHAR(1) ASCII BINARY'), (mysql.MSChar, [1], {'unicode':True, 'binary':True}, 'CHAR(1) UNICODE BINARY'), (mysql.MSChar, [1], {'charset':'utf8'}, 'CHAR(1) CHARACTER SET utf8'), (mysql.MSChar, [1], {'charset':'utf8', 'binary':True}, 'CHAR(1) CHARACTER SET utf8 BINARY'), (mysql.MSChar, [1], {'charset':'utf8', 'unicode':True}, 'CHAR(1) CHARACTER SET utf8'), (mysql.MSChar, [1], {'charset':'utf8', 'ascii':True}, 'CHAR(1) CHARACTER SET utf8'), (mysql.MSChar, [1], {'collation': 'utf8_bin'}, 'CHAR(1) COLLATE utf8_bin'), (mysql.MSChar, [1], {'charset': 'utf8', 'collati
Kunalpod/codewars
dubstep.py
Python
mit
163
0.02454
#Kunal Gautam #Codewars : @Kunal
pod #Problem name: Dubstep #Problem level: 6 kyu def song_decoder(song):
return " ".join(" ".join(song.split('WUB')).split())
HenryGBC/landing_company
landing/migrations/0001_initial.py
Python
mit
556
0.001799
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.
db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( nam
e='Prueba', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('nombre', models.CharField(max_length=100)), ], options={ }, bases=(models.Model,), ), ]
frc2423/2015
recycle_rush/commands/autonomous.py
Python
gpl-2.0
485
0.010309
import wpilib from wpilib.command.commandgroup import CommandGroup class Autonomous(Comma
ndGroup): def __init__(self, drive, grabber_lift): super().__init__() self.drive = drive self.grabber_lift = grabber_lift self.addSequential(ClawGrab(grabber_lift)) self.addSequential(MoveLift(grabber_lift, .5),
1.5) self.addParallel(TurnToSpecifiedAngle(drive, 180)) self.addSequential(ArcadeDrive(drive, 0, 1))