hexsha
stringlengths
40
40
size
int64
4
1.02M
ext
stringclasses
8 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
209
max_stars_repo_name
stringlengths
5
121
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
209
max_issues_repo_name
stringlengths
5
121
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
209
max_forks_repo_name
stringlengths
5
121
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
4
1.02M
avg_line_length
float64
1.07
66.1k
max_line_length
int64
4
266k
alphanum_fraction
float64
0.01
1
bca0fa8e74628a1e3b4d12b48aced9b11ac7d4e9
775
py
Python
lasercut/laser_cut.py
willdickson/teensy_to_autodriver_mount
6c0cc48701850b4afd77b0c4ce3a3d1152bb8219
[ "CC-BY-4.0" ]
null
null
null
lasercut/laser_cut.py
willdickson/teensy_to_autodriver_mount
6c0cc48701850b4afd77b0c4ce3a3d1152bb8219
[ "CC-BY-4.0" ]
null
null
null
lasercut/laser_cut.py
willdickson/teensy_to_autodriver_mount
6c0cc48701850b4afd77b0c4ce3a3d1152bb8219
[ "CC-BY-4.0" ]
null
null
null
import os import sys from py2gcode import gcode_cmd from py2gcode import cnc_laser dxfFileName = sys.argv[1] prog = gcode_cmd.GCodeProg() prog.add(gcode_cmd.GenericStart()) prog.add(gcode_cmd.Space()) param = { 'fileName' : dxfFileName, 'layers' : ['vector'], 'dxfTypes' : ['LINE','ARC','CIRCLE'], 'laserPower' : 600, 'feedRate' : 10, 'convertArcs' : True, 'startCond' : 'minX', 'direction' : 'ccw', 'ptEquivTol' : 0.4e-3, } vectorCut = cnc_laser.VectorCut(param) prog.add(vectorCut) prog.add(gcode_cmd.Space()) prog.add(gcode_cmd.End(),comment=True) baseName, ext = os.path.splitext(dxfFileName) ngcFileName = '{0}.ngc'.format(baseName) prog.write(ngcFileName)
23.484848
49
0.618065
c24d3e83922ef9a56591594b9d80af9bb6a30ce2
6,153
py
Python
system_test/system_test_env.py
mthak/test_kafka
5ad9bd376951c0167038609a9afc4ef9e8329a39
[ "Apache-2.0" ]
6
2015-02-23T05:17:54.000Z
2018-05-11T09:36:24.000Z
system_test/system_test_env.py
mthak/test_kafka
5ad9bd376951c0167038609a9afc4ef9e8329a39
[ "Apache-2.0" ]
31
2019-09-09T03:06:25.000Z
2021-05-03T12:29:32.000Z
system_test/system_test_env.py
mthak/test_kafka
5ad9bd376951c0167038609a9afc4ef9e8329a39
[ "Apache-2.0" ]
5
2017-08-23T02:50:05.000Z
2020-09-11T11:25:03.000Z
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. #!/usr/bin/env python # =================================== # system_test_env.py # =================================== import copy import json import os import sys from utils import system_test_utils class SystemTestEnv(): # private: _cwdFullPath = os.getcwd() _thisScriptFullPathName = os.path.realpath(__file__) _thisScriptBaseDir = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) # public: SYSTEM_TEST_BASE_DIR = os.path.abspath(_thisScriptBaseDir) SYSTEM_TEST_UTIL_DIR = os.path.abspath(SYSTEM_TEST_BASE_DIR + "/utils") SYSTEM_TEST_SUITE_SUFFIX = "_testsuite" SYSTEM_TEST_CASE_PREFIX = "testcase_" SYSTEM_TEST_MODULE_EXT = ".py" CLUSTER_CONFIG_FILENAME = "cluster_config.json" CLUSTER_CONFIG_PATHNAME = os.path.abspath(SYSTEM_TEST_BASE_DIR + "/" + CLUSTER_CONFIG_FILENAME) METRICS_FILENAME = "metrics.json" METRICS_PATHNAME = os.path.abspath(SYSTEM_TEST_BASE_DIR + "/" + METRICS_FILENAME) TESTCASE_TO_RUN_FILENAME = "testcase_to_run.json" TESTCASE_TO_RUN_PATHNAME = os.path.abspath(SYSTEM_TEST_BASE_DIR + "/" + TESTCASE_TO_RUN_FILENAME) TESTCASE_TO_SKIP_FILENAME = "testcase_to_skip.json" TESTCASE_TO_SKIP_PATHNAME = os.path.abspath(SYSTEM_TEST_BASE_DIR + "/" + TESTCASE_TO_SKIP_FILENAME) clusterEntityConfigDictList = [] # cluster entity config for current level clusterEntityConfigDictListInSystemTestLevel = [] # cluster entity config defined in system level clusterEntityConfigDictListLastFoundInTestSuite = [] # cluster entity config last found in testsuite level clusterEntityConfigDictListLastFoundInTestCase = [] # cluster entity config last found in testcase level systemTestResultsList = [] testCaseToRunListDict = {} testCaseToSkipListDict = {} printTestDescriptionsOnly = False doNotValidateRemoteHost = False def __init__(self): "Create an object with this system test session environment" # load the system level cluster config system_test_utils.load_cluster_config(self.CLUSTER_CONFIG_PATHNAME, self.clusterEntityConfigDictList) # save the system level cluster config self.clusterEntityConfigDictListInSystemTestLevel = copy.deepcopy(self.clusterEntityConfigDictList) # retrieve testcases to run from testcase_to_run.json try: testcaseToRunFileContent = open(self.TESTCASE_TO_RUN_PATHNAME, "r").read() testcaseToRunData = json.loads(testcaseToRunFileContent) for testClassName, caseList in testcaseToRunData.items(): self.testCaseToRunListDict[testClassName] = caseList except: pass # retrieve testcases to skip from testcase_to_skip.json try: testcaseToSkipFileContent = open(self.TESTCASE_TO_SKIP_PATHNAME, "r").read() testcaseToSkipData = json.loads(testcaseToSkipFileContent) for testClassName, caseList in testcaseToSkipData.items(): self.testCaseToSkipListDict[testClassName] = caseList except: pass def isTestCaseToSkip(self, testClassName, testcaseDirName): testCaseToRunList = {} testCaseToSkipList = {} try: testCaseToRunList = self.testCaseToRunListDict[testClassName] except: # no 'testClassName' found => no need to run any cases for this test class return True try: testCaseToSkipList = self.testCaseToSkipListDict[testClassName] except: pass # if testCaseToRunList has elements, it takes precedence: if len(testCaseToRunList) > 0: #print "#### testClassName => ", testClassName #print "#### testCaseToRunList => ", testCaseToRunList #print "#### testcaseDirName => ", testcaseDirName if not testcaseDirName in testCaseToRunList: #self.log_message("Skipping : " + testcaseDirName) return True elif len(testCaseToSkipList) > 0: #print "#### testClassName => ", testClassName #print "#### testCaseToSkipList => ", testCaseToSkipList #print "#### testcaseDirName => ", testcaseDirName if testcaseDirName in testCaseToSkipList: #self.log_message("Skipping : " + testcaseDirName) return True return False def getSystemTestEnvDict(self): envDict = {} envDict["system_test_base_dir"] = self.SYSTEM_TEST_BASE_DIR envDict["system_test_util_dir"] = self.SYSTEM_TEST_UTIL_DIR envDict["cluster_config_pathname"] = self.CLUSTER_CONFIG_PATHNAME envDict["system_test_suite_suffix"] = self.SYSTEM_TEST_SUITE_SUFFIX envDict["system_test_case_prefix"] = self.SYSTEM_TEST_CASE_PREFIX envDict["system_test_module_ext"] = self.SYSTEM_TEST_MODULE_EXT envDict["cluster_config_pathname"] = self.CLUSTER_CONFIG_PATHNAME envDict["cluster_entity_config_dict_list"] = self.clusterEntityConfigDictList envDict["system_test_results_list"] = self.systemTestResultsList return envDict
44.266187
113
0.675443
4f50e2d175e110602a125a0c85f853d363b8c394
14,370
py
Python
kubernetes/client/models/v1_node_system_info.py
henrywu2019/python
fb7214144395c05349e70a58ea129576f6b11fc4
[ "Apache-2.0" ]
4,417
2018-01-13T04:30:48.000Z
2022-03-31T15:33:59.000Z
kubernetes/client/models/v1_node_system_info.py
g1f1/python-1
da6076070b2ada0e048e060943b94358213c414b
[ "Apache-2.0" ]
1,414
2018-01-12T19:31:56.000Z
2022-03-31T22:01:02.000Z
kubernetes/client/models/v1_node_system_info.py
g1f1/python-1
da6076070b2ada0e048e060943b94358213c414b
[ "Apache-2.0" ]
2,854
2018-01-14T08:57:33.000Z
2022-03-31T01:41:56.000Z
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: release-1.21 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from kubernetes.client.configuration import Configuration class V1NodeSystemInfo(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_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. """ openapi_types = { 'architecture': 'str', 'boot_id': 'str', 'container_runtime_version': 'str', 'kernel_version': 'str', 'kube_proxy_version': 'str', 'kubelet_version': 'str', 'machine_id': 'str', 'operating_system': 'str', 'os_image': 'str', 'system_uuid': 'str' } attribute_map = { 'architecture': 'architecture', 'boot_id': 'bootID', 'container_runtime_version': 'containerRuntimeVersion', 'kernel_version': 'kernelVersion', 'kube_proxy_version': 'kubeProxyVersion', 'kubelet_version': 'kubeletVersion', 'machine_id': 'machineID', 'operating_system': 'operatingSystem', 'os_image': 'osImage', 'system_uuid': 'systemUUID' } def __init__(self, architecture=None, boot_id=None, container_runtime_version=None, kernel_version=None, kube_proxy_version=None, kubelet_version=None, machine_id=None, operating_system=None, os_image=None, system_uuid=None, local_vars_configuration=None): # noqa: E501 """V1NodeSystemInfo - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._architecture = None self._boot_id = None self._container_runtime_version = None self._kernel_version = None self._kube_proxy_version = None self._kubelet_version = None self._machine_id = None self._operating_system = None self._os_image = None self._system_uuid = None self.discriminator = None self.architecture = architecture self.boot_id = boot_id self.container_runtime_version = container_runtime_version self.kernel_version = kernel_version self.kube_proxy_version = kube_proxy_version self.kubelet_version = kubelet_version self.machine_id = machine_id self.operating_system = operating_system self.os_image = os_image self.system_uuid = system_uuid @property def architecture(self): """Gets the architecture of this V1NodeSystemInfo. # noqa: E501 The Architecture reported by the node # noqa: E501 :return: The architecture of this V1NodeSystemInfo. # noqa: E501 :rtype: str """ return self._architecture @architecture.setter def architecture(self, architecture): """Sets the architecture of this V1NodeSystemInfo. The Architecture reported by the node # noqa: E501 :param architecture: The architecture of this V1NodeSystemInfo. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and architecture is None: # noqa: E501 raise ValueError("Invalid value for `architecture`, must not be `None`") # noqa: E501 self._architecture = architecture @property def boot_id(self): """Gets the boot_id of this V1NodeSystemInfo. # noqa: E501 Boot ID reported by the node. # noqa: E501 :return: The boot_id of this V1NodeSystemInfo. # noqa: E501 :rtype: str """ return self._boot_id @boot_id.setter def boot_id(self, boot_id): """Sets the boot_id of this V1NodeSystemInfo. Boot ID reported by the node. # noqa: E501 :param boot_id: The boot_id of this V1NodeSystemInfo. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and boot_id is None: # noqa: E501 raise ValueError("Invalid value for `boot_id`, must not be `None`") # noqa: E501 self._boot_id = boot_id @property def container_runtime_version(self): """Gets the container_runtime_version of this V1NodeSystemInfo. # noqa: E501 ContainerRuntime Version reported by the node through runtime remote API (e.g. docker://1.5.0). # noqa: E501 :return: The container_runtime_version of this V1NodeSystemInfo. # noqa: E501 :rtype: str """ return self._container_runtime_version @container_runtime_version.setter def container_runtime_version(self, container_runtime_version): """Sets the container_runtime_version of this V1NodeSystemInfo. ContainerRuntime Version reported by the node through runtime remote API (e.g. docker://1.5.0). # noqa: E501 :param container_runtime_version: The container_runtime_version of this V1NodeSystemInfo. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and container_runtime_version is None: # noqa: E501 raise ValueError("Invalid value for `container_runtime_version`, must not be `None`") # noqa: E501 self._container_runtime_version = container_runtime_version @property def kernel_version(self): """Gets the kernel_version of this V1NodeSystemInfo. # noqa: E501 Kernel Version reported by the node from 'uname -r' (e.g. 3.16.0-0.bpo.4-amd64). # noqa: E501 :return: The kernel_version of this V1NodeSystemInfo. # noqa: E501 :rtype: str """ return self._kernel_version @kernel_version.setter def kernel_version(self, kernel_version): """Sets the kernel_version of this V1NodeSystemInfo. Kernel Version reported by the node from 'uname -r' (e.g. 3.16.0-0.bpo.4-amd64). # noqa: E501 :param kernel_version: The kernel_version of this V1NodeSystemInfo. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and kernel_version is None: # noqa: E501 raise ValueError("Invalid value for `kernel_version`, must not be `None`") # noqa: E501 self._kernel_version = kernel_version @property def kube_proxy_version(self): """Gets the kube_proxy_version of this V1NodeSystemInfo. # noqa: E501 KubeProxy Version reported by the node. # noqa: E501 :return: The kube_proxy_version of this V1NodeSystemInfo. # noqa: E501 :rtype: str """ return self._kube_proxy_version @kube_proxy_version.setter def kube_proxy_version(self, kube_proxy_version): """Sets the kube_proxy_version of this V1NodeSystemInfo. KubeProxy Version reported by the node. # noqa: E501 :param kube_proxy_version: The kube_proxy_version of this V1NodeSystemInfo. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and kube_proxy_version is None: # noqa: E501 raise ValueError("Invalid value for `kube_proxy_version`, must not be `None`") # noqa: E501 self._kube_proxy_version = kube_proxy_version @property def kubelet_version(self): """Gets the kubelet_version of this V1NodeSystemInfo. # noqa: E501 Kubelet Version reported by the node. # noqa: E501 :return: The kubelet_version of this V1NodeSystemInfo. # noqa: E501 :rtype: str """ return self._kubelet_version @kubelet_version.setter def kubelet_version(self, kubelet_version): """Sets the kubelet_version of this V1NodeSystemInfo. Kubelet Version reported by the node. # noqa: E501 :param kubelet_version: The kubelet_version of this V1NodeSystemInfo. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and kubelet_version is None: # noqa: E501 raise ValueError("Invalid value for `kubelet_version`, must not be `None`") # noqa: E501 self._kubelet_version = kubelet_version @property def machine_id(self): """Gets the machine_id of this V1NodeSystemInfo. # noqa: E501 MachineID reported by the node. For unique machine identification in the cluster this field is preferred. Learn more from man(5) machine-id: http://man7.org/linux/man-pages/man5/machine-id.5.html # noqa: E501 :return: The machine_id of this V1NodeSystemInfo. # noqa: E501 :rtype: str """ return self._machine_id @machine_id.setter def machine_id(self, machine_id): """Sets the machine_id of this V1NodeSystemInfo. MachineID reported by the node. For unique machine identification in the cluster this field is preferred. Learn more from man(5) machine-id: http://man7.org/linux/man-pages/man5/machine-id.5.html # noqa: E501 :param machine_id: The machine_id of this V1NodeSystemInfo. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and machine_id is None: # noqa: E501 raise ValueError("Invalid value for `machine_id`, must not be `None`") # noqa: E501 self._machine_id = machine_id @property def operating_system(self): """Gets the operating_system of this V1NodeSystemInfo. # noqa: E501 The Operating System reported by the node # noqa: E501 :return: The operating_system of this V1NodeSystemInfo. # noqa: E501 :rtype: str """ return self._operating_system @operating_system.setter def operating_system(self, operating_system): """Sets the operating_system of this V1NodeSystemInfo. The Operating System reported by the node # noqa: E501 :param operating_system: The operating_system of this V1NodeSystemInfo. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and operating_system is None: # noqa: E501 raise ValueError("Invalid value for `operating_system`, must not be `None`") # noqa: E501 self._operating_system = operating_system @property def os_image(self): """Gets the os_image of this V1NodeSystemInfo. # noqa: E501 OS Image reported by the node from /etc/os-release (e.g. Debian GNU/Linux 7 (wheezy)). # noqa: E501 :return: The os_image of this V1NodeSystemInfo. # noqa: E501 :rtype: str """ return self._os_image @os_image.setter def os_image(self, os_image): """Sets the os_image of this V1NodeSystemInfo. OS Image reported by the node from /etc/os-release (e.g. Debian GNU/Linux 7 (wheezy)). # noqa: E501 :param os_image: The os_image of this V1NodeSystemInfo. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and os_image is None: # noqa: E501 raise ValueError("Invalid value for `os_image`, must not be `None`") # noqa: E501 self._os_image = os_image @property def system_uuid(self): """Gets the system_uuid of this V1NodeSystemInfo. # noqa: E501 SystemUUID reported by the node. For unique machine identification MachineID is preferred. This field is specific to Red Hat hosts https://access.redhat.com/documentation/en-us/red_hat_subscription_management/1/html/rhsm/uuid # noqa: E501 :return: The system_uuid of this V1NodeSystemInfo. # noqa: E501 :rtype: str """ return self._system_uuid @system_uuid.setter def system_uuid(self, system_uuid): """Sets the system_uuid of this V1NodeSystemInfo. SystemUUID reported by the node. For unique machine identification MachineID is preferred. This field is specific to Red Hat hosts https://access.redhat.com/documentation/en-us/red_hat_subscription_management/1/html/rhsm/uuid # noqa: E501 :param system_uuid: The system_uuid of this V1NodeSystemInfo. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and system_uuid is None: # noqa: E501 raise ValueError("Invalid value for `system_uuid`, must not be `None`") # noqa: E501 self._system_uuid = system_uuid def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1NodeSystemInfo): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1NodeSystemInfo): return True return self.to_dict() != other.to_dict()
37.324675
274
0.653236
abe6cf25e2c23c55ae15fb8e915e9c56ea873299
2,786
py
Python
4 text_predict.py
dreamer221/text_cnn_model_pb
e532e6106d2e877867e09e7ef1d18d6ad6a56d49
[ "MIT" ]
null
null
null
4 text_predict.py
dreamer221/text_cnn_model_pb
e532e6106d2e877867e09e7ef1d18d6ad6a56d49
[ "MIT" ]
null
null
null
4 text_predict.py
dreamer221/text_cnn_model_pb
e532e6106d2e877867e09e7ef1d18d6ad6a56d49
[ "MIT" ]
null
null
null
# encoding:utf-8 from text_model import * import tensorflow as tf import tensorflow.contrib.keras as kr from loader import read_vocab import jieba import re import codecs def predict(sentences): _, word_to_id = read_vocab(config.vocab_filename) input_x2 = process_file(sentences, word_to_id, max_length=config.seq_length) labels = {0: '体育', 1: '财经', 2: '房产', 3: '家居', 4: '教育', 5: '科技', 6: '时尚', 7: '时政', 8: '游戏', 9: '娱乐'} output_graph_def = tf.compat.v1.GraphDef() with open(model_file, "rb") as f: output_graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(output_graph_def, name="") with tf.Session() as session: input_x = session.graph.get_tensor_by_name("input_x:0") keep_prob = session.graph.get_tensor_by_name("dropout:0") prediction = session.graph.get_tensor_by_name("output/predict:0") feed_dict = {input_x: input_x2, keep_prob: 1.0} y_prob = session.run(prediction, feed_dict=feed_dict) y_prob = y_prob.tolist() cat = [] for prob in y_prob: cat.append(labels[prob]) return cat def sentence_cut(sentences): re_han = re.compile(u"([\u4E00-\u9FD5a-zA-Z0-9+#&\._%]+)") # the method of cutting text by punctuation seglist = [] for sentence in sentences: words = [] blocks = re_han.split(sentence) for blk in blocks: if re_han.match(blk): words.extend(jieba.lcut(blk)) seglist.append(words) return seglist def process_file(sentences, word_to_id, max_length=600): data_id = [] seglist = sentence_cut(sentences) for i in range(len(seglist)): data_id.append([word_to_id[x] for x in seglist[i] if x in word_to_id]) x_pad = kr.preprocessing.sequence.pad_sequences(data_id, max_length) return x_pad if __name__ == '__main__': import random config = TextConfig() model_file = './checkpoints/cnn_model.pb' sentences = [] labels = [] with codecs.open('./data/cnews.test.txt', 'r', encoding='utf-8') as f: sample = random.sample(f.readlines(), 5) for line in sample: try: line = line.rstrip().split('\t') assert len(line) == 2 sentences.append(line[1]) labels.append(line[0]) except: pass cat = predict(sentences) for i, sentence in enumerate(sentences, 0): print('----------------------the text-------------------------') print(sentence[:50] + '....') print('the true label:%s' % labels[i]) print('the predict label:%s' % cat[i])
31.659091
107
0.574659
ff947dc2f3910d5af576dc984c25dc93b1389941
3,329
py
Python
pypureclient/flasharray/FA_2_6/models/reference.py
Flav-STOR-WL/py-pure-client
03b889c997d90380ac5d6380ca5d5432792d3e89
[ "BSD-2-Clause" ]
14
2018-12-07T18:30:27.000Z
2022-02-22T09:12:33.000Z
pypureclient/flasharray/FA_2_6/models/reference.py
Flav-STOR-WL/py-pure-client
03b889c997d90380ac5d6380ca5d5432792d3e89
[ "BSD-2-Clause" ]
28
2019-09-17T21:03:52.000Z
2022-03-29T22:07:35.000Z
pypureclient/flasharray/FA_2_6/models/reference.py
Flav-STOR-WL/py-pure-client
03b889c997d90380ac5d6380ca5d5432792d3e89
[ "BSD-2-Clause" ]
15
2020-06-11T15:50:08.000Z
2022-03-21T09:27:25.000Z
# coding: utf-8 """ FlashArray REST API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 2.6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re import six import typing from ....properties import Property if typing.TYPE_CHECKING: from pypureclient.flasharray.FA_2_6 import models class Reference(object): """ 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 = { 'id': 'str', 'name': 'str' } attribute_map = { 'id': 'id', 'name': 'name' } required_args = { } def __init__( self, id=None, # type: str name=None, # type: str ): """ Keyword args: id (str): A globally unique, system-generated ID. The ID cannot be modified. name (str): The resource name, such as volume name, pod name, snapshot name, and so on. """ if id is not None: self.id = id if name is not None: self.name = name def __setattr__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `Reference`".format(key)) self.__dict__[key] = value def __getattribute__(self, item): value = object.__getattribute__(self, item) if isinstance(value, Property): raise AttributeError else: return value def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): if hasattr(self, attr): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(Reference, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, Reference): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
28.211864
105
0.534695
4ca7134325c720758954d975d40b7b1a7b081637
1,262
py
Python
Old/src/com/basic/filter.py
exchris/Pythonlearn
174f38a86cf1c85d6fc099005aab3568e7549cd0
[ "MIT" ]
null
null
null
Old/src/com/basic/filter.py
exchris/Pythonlearn
174f38a86cf1c85d6fc099005aab3568e7549cd0
[ "MIT" ]
1
2018-11-27T09:58:54.000Z
2018-11-27T09:58:54.000Z
Old/src/com/basic/filter.py
exchris/pythonlearn
174f38a86cf1c85d6fc099005aab3568e7549cd0
[ "MIT" ]
null
null
null
# -*- coding:utf-8 -*- ''' 和map()类似,filter()也接收一个函数和一个序列。 和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素 例如:在一个list中,删掉偶数,只保留奇数,可以这么写 ''' def is_odd(n) : return n % 2 == 1 odd = list(filter(is_odd, [1,2,4,5,6,9,10,15])) print(odd) # 打印奇数 # 把一个序列中的空字符串删掉,可以这么写: def not_empty(s) : return s and s.strip() notEmpty = list(filter(not_empty, ['A','','B',None,'C',''])) print(notEmpty) # 结果: ['A','B','C'] # 注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,所有要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list. ''' 用filter求素数 计算素数的一个方法是埃氏2筛法 ''' # 构造一个从3开始的奇数序列 def _odd_iter() : n = 1 while True : n = n + 2 yield n # 定义一个筛选函数 def _not_divisible(n) : return lambda x : x % n > 0 # 最后定义一个生成器,不断返回下一个素数: def primes() : yield 2 it = _odd_iter() # 初始序列 while True : n = next(it) # 返回序列的第一个数 yield n it = filter(_not_divisible(n), it) # 构造新序列 # 由于primes()也是一个无限序列,所以调用时需要设置一个退出循环的条件: # 打印100以内的素数: for n in primes() : if n < 100: print(n) else : break # 回数是指从左向右读和从右向左读都是一样的数,例如12321,909.请利用filter()滤掉非回数 def is_palindrome(n) : return str(n) == str(n)[::-1] output = filter(is_palindrome, range(11, 100)) print(list(output)) # 结果:[11,22,33,44,55,66,77,88,99]
20.031746
85
0.62916
1acd17c3fbbe93a0d37e50590a9e52d78ace5fb4
19,795
py
Python
lib/storage.py
GetAywa/electrum-aywa
07a548bd14cdf563da49c1f1e52644b833ca972e
[ "MIT" ]
null
null
null
lib/storage.py
GetAywa/electrum-aywa
07a548bd14cdf563da49c1f1e52644b833ca972e
[ "MIT" ]
null
null
null
lib/storage.py
GetAywa/electrum-aywa
07a548bd14cdf563da49c1f1e52644b833ca972e
[ "MIT" ]
4
2018-07-07T16:35:50.000Z
2018-12-25T16:02:52.000Z
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2015 Thomas Voegtlin # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import ast import threading import json import copy import re import stat import pbkdf2, hmac, hashlib import base64 import zlib from .util import PrintError, profiler from .plugins import run_hook, plugin_loaders from .keystore import bip44_derivation from . import bitcoin # seed_version is now used for the version of the wallet file OLD_SEED_VERSION = 4 # electrum versions < 2.0 NEW_SEED_VERSION = 11 # electrum versions >= 2.0 FINAL_SEED_VERSION = 16 # electrum >= 2.7 will set this to prevent # old versions from overwriting new format def multisig_type(wallet_type): '''If wallet_type is mofn multi-sig, return [m, n], otherwise return None.''' match = re.match('(\d+)of(\d+)', wallet_type) if match: match = [int(x) for x in match.group(1, 2)] return match class WalletStorage(PrintError): def __init__(self, path, manual_upgrades=False): self.print_error("wallet path", path) self.manual_upgrades = manual_upgrades self.lock = threading.RLock() self.data = {} self.path = path self.modified = False self.pubkey = None if self.file_exists(): with open(self.path, "r") as f: self.raw = f.read() if not self.is_encrypted(): self.load_data(self.raw) else: # avoid new wallets getting 'upgraded' self.put('seed_version', FINAL_SEED_VERSION) def load_data(self, s): try: self.data = json.loads(s) except: try: d = ast.literal_eval(s) labels = d.get('labels', {}) except Exception as e: raise IOError("Cannot read wallet file '%s'" % self.path) self.data = {} for key, value in d.items(): try: json.dumps(key) json.dumps(value) except: self.print_error('Failed to convert label to json format', key) continue self.data[key] = value # check here if I need to load a plugin t = self.get('wallet_type') l = plugin_loaders.get(t) if l: l() if not self.manual_upgrades: if self.requires_split(): raise BaseException("This wallet has multiple accounts and must be split") if self.requires_upgrade(): self.upgrade() def is_encrypted(self): try: return base64.b64decode(self.raw)[0:4] == b'BIE1' except: return False def file_exists(self): return self.path and os.path.exists(self.path) def get_key(self, password): secret = pbkdf2.PBKDF2(password, '', iterations = 1024, macmodule = hmac, digestmodule = hashlib.sha512).read(64) ec_key = bitcoin.EC_KEY(secret) return ec_key def decrypt(self, password): ec_key = self.get_key(password) s = zlib.decompress(ec_key.decrypt_message(self.raw)) if self.raw else None self.pubkey = ec_key.get_public_key() s = s.decode('utf8') self.load_data(s) def set_password(self, password, encrypt): self.put('use_encryption', bool(password)) if encrypt and password: ec_key = self.get_key(password) self.pubkey = ec_key.get_public_key() else: self.pubkey = None def get(self, key, default=None): with self.lock: v = self.data.get(key) if v is None: v = default else: v = copy.deepcopy(v) return v def put(self, key, value): try: json.dumps(key) json.dumps(value) except: self.print_error("json error: cannot save", key) return with self.lock: if value is not None: if self.data.get(key) != value: self.modified = True self.data[key] = copy.deepcopy(value) elif key in self.data: self.modified = True self.data.pop(key) @profiler def write(self): with self.lock: self._write() def _write(self): if threading.currentThread().isDaemon(): self.print_error('warning: daemon thread cannot write wallet') return if not self.modified: return s = json.dumps(self.data, indent=4, sort_keys=True) if self.pubkey: s = bytes(s, 'utf8') c = zlib.compress(s) s = bitcoin.encrypt_message(c, self.pubkey) s = s.decode('utf8') temp_path = "%s.tmp.%s" % (self.path, os.getpid()) with open(temp_path, "w") as f: f.write(s) f.flush() os.fsync(f.fileno()) mode = os.stat(self.path).st_mode if os.path.exists(self.path) else stat.S_IREAD | stat.S_IWRITE # perform atomic write on POSIX systems try: os.rename(temp_path, self.path) except: os.remove(self.path) os.rename(temp_path, self.path) os.chmod(self.path, mode) self.print_error("saved", self.path) self.modified = False def requires_split(self): d = self.get('accounts', {}) return len(d) > 1 def split_accounts(storage): result = [] # backward compatibility with old wallets d = storage.get('accounts', {}) if len(d) < 2: return wallet_type = storage.get('wallet_type') if wallet_type == 'old': assert len(d) == 2 storage1 = WalletStorage(storage.path + '.deterministic') storage1.data = copy.deepcopy(storage.data) storage1.put('accounts', {'0': d['0']}) storage1.upgrade() storage1.write() storage2 = WalletStorage(storage.path + '.imported') storage2.data = copy.deepcopy(storage.data) storage2.put('accounts', {'/x': d['/x']}) storage2.put('seed', None) storage2.put('seed_version', None) storage2.put('master_public_key', None) storage2.put('wallet_type', 'imported') storage2.upgrade() storage2.write() result = [storage1.path, storage2.path] elif wallet_type in ['bip44', 'trezor', 'keepkey', 'ledger', 'btchip', 'digitalbitbox']: mpk = storage.get('master_public_keys') for k in d.keys(): i = int(k) x = d[k] if x.get("pending"): continue xpub = mpk["x/%d'"%i] new_path = storage.path + '.' + k storage2 = WalletStorage(new_path) storage2.data = copy.deepcopy(storage.data) # save account, derivation and xpub at index 0 storage2.put('accounts', {'0': x}) storage2.put('master_public_keys', {"x/0'": xpub}) storage2.put('derivation', bip44_derivation(k)) storage2.upgrade() storage2.write() result.append(new_path) else: raise BaseException("This wallet has multiple accounts and must be split") return result def requires_upgrade(self): return self.file_exists() and self.get_seed_version() < FINAL_SEED_VERSION def upgrade(self): self.print_error('upgrading wallet format') if self.requires_upgrade(): self.backup_old_version() self.convert_imported() self.convert_wallet_type() self.convert_account() self.convert_version_13_b() self.convert_version_14() self.convert_version_15() self.convert_version_16() self.put('seed_version', FINAL_SEED_VERSION) # just to be sure self.write() def backup_old_version(self): from datetime import datetime now = datetime.now() now_str = now.strftime('%Y%m%d_%H%M%S') backup_file = '%s_%s.back' % (self.path, now_str) if not os.path.exists(backup_file): from shutil import copyfile, copymode copyfile(self.path, backup_file) copymode(self.path, backup_file) self.backup_file = backup_file self.backup_message = ('Wallet was upgraded to new version.' ' Backup copy of old wallet version' ' placed at: %s' % backup_file) def convert_wallet_type(self): wallet_type = self.get('wallet_type') if wallet_type == 'btchip': wallet_type = 'ledger' if self.get('keystore') or self.get('x1/') or wallet_type=='imported': return False assert not self.requires_split() seed_version = self.get_seed_version() seed = self.get('seed') xpubs = self.get('master_public_keys') xprvs = self.get('master_private_keys', {}) mpk = self.get('master_public_key') keypairs = self.get('keypairs') key_type = self.get('key_type') if seed_version == OLD_SEED_VERSION or wallet_type == 'old': d = { 'type': 'old', 'seed': seed, 'mpk': mpk, } self.put('wallet_type', 'standard') self.put('keystore', d) elif key_type == 'imported': d = { 'type': 'imported', 'keypairs': keypairs, } self.put('wallet_type', 'standard') self.put('keystore', d) elif wallet_type in ['xpub', 'standard']: xpub = xpubs["x/"] xprv = xprvs.get("x/") d = { 'type': 'bip32', 'xpub': xpub, 'xprv': xprv, 'seed': seed, } self.put('wallet_type', 'standard') self.put('keystore', d) elif wallet_type in ['bip44']: xpub = xpubs["x/0'"] xprv = xprvs.get("x/0'") d = { 'type': 'bip32', 'xpub': xpub, 'xprv': xprv, } self.put('wallet_type', 'standard') self.put('keystore', d) elif wallet_type in ['trezor', 'keepkey', 'ledger', 'digitalbitbox']: xpub = xpubs["x/0'"] derivation = self.get('derivation', bip44_derivation(0)) d = { 'type': 'hardware', 'hw_type': wallet_type, 'xpub': xpub, 'derivation': derivation, } self.put('wallet_type', 'standard') self.put('keystore', d) elif multisig_type(wallet_type): for key in xpubs.keys(): d = { 'type': 'bip32', 'xpub': xpubs[key], 'xprv': xprvs.get(key), } if key == 'x1/' and seed: d['seed'] = seed self.put(key, d) else: raise # remove junk self.put('master_public_key', None) self.put('master_public_keys', None) self.put('master_private_keys', None) self.put('derivation', None) self.put('seed', None) self.put('keypairs', None) self.put('key_type', None) def convert_version_13_b(self): # version 13 is ambiguous, and has an earlier and a later structure if not self._is_upgrade_method_needed(0, 13): return if self.get('wallet_type') == 'standard': if self.get('keystore').get('type') == 'imported': pubkeys = self.get('keystore').get('keypairs').keys() d = {'change': []} receiving_addresses = [] for pubkey in pubkeys: addr = bitcoin.pubkey_to_address('p2pkh', pubkey) receiving_addresses.append(addr) d['receiving'] = receiving_addresses self.put('addresses', d) self.put('pubkeys', None) self.put('seed_version', 13) def convert_version_14(self): # convert imported wallets for 3.0 if not self._is_upgrade_method_needed(13, 13): return if self.get('wallet_type') =='imported': addresses = self.get('addresses') if type(addresses) is list: addresses = dict([(x, None) for x in addresses]) self.put('addresses', addresses) elif self.get('wallet_type') == 'standard': if self.get('keystore').get('type')=='imported': addresses = set(self.get('addresses').get('receiving')) pubkeys = self.get('keystore').get('keypairs').keys() assert len(addresses) == len(pubkeys) d = {} for pubkey in pubkeys: addr = bitcoin.pubkey_to_address('p2pkh', pubkey) assert addr in addresses d[addr] = { 'pubkey': pubkey, 'redeem_script': None, 'type': 'p2pkh' } self.put('addresses', d) self.put('pubkeys', None) self.put('wallet_type', 'imported') self.put('seed_version', 14) def convert_version_15(self): if not self._is_upgrade_method_needed(14, 14): return self.put('seed_version', 15) def convert_version_16(self): # fixes issue #3193 for Imported_Wallets with addresses # also, previous versions allowed importing any garbage as an address # which we now try to remove, see pr #3191 if not self._is_upgrade_method_needed(15, 15): return def remove_address(addr): def remove_from_dict(dict_name): d = self.get(dict_name, None) if d is not None: d.pop(addr, None) self.put(dict_name, d) def remove_from_list(list_name): lst = self.get(list_name, None) if lst is not None: s = set(lst) s -= {addr} self.put(list_name, list(s)) # note: we don't remove 'addr' from self.get('addresses') remove_from_dict('addr_history') remove_from_dict('labels') remove_from_dict('payment_requests') remove_from_list('frozen_addresses') if self.get('wallet_type') == 'imported': addresses = self.get('addresses') assert isinstance(addresses, dict) addresses_new = dict() for address, details in addresses.items(): if not bitcoin.is_address(address): remove_address(address) continue if details is None: addresses_new[address] = {} else: addresses_new[address] = details self.put('addresses', addresses_new) self.put('seed_version', 16) def convert_imported(self): # '/x' is the internal ID for imported accounts d = self.get('accounts', {}).get('/x', {}).get('imported',{}) if not d: return False addresses = [] keypairs = {} for addr, v in d.items(): pubkey, privkey = v if privkey: keypairs[pubkey] = privkey else: addresses.append(addr) if addresses and keypairs: raise BaseException('mixed addresses and privkeys') elif addresses: self.put('addresses', addresses) self.put('accounts', None) elif keypairs: self.put('wallet_type', 'standard') self.put('key_type', 'imported') self.put('keypairs', keypairs) self.put('accounts', None) else: raise BaseException('no addresses or privkeys') def convert_account(self): self.put('accounts', None) def _is_upgrade_method_needed(self, min_version, max_version): cur_version = self.get_seed_version() if cur_version > max_version: return False elif cur_version < min_version: raise BaseException( ('storage upgrade: unexpected version %d (should be %d-%d)' % (cur_version, min_version, max_version))) else: return True def get_action(self): action = run_hook('get_action', self) if action: return action if not self.file_exists(): return 'new' def get_seed_version(self): seed_version = self.get('seed_version') if not seed_version: seed_version = OLD_SEED_VERSION if len(self.get('master_public_key','')) == 128 else NEW_SEED_VERSION if seed_version > FINAL_SEED_VERSION: raise BaseException('This version of Electrum is too old to open this wallet') if seed_version >=12: return seed_version if seed_version not in [OLD_SEED_VERSION, NEW_SEED_VERSION]: self.raise_unsupported_version(seed_version) return seed_version def raise_unsupported_version(self, seed_version): msg = "Your wallet has an unsupported seed version." msg += '\n\nWallet file: %s' % os.path.abspath(self.path) if seed_version in [5, 7, 8, 9, 10, 14]: msg += "\n\nTo open this wallet, try 'git checkout seed_v%d'"%seed_version if seed_version == 6: # version 1.9.8 created v6 wallets when an incorrect seed was entered in the restore dialog msg += '\n\nThis file was created because of a bug in version 1.9.8.' if self.get('master_public_keys') is None and self.get('master_private_keys') is None and self.get('imported_keys') is None: # pbkdf2 was not included with the binaries, and wallet creation aborted. msg += "\nIt does not contain any keys, and can safely be removed." else: # creation was complete if electrum was run from source msg += "\nPlease open this file with Electrum 1.9.8, and move your coins to a new wallet." raise BaseException(msg)
36.862197
136
0.551149
4ce81f0531e45823c68b1ec70784052df3bdccf4
456
py
Python
project/app/urls.py
NPriyajit/DevChroma-Django-WebApp
b89a8ac36913ec8c56be537c53ce91c0b7719b51
[ "MIT" ]
null
null
null
project/app/urls.py
NPriyajit/DevChroma-Django-WebApp
b89a8ac36913ec8c56be537c53ce91c0b7719b51
[ "MIT" ]
null
null
null
project/app/urls.py
NPriyajit/DevChroma-Django-WebApp
b89a8ac36913ec8c56be537c53ce91c0b7719b51
[ "MIT" ]
null
null
null
from django.urls import path, include from app import views urlpatterns = [ path('',views.home,name="home"), path('blog',views.handleblog,name="handleblog"), path('contact',views.contact,name="contact"), path('about',views.about,name="about"), path('services',views.services,name="services"), path('login',views.handleLogin,name="handleLogin"), path('signup',views.signup,name="signup"), path('dev',views.dev,name="dev") ]
32.571429
55
0.679825
f0dbae5ae8cd43b05ce41fee080e206f14b03718
177
py
Python
fineName.py
yuhengfdada/Document-Image-Rectification-with-Deep-Learning
22070270fe21e06c5aa08a839531a3d6fabb1592
[ "MIT" ]
2
2020-08-19T03:21:09.000Z
2022-03-25T07:37:55.000Z
fineName.py
yuhengfdada/Document-Image-Rectification-with-Deep-Learning
22070270fe21e06c5aa08a839531a3d6fabb1592
[ "MIT" ]
null
null
null
fineName.py
yuhengfdada/Document-Image-Rectification-with-Deep-Learning
22070270fe21e06c5aa08a839531a3d6fabb1592
[ "MIT" ]
1
2020-09-17T09:41:30.000Z
2020-09-17T09:41:30.000Z
'''from pathlib import Path p = Path('.') li = list(p.glob('*.png')) f = open('test.txt','w') for i, file in enumerate(li): f.write(file.stem) f.write('\n') f.close()'''
22.125
29
0.570621
5be7b2afbd354463434547c58a484c4567ed5801
2,360
py
Python
qtpyvcp/widgets/dialogs/probesim_dialog.py
Lcvette/qtpyvcp
4143a4a4e1f557f7d0c8998c886b4a254f0be60b
[ "BSD-3-Clause-LBNL", "MIT" ]
71
2018-12-13T20:31:18.000Z
2022-03-26T08:44:22.000Z
qtpyvcp/widgets/dialogs/probesim_dialog.py
adargel/qtpyvcp
2fcb9c26616ac4effa8d92befa9e1c00a80daafa
[ "BSD-3-Clause-LBNL", "MIT" ]
78
2019-01-10T18:16:33.000Z
2022-03-18T19:30:49.000Z
qtpyvcp/widgets/dialogs/probesim_dialog.py
adargel/qtpyvcp
2fcb9c26616ac4effa8d92befa9e1c00a80daafa
[ "BSD-3-Clause-LBNL", "MIT" ]
38
2018-10-10T19:02:26.000Z
2022-01-30T04:38:14.000Z
# Copyright (c) 2018 Kurt Jacobson # <kurtcjacobson@gmail.com> # # This file is part of QtPyVCP. # # QtPyVCP 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. # # QtPyVCP 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 QtPyVCP. If not, see <http://www.gnu.org/licenses/>. import subprocess from qtpy.QtCore import QTimer from qtpy.QtWidgets import QPushButton, QVBoxLayout, QCheckBox from qtpyvcp.widgets.dialogs.base_dialog import BaseDialog from qtpyvcp.utilities.info import Info from qtpyvcp.utilities import logger Log = logger.getLogger(__name__) class ProbeSim(BaseDialog): def __init__(self, parent=None): super(ProbeSim, self).__init__(parent=parent) self.info = Info() self.log = Log self.close_button = QPushButton("Touch") self.pulse_checkbox = QCheckBox("Pulse") main_layout = QVBoxLayout() main_layout.addWidget(self.close_button) main_layout.addWidget(self.pulse_checkbox) self.setLayout(main_layout) self.setWindowTitle("Simulate touch probe") self.close_button.pressed.connect(self.touch_on) self.close_button.released.connect(self.touch_off) self.timer = QTimer() self.timer.timeout.connect(self.pulse_off) self.timer.setSingleShot(True) def touch_on(self): if self.pulse_checkbox.checkState(): self.timer.start(1000) subprocess.Popen(['halcmd', 'setp', 'motion.probe-input', '1']) else: subprocess.Popen(['halcmd', 'setp', 'motion.probe-input', '1']) def touch_off(self): if self.pulse_checkbox.checkState(): return subprocess.Popen(['halcmd', 'setp', 'motion.probe-input', '0']) def pulse_off(self): subprocess.Popen(['halcmd', 'setp', 'motion.probe-input', '0']) def close(self): self.hide()
29.5
75
0.676695
83f7616435bb56d0fd5629fd572d5eff240ddcaf
412
py
Python
scipy/optimize/cython_optimize/setup.py
jcharlong/scipy
153467a9174b0c6f4b90ffeed5871e5018658108
[ "BSD-3-Clause" ]
9,095
2015-01-02T18:24:23.000Z
2022-03-31T20:35:31.000Z
scipy/optimize/cython_optimize/setup.py
jcharlong/scipy
153467a9174b0c6f4b90ffeed5871e5018658108
[ "BSD-3-Clause" ]
11,500
2015-01-01T01:15:30.000Z
2022-03-31T23:07:35.000Z
scipy/optimize/cython_optimize/setup.py
jcharlong/scipy
153467a9174b0c6f4b90ffeed5871e5018658108
[ "BSD-3-Clause" ]
5,838
2015-01-05T11:56:42.000Z
2022-03-31T23:21:19.000Z
def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('cython_optimize', parent_package, top_path) config.add_data_files('*.pxd') config.add_extension('_zeros', sources='_zeros.c') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
29.428571
71
0.730583
8f7b2f64fef2b0e38c810ab3276965e0b22e0fe4
7,739
py
Python
tensorflow-posenet-keras/quantize_graph_image_keras.py
hulop/CNNLocalizationTF
90903916d2c7b95ec9e3851db4919fc0e1485bbf
[ "MIT" ]
2
2018-08-10T21:15:18.000Z
2021-12-22T17:29:41.000Z
tensorflow-posenet-keras/quantize_graph_image_keras.py
hulop/CNNLocalizationTF
90903916d2c7b95ec9e3851db4919fc0e1485bbf
[ "MIT" ]
null
null
null
tensorflow-posenet-keras/quantize_graph_image_keras.py
hulop/CNNLocalizationTF
90903916d2c7b95ec9e3851db4919fc0e1485bbf
[ "MIT" ]
4
2018-08-09T16:38:15.000Z
2021-04-11T19:54:20.000Z
############################################################################## #The MIT License (MIT) # #Copyright (c) 2018 IBM Corporation, Carnegie Mellon University and others # #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: # #The above copyright notice and this permission notice shall be included in all #copies or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE. ############################################################################## import argparse import os import sys import subprocess import tensorflow as tf from posenet_config import posenet_config tensorflow_dir = "~/opt/tensorflow-1.4.1" def main(): global tensorflow_dir description = 'This script is for testing posenet' parser = argparse.ArgumentParser(description=description) parser.add_argument('input_graph_file', action='store', nargs=None, const=None, \ default=None, type=str, choices=None, metavar=None, \ help='File path where exported graph def protobuf (.pb) file will be saved.') parser.add_argument('checkpoint_dir', action='store', nargs=None, const=None, \ default=None, type=str, choices=None, metavar=None, \ help='Directory path where trained model files are be saved.') parser.add_argument('output_graph_dir', action='store', nargs=None, const=None, \ default=None, type=str, choices=None, metavar=None, \ help='Directory path where freezed, optimized, quantized files will be saved.') parser.add_argument('-m', '--base_model', action='store', type=str, default=posenet_config.base_model, \ help='Base model : inception-v1/inception-v3/mobilenet-v1 (Default : ' + str(posenet_config.base_model)) args = parser.parse_args() input_graph_file = args.input_graph_file checkpoint_dir = args.checkpoint_dir output_graph_dir = args.output_graph_dir posenet_config.base_model = args.base_model print "base model : " + str(posenet_config.base_model) #Save frozon graph, optimized graph, and quantized graph from graph definition and checkpoint latest_checkpoint_filepath = tf.train.latest_checkpoint(checkpoint_dir) # you can check output node name by tensorflow/tools/graph_transforms::summarize_graph # https://github.com/tensorflow/models/tree/master/research/slim#Export if posenet_config.base_model=="inception-v1": output_node_names = "cls3_fc_pose_xyz/BiasAdd,cls3_fc_pose_wpqr/BiasAdd" elif posenet_config.base_model=="inception-v3" or posenet_config.base_model=="mobilenet-v1": output_node_names = "cls_fc_pose_xyz/BiasAdd,cls_fc_pose_wpqr/BiasAdd" else: print "invalid base model : " + posenet_config.base_model sys.exit() output_frozen_graph_filepath = os.path.join(output_graph_dir, 'frozen_graph.pb') freeze_graph_command_exec = os.path.join(tensorflow_dir, "bazel-bin/tensorflow/python/tools/freeze_graph") if not os.path.exists(freeze_graph_command_exec): print("fatal error, cannot find command : " + freeze_graph_command_exec) sys.exit() freeze_graph_command_env = os.environ.copy() freeze_graph_command_env["CUDA_VISIBLE_DEVICES"] = '' freeze_graph_command = [] freeze_graph_command.append(freeze_graph_command_exec) freeze_graph_command.append("--input_graph=" + input_graph_file) freeze_graph_command.append("--input_checkpoint=" + latest_checkpoint_filepath) freeze_graph_command.append("--input_binary=true") freeze_graph_command.append("--output_graph=" + output_frozen_graph_filepath) freeze_graph_command.append("--output_node_names=" + output_node_names) print("start exec:" + " ".join(freeze_graph_command)) proc = subprocess.Popen(freeze_graph_command, env=freeze_graph_command_env) print("freeze graph process ID=" + str(proc.pid)) proc.communicate() print("finish exec:" + " ".join(freeze_graph_command)) output_optimized_graph_filepath = os.path.join(output_graph_dir, 'optimized_graph.pb') optimize_graph_command_exec = os.path.join(tensorflow_dir, "bazel-bin/tensorflow/python/tools/optimize_for_inference") if not os.path.exists(optimize_graph_command_exec): print("fatal error, cannot find command : " + optimize_graph_command_exec) sys.exit() optimize_graph_command_env = os.environ.copy() optimize_graph_command_env["CUDA_VISIBLE_DEVICES"] = '' optimize_graph_command = [] optimize_graph_command.append(optimize_graph_command_exec) optimize_graph_command.append("--input=" + output_frozen_graph_filepath) optimize_graph_command.append("--output=" + output_optimized_graph_filepath) optimize_graph_command.append("--input_names=input_1") optimize_graph_command.append("--output_names=" + output_node_names) optimize_graph_command.append("--frozen_graph=true") print("start exec:" + " ".join(optimize_graph_command)) proc = subprocess.Popen(optimize_graph_command, env=optimize_graph_command_env) print("optimize graph process ID=" + str(proc.pid)) proc.communicate() print("finish exec:" + " ".join(optimize_graph_command)) output_quantized_graph_filepath = os.path.join(output_graph_dir, 'quantized_graph.pb') quantize_graph_command_exec = os.path.join(tensorflow_dir, "bazel-bin/tensorflow/tools/quantization/quantize_graph") if not os.path.exists(quantize_graph_command_exec): print("fatal error, cannot find command : " + quantize_graph_command_exec) sys.exit() quantize_graph_command_env = os.environ.copy() quantize_graph_command_env["CUDA_VISIBLE_DEVICES"] = '' quantize_graph_command = [] quantize_graph_command.append(quantize_graph_command_exec) quantize_graph_command.append("--input=" + output_optimized_graph_filepath) quantize_graph_command.append("--output=" + output_quantized_graph_filepath) quantize_graph_command.append("--input_node_names=input_1") quantize_graph_command.append("--output_node_names=" + output_node_names) quantize_graph_command.append("--mode=eightbit") print("start exec:" + " ".join(quantize_graph_command)) proc = subprocess.Popen(quantize_graph_command, env=quantize_graph_command_env) print("quantize graph process ID=" + str(proc.pid)) proc.communicate() print("finish exec:" + " ".join(quantize_graph_command)) if __name__ == '__main__': main()
58.628788
132
0.689495
e59327dd1ec2e1a01859200b9392d06f686c7415
1,032
py
Python
src/hand.py
davidjayfrancis/blackjack-in-python
342bf2752fa6cd0af6777d5a702ad1eefc325387
[ "MIT" ]
null
null
null
src/hand.py
davidjayfrancis/blackjack-in-python
342bf2752fa6cd0af6777d5a702ad1eefc325387
[ "MIT" ]
null
null
null
src/hand.py
davidjayfrancis/blackjack-in-python
342bf2752fa6cd0af6777d5a702ad1eefc325387
[ "MIT" ]
null
null
null
class Hand: def __init__(self, stay=False): self.stay = stay self.cards = [] def drawCard(self, deck): self.cards.append(deck.dealCard()) def displayHand(self): return f"{[f'{card.num}{card.face},' for card in self.cards]}" # Corner case to be resolved: # --> Ace Ace Jack will fail (e.g. 11 + 1 + 10 = 22) def calculateScore(self): values = { 'Ace': 1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:10, 'Jack': 10, 'Queen': 10, 'King': 10 } aces = [] total = 0 for card in self.cards: if card.num == 'Ace': aces.append(card) else: total += values[card.num] for ace in aces: if total <= 10: total += 11 else: total += 1 return total
24.571429
70
0.390504
40fedb9e9ef950cc83e2be88afdfa044f5068cef
1,051
py
Python
plugins/Vibe/__init__.py
koalasthegreat/Automata
c2dd271c9e8028759ba7f4fe94ab9c4be340dd25
[ "MIT" ]
null
null
null
plugins/Vibe/__init__.py
koalasthegreat/Automata
c2dd271c9e8028759ba7f4fe94ab9c4be340dd25
[ "MIT" ]
null
null
null
plugins/Vibe/__init__.py
koalasthegreat/Automata
c2dd271c9e8028759ba7f4fe94ab9c4be340dd25
[ "MIT" ]
null
null
null
import nextcord from nextcord.ext import commands from Plugin import AutomataPlugin VIBE_IMAGE = "https://s3.gifyu.com/images/catvibe.gif" VIBIER_IMAGE = "https://s3.gifyu.com/images/ezgif.com-gif-maker-174e18faa852a3028.gif" VIBIEST_IMAGE = "https://s3.gifyu.com/images/ezgif.com-gif-maker-2664260aedaea9638.gif" VIBE_CAR = "https://s9.gifyu.com/images/ezgif.com-gif-maker-28d39714362a6d155.gif" NO_VIBE = "https://s6.gifyu.com/images/ezgif.com-gif-maker682fded14a604d26.gif" class Vibe(AutomataPlugin): """Cat Bop""" @commands.command() async def vibe(self, ctx: commands.Context, vibelevel: int = 1): """Replies with a Cat Bop Gif! Vibe levels from 1-3 can also be specified.""" if vibelevel <= 0: await ctx.send(NO_VIBE) elif vibelevel == 1: await ctx.send(VIBE_IMAGE) elif vibelevel == 2: await ctx.send(VIBIER_IMAGE) elif vibelevel == 69 or vibelevel == 420: await ctx.send(VIBE_CAR) else: await ctx.send(VIBIEST_IMAGE)
36.241379
87
0.675547
9897370ae60d27a240085479a81ddd4b3b7a3fb3
750
py
Python
socketclusterclient/Emitter.py
sacOO7/socketcluster-client-python
aac7f395847f32c031a94815526167d337c54ce7
[ "MIT" ]
51
2016-12-09T14:35:16.000Z
2021-09-24T21:39:43.000Z
socketclusterclient/Emitter.py
sacOO7/socketcluster-client-python
aac7f395847f32c031a94815526167d337c54ce7
[ "MIT" ]
19
2017-01-03T10:41:42.000Z
2021-04-29T06:33:57.000Z
socketclusterclient/Emitter.py
sacOO7/socketcluster-client-python
aac7f395847f32c031a94815526167d337c54ce7
[ "MIT" ]
19
2017-02-06T18:43:29.000Z
2021-09-26T02:15:17.000Z
class emitter(object): def on(self, key, function): self.map[key] = function def onchannel(self, key, function): self.map[key] = function def onack(self, key, function): self.mapack[key] = function def execute(self, key, object): if key in self.map: function = self.map[key] if function is not None: function(key, object) def haseventack(self, key): return key in self.mapack def executeack(self, key, object, ack): if key in self.mapack: function = self.mapack[key] if function is not None: function(key, object, ack) def __init__(self): self.map = {} self.mapack = {}
24.193548
43
0.554667
c51b66d2122bf3db9393237448d93e706be36e10
7,898
py
Python
bin/parse_cutadapt.py
mr-c/eclip
833a389b773e12492d316e61db802dd353404f4f
[ "BSD-3-Clause" ]
null
null
null
bin/parse_cutadapt.py
mr-c/eclip
833a389b773e12492d316e61db802dd353404f4f
[ "BSD-3-Clause" ]
null
null
null
bin/parse_cutadapt.py
mr-c/eclip
833a389b773e12492d316e61db802dd353404f4f
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # transitionning to python2/python3 support # uncomment from this compatibility import list, as py3/py2 support progresses from __future__ import print_function from __future__ import division # from __future__ import absolute_import # from __future__ import unicode_literals # from future import standard_library # from future.builtins import builtins # from future.builtins import utils # from future.utils import raise_with_traceback # from future.utils import iteritems import os import argparse ############################################################################### def parse_cutadapt_file(report): ############################# #print("parse_cutadapt_file report:", report) if os.path.getsize(report) == 0: return old_cutadapt = get_cutadapt_version(report) <= 8 if old_cutadapt: return parse_old_cutadapt_file(report) else: return parse_new_cutadapt_file(report) ############################################################################### def get_cutadapt_version(report): ############################## with open(report) as file_handle: version = file_handle.next() try: version = version.split()[-4] except: 1 return int(version.split(".")[1]) ############################################################################### def parse_old_cutadapt_file(report): ################################ report_dir = {} try: with open(report) as report: report.next() #header report.next() #paramaters report.next() #max error rate report.next() #adapters (known already) processed_reads = [x.strip() for x in report.next().strip().split(":")] processed_bases = [x.strip() for x in report.next().strip().split(":")] trimmed_reads = [x.strip() for x in report.next().strip().split(":")] quality_trimmed = [x.strip() for x in report.next().strip().split(":")] trimmed_bases = [x.strip() for x in report.next().strip().split(":")] too_short_reads = [x.strip() for x in report.next().strip().split(":")] too_long_reads = [x.strip() for x in report.next().strip().split(":")] total_time = [x.strip() for x in report.next().strip().split(":")] time_pre_read = [x.strip() for x in report.next().strip().split(":")] report_dir[processed_reads[0]] = int(processed_reads[1]) report_dir[processed_bases[0]] = int(processed_bases[1].split()[0]) report_dir[trimmed_reads[0]] = int(trimmed_reads[1].split()[0]) report_dir[quality_trimmed[0]] = int(quality_trimmed[1].split()[0]) report_dir[trimmed_bases[0]] = int(trimmed_bases[1].split()[0]) report_dir[too_short_reads[0]] = int(too_short_reads[1].split()[0]) report_dir[too_long_reads[0]] = int(too_long_reads[1].split()[0]) report_dir[trimmed_bases[0]] = int(trimmed_bases[1].split()[0]) except: print(report) return report_dir ############################################################################### def parse_new_cutadapt_file(report): ################################ report_dict = {} try: with open(report) as file_handle: remove_header(file_handle) processed_reads = get_number(file_handle.next()) paired_file = processed_reads[0] == 'Total read pairs processed' if paired_file: r1_adapter = get_number_and_percent(file_handle.next()) r2_adapter = get_number_and_percent(file_handle.next()) else: adapter = get_number_and_percent(file_handle.next()) too_short = get_number_and_percent(file_handle.next()) written = get_number_and_percent(file_handle.next()) file_handle.next() bp_processed = get_number(strip_bp(file_handle.next())) if paired_file: r1_bp_processed = get_number(strip_bp(file_handle.next())) r2_bp_processed = get_number(strip_bp(file_handle.next())) bp_quality_trimmed = get_number_and_percent(strip_bp(file_handle.next())) if paired_file: r1_bp_trimmed = get_number(strip_bp(file_handle.next())) r2_bp_trimmed = get_number(strip_bp(file_handle.next())) bp_written = get_number_and_percent(strip_bp(file_handle.next())) if paired_file: r1_bp_written = get_number(strip_bp(file_handle.next())) r2_bp_written = get_number(strip_bp(file_handle.next())) except Exception as e: print(e) print(report) return report_dict report_dict['Processed reads'] = processed_reads[1] if paired_file: report_dict["Read 1 with adapter"] = r1_adapter[1] report_dict["Read 1 with adapter percent"] = r1_adapter[2] report_dict["Read 2 with adapter"] = r2_adapter[1] report_dict["Read 2 with adapter percent"] = r2_adapter[2] report_dict['Read 1 basepairs processed'] = r1_bp_processed[1] report_dict['Read 2 basepairs processed'] = r2_bp_processed[1] report_dict['Read 1 Trimmed bases'] = r1_bp_trimmed[1] report_dict['Read 2 Trimmed bases'] = r2_bp_trimmed[1] report_dict['Read 1 {}'.format(bp_written[0])] = r1_bp_written[1] report_dict['Read 2 {}'.format(bp_written[0])] = r2_bp_written[1] else: report_dict['Reads with adapter'] = adapter[1] report_dict['Reads with adapter percent'] = adapter[2] report_dict['Too short reads'] = too_short[1] report_dict['Reads that were too short percent'] = too_short[2] report_dict['Reads Written'] = written[1] report_dict['Reads Written percent'] = written[2] report_dict['Processed bases'] = bp_processed[1] report_dict['Trimmed bases'] = bp_quality_trimmed[1] report_dict['Trimmed bases percent'] = bp_quality_trimmed[2] report_dict[bp_written[0]] = bp_written[1] report_dict["{} percent".format(bp_written[0])] = bp_written[2] return report_dict ############################################################################### ## parse_new_cutadapt_file utilities ###################################### def get_number_and_percent(line): """ Parses cutadapt line containing a number (string) and returns number typecasted to int, as well as a percentage (float), as a list. :param line: basestring :return line: list """ line = [x.strip() for x in line.strip().split(":")] line = [line[0]] + line[1].split() line[2] = float(line[2][1:-2]) line[1] = int(line[1].replace(",", "")) return line def get_number(line): """ Parses cutadapt line containing a number (string) and returns number typecasted to int. :param line: basestring :return number: int """ line = [x.strip() for x in line.strip().split(":")] line[1] = int(line[1].replace(",", "")) return line def strip_bp(line): return line.replace("bp", "") def remove_header(file_handle): """ for both SE and PE output removes header unifromly from cutadapt metrics file""" file_handle.next() file_handle.next() file_handle.next() file_handle.next() file_handle.next() file_handle.next() file_handle.next() file_handle.next() #print foo.next() ############################################################################### if __name__ == '__main__': parser = argparse.ArgumentParser(description="prints a report_dict for a cutadapt report") parser.add_argument("--report", help="report", required=True) args = parser.parse_args() print("args:", args) report_dict = parse_cutadapt_file(args.report) print("report_dict:", report_dict)
39.09901
94
0.592808
0a852f0e9db20cc5a9de040748f68bb35742682e
5,965
py
Python
csiread/_type.py
benjaminjacobreji/csiread
58c62fc8ff818271f3c9ff84361361d83629df1a
[ "MIT" ]
null
null
null
csiread/_type.py
benjaminjacobreji/csiread
58c62fc8ff818271f3c9ff84361361d83629df1a
[ "MIT" ]
null
null
null
csiread/_type.py
benjaminjacobreji/csiread
58c62fc8ff818271f3c9ff84361361d83629df1a
[ "MIT" ]
null
null
null
import numpy as np def init_dtype_picoscenes(pl_size): dt_ieee80211_mac_frame_header_frame_control_field = np.dtype([ ('Version', np.uint8), ('Type', np.uint8), ('SubType', np.uint8), ('ToDS', np.uint8), ('FromDS', np.uint8), ('MoreFrags', np.uint8), ('Retry', np.uint8), ('PowerManagement', np.uint8), ('More', np.uint8), ('Protected', np.uint8), ('Order', np.uint8), ]) dt_ieee80211_mac_frame_header = np.dtype([ ('ControlField', dt_ieee80211_mac_frame_header_frame_control_field), ('Addr1', np.uint8, (6, )), ('Addr2', np.uint8, (6, )), ('Addr3', np.uint8, (6, )), ('Fragment', np.uint16), ('Sequence', np.uint16), ]) dt_RxSBasic = np.dtype([ ('DeviceType', np.uint16), ('Timestamp', np.uint64), ('CenterFreq', np.int16), ('ControlFreq', np.int16), ('CBW', np.uint16), ('PacketFormat', np.uint8), ('PacketCBW', np.uint16), ('GI', np.uint16), ('MCS', np.uint8), ('NumSTS', np.uint8), ('NumESS', np.uint8), ('NumRx', np.uint8), ('NoiseFloor', np.int8), ('RSSI', np.int8), ('RSSI1', np.int8), ('RSSI2', np.int8), ('RSSI3', np.int8), ]) dt_ExtraInfo = np.dtype([ ('HasLength', bool), ('HasVersion', bool), ('HasMacAddr_cur', bool), ('HasMacAddr_rom', bool), ('HasChansel', bool), ('HasBMode', bool), ('HasEVM', bool), ('HasTxChainMask', bool), ('HasRxChainMask', bool), ('HasTxpower', bool), ('HasCF', bool), ('HasTxTSF', bool), ('HasLastHwTxTSF', bool), ('HasChannelFlags', bool), ('HasTxNess', bool), ('HasTuningPolicy', bool), ('HasPLLRate', bool), ('HasPLLClkSel', bool), ('HasPLLRefDiv', bool), ('HasAGC', bool), ('HasAntennaSelection', bool), ('HasSamplingRate', bool), ('HasCFO', bool), ('HasSFO', bool), ('HasTemperature', bool), ('Length', np.uint16), ('Version', np.uint64), ('MACAddressCurrent', np.uint8, (6, )), ('MACAddressROM', np.uint8, (6, )), ('CHANSEL', np.uint32), ('BMode', np.uint8), ('EVM', np.int8, (20, )), ('TxChainMask', np.uint8), ('RxChainMask', np.uint8), ('TxPower', np.uint8), ('CF', np.uint64), ('TxTSF', np.uint32), ('LastTXTSF', np.uint32), ('ChannelFlags', np.uint16), ('TXNESS', np.uint8), ('TuningPolicy', np.uint8), ('PLLRate', np.uint16), ('PLLClockSelect', np.uint8), ('PLLRefDiv', np.uint8), ('AGC', np.uint8), ('ANTSEL', np.uint8, (3, )), ('SF', np.uint64), ('CFO', np.int32), ('SFO', np.int32), ('Temperature', np.int8), ]) dt_CSI_info = np.dtype([ ('DeviceType', np.uint16), ('FirmwareVersion', np.uint8), ('PacketFormat', np.int8), ('CBW', np.uint16), ('CarrierFreq', np.uint64), ('SamplingRate', np.uint64), ('SubcarrierBandwidth', np.uint32), ('NumTones', np.uint16), ('NumTx', np.uint8), ('NumRx', np.uint8), ('NumESS', np.uint8), ('NumCSI', np.uint16), ('ANTSEL', np.uint8) ]) dt_CSI = np.dtype([ ('Info', dt_CSI_info), ('CSI', complex, pl_size['CSI']), ('SubcarrierIndex', np.int32, (pl_size['CSI'][0], )), ]) dt_PilotCSI = np.dtype([ ('Info', dt_CSI_info), ('CSI', complex, pl_size['PilotCSI']), ('SubcarrierIndex', np.int32, (pl_size['PilotCSI'][0], )), ]) dt_LegacyCSI = np.dtype([ ('Info', dt_CSI_info), ('CSI', complex, pl_size['LegacyCSI']), ('SubcarrierIndex', np.int32, (pl_size['LegacyCSI'][0], )), ]) dt_IntelMVMExtrta = np.dtype([ ('FTMClock', np.uint32), ('MuClock', np.uint32), ('RateNFlags', np.uint32), ]) dt_DPASRequest = np.dtype([ ('RequestMode', np.uint8), ('BatchId', np.uint16), ('BatchLength', np.uint16), ('Sequence', np.uint16), ('Interval', np.uint16), ('Step', np.uint16), ('DeviceType', np.uint16), ('DeviceSubtype', np.uint16), ('CarrierFrequency', np.uint64), ('SamplingRate', np.uint32), ]) dt_PicoScenesFrameHeader = np.dtype([ ('MagicValue', np.uint32), ('Version', np.uint32), ('DeviceType', np.uint16), ('FrameType', np.uint8), ('TaskId', np.uint16), ('TxId', np.uint16), ]) dt_SignalMatrix_info = np.dtype([ ('Ndim', np.uint8), ('Shape', np.uint16, (3, )), ('Itemsize', np.uint8), ('Majority', np.byte), ]) dt_BasebandSignals = np.dtype([ ('Info', dt_SignalMatrix_info), ('Data', np.complex128, pl_size['BasebandSignals']) ]) dt_PreEQSymbols = np.dtype([ ('Info', dt_SignalMatrix_info), ('Data', np.complex128, pl_size['PreEQSymbols']) ]) dt_MPDU_info = np.dtype([ ('Length', np.uint32) ]) dt_MPDU = np.dtype([ ('Info', dt_MPDU_info), ('Data', np.uint8, (pl_size['MPDU'], )) ]) dt = np.dtype([ ('StandardHeader', dt_ieee80211_mac_frame_header), ('RxSBasic', dt_RxSBasic), ('RxExtraInfo', dt_ExtraInfo), ('CSI', dt_CSI), ('MVMExtra', dt_IntelMVMExtrta), ('DPASRequest', dt_DPASRequest), ('PicoScenesHeader', dt_PicoScenesFrameHeader), ('TxExtraInfo', dt_ExtraInfo), ('PilotCSI', dt_PilotCSI), ('LegacyCSI', dt_LegacyCSI), ('BasebandSignals', dt_BasebandSignals), ('PreEQSymbols', dt_PreEQSymbols), ('MPDU', dt_MPDU), ]) return dt
28.956311
76
0.506454
6e9f65f31ea2eef47b74cfb10c4226cdd45b05c1
51,872
py
Python
NodeGraphQt/base/graph.py
githeshuai/NodeGraphQt
1291f72804fd2fe4f20aae446c483b8412a88dc5
[ "MIT" ]
null
null
null
NodeGraphQt/base/graph.py
githeshuai/NodeGraphQt
1291f72804fd2fe4f20aae446c483b8412a88dc5
[ "MIT" ]
null
null
null
NodeGraphQt/base/graph.py
githeshuai/NodeGraphQt
1291f72804fd2fe4f20aae446c483b8412a88dc5
[ "MIT" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- import json import os import re import copy import gc from .. import QtCore, QtWidgets, QtGui from .commands import (NodeAddedCmd, NodeRemovedCmd, NodeMovedCmd, PortConnectedCmd) from .factory import NodeFactory from .menu import NodeGraphMenu, NodesMenu from .model import NodeGraphModel from .node import NodeObject, BaseNode from .port import Port from ..constants import (DRAG_DROP_ID, PIPE_LAYOUT_CURVED, PIPE_LAYOUT_STRAIGHT, PIPE_LAYOUT_ANGLE, IN_PORT, OUT_PORT, VIEWER_GRID_LINES) from ..widgets.viewer import NodeViewer from ..widgets.node_space_bar import node_space_bar class QWidgetDrops(QtWidgets.QWidget): def __init__(self): super(QWidgetDrops, self).__init__() self.setAcceptDrops(True) self.setWindowTitle("NodeGraphQt") self.setStyleSheet(''' QWidget { background-color: rgb(55,55,55); color: rgb(200,200,200); border-width: 0px; }''') def dragEnterEvent(self, event): if event.mimeData().hasUrls: event.accept() else: event.ignore() def dragMoveEvent(self, event): if event.mimeData().hasUrls: event.accept() else: event.ignore() def dropEvent(self, event): if event.mimeData().hasUrls: event.setDropAction(QtCore.Qt.CopyAction) event.accept() for url in event.mimeData().urls(): self.import_session(url.toLocalFile()) else: event.ignore() class NodeGraph(QtCore.QObject): """ The ``NodeGraph`` class is the main controller for managing all nodes. Inherited from: :class:`PySide2.QtCore.QObject` .. image:: _images/graph.png :width: 60% """ node_created = QtCore.Signal(NodeObject) """ Signal triggered when a node is created in the node graph. :parameters: :class:`NodeGraphQt.NodeObject` :emits: created node """ nodes_deleted = QtCore.Signal(list) """ Signal triggered when nodes have been deleted from the node graph. :parameters: list[str] :emits: list of deleted node ids. """ node_selected = QtCore.Signal(NodeObject) """ Signal triggered when a node is clicked with the LMB. :parameters: :class:`NodeGraphQt.NodeObject` :emits: selected node """ node_selection_changed = QtCore.Signal(list, list) """ Signal triggered when the node selection has changed. :parameters: list[:class:`NodeGraphQt.NodeObject`], list[:class:`NodeGraphQt.NodeObject`] :emits: selected node, deselected nodes. """ node_double_clicked = QtCore.Signal(NodeObject) """ Signal triggered when a node is double clicked and emits the node. :parameters: :class:`NodeGraphQt.NodeObject` :emits: selected node """ port_connected = QtCore.Signal(Port, Port) """ Signal triggered when a node port has been connected. :parameters: :class:`NodeGraphQt.Port`, :class:`NodeGraphQt.Port` :emits: input port, output port """ port_disconnected = QtCore.Signal(Port, Port) """ Signal triggered when a node port has been disconnected. :parameters: :class:`NodeGraphQt.Port`, :class:`NodeGraphQt.Port` :emits: input port, output port """ property_changed = QtCore.Signal(NodeObject, str, object) """ Signal is triggered when a property has changed on a node. :parameters: :class:`NodeGraphQt.BaseNode`, str, object :emits: triggered node, property name, property value """ data_dropped = QtCore.Signal(QtCore.QMimeData, QtCore.QPoint) """ Signal is triggered when data has been dropped to the graph. :parameters: :class:`PySide2.QtCore.QMimeData`, :class:`PySide2.QtCore.QPoint` :emits: mime data, node graph position """ session_changed = QtCore.Signal(str) """ Signal is triggered when session has been changed. :parameters: :str :emits: new session path """ def __init__(self, parent=None): super(NodeGraph, self).__init__(parent) self.setObjectName('NodeGraphQt') self._widget = None self._undo_view = None self._model = NodeGraphModel() self._viewer = NodeViewer() self._node_factory = NodeFactory() self._undo_stack = QtWidgets.QUndoStack(self) self._current_node_space = None self._editable = True tab = QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Tab), self._viewer) tab.activated.connect(self._toggle_tab_search) self._viewer.need_show_tab_search.connect(self._toggle_tab_search) self._wire_signals() self._node_space_bar = node_space_bar(self) self._auto_update = True def __repr__(self): return '<{} object at {}>'.format(self.__class__.__name__, hex(id(self))) def _wire_signals(self): # internal signals. self._viewer.search_triggered.connect(self._on_search_triggered) self._viewer.connection_sliced.connect(self._on_connection_sliced) self._viewer.connection_changed.connect(self._on_connection_changed) self._viewer.moved_nodes.connect(self._on_nodes_moved) self._viewer.node_double_clicked.connect(self._on_node_double_clicked) self._viewer.insert_node.connect(self._insert_node) # pass through signals. self._viewer.node_selected.connect(self._on_node_selected) self._viewer.node_selection_changed.connect( self._on_node_selection_changed) self._viewer.data_dropped.connect(self._on_node_data_dropped) def _insert_node(self, pipe, node_id, prev_node_pos): """ Slot function triggered when a selected node has collided with a pipe. Args: pipe (Pipe): collided pipe item. node_id (str): selected node id to insert. prev_node_pos (dict): previous node position. {NodeItem: [prev_x, prev_y]} """ if not self._editable: return node = self.get_node_by_id(node_id) # exclude the BackdropNode if not isinstance(node, BaseNode): return disconnected = [(pipe.input_port, pipe.output_port)] connected = [] if node.input_ports(): connected.append( (pipe.output_port, node.input_ports()[0].view) ) if node.output_ports(): connected.append( (node.output_ports()[0].view, pipe.input_port) ) self._undo_stack.beginMacro('inserted node') self._on_connection_changed(disconnected, connected) self._on_nodes_moved(prev_node_pos) self._undo_stack.endMacro() def _toggle_tab_search(self): """ toggle the tab search widget. """ if not self._editable: return if self._viewer.underMouse(): self._viewer.tab_search_set_nodes(self._node_factory.names) self._viewer.tab_search_toggle() def _on_property_bin_changed(self, node_id, prop_name, prop_value): """ called when a property widget has changed in a properties bin. (emits the node object, property name, property value) Args: node_id (str): node id. prop_name (str): node property name. prop_value (object): python object. """ if not self._editable: return node = self.get_node_by_id(node_id) # prevent signals from causing a infinite loop. _exc = [float, int, str, bool, None] if node.get_property(prop_name) != prop_value: if type(node.get_property(prop_name)) in _exc: value = prop_value else: value = copy.deepcopy(prop_value) node.set_property(prop_name, value) def _on_node_double_clicked(self, node_id): """ called when a node in the viewer is double click. (emits the node object when the node is clicked) Args: node_id (str): node id emitted by the viewer. """ node = self.get_node_by_id(node_id) self.node_double_clicked.emit(node) if isinstance(node, SubGraph): self.set_node_space(node) def _on_node_selected(self, node_id): """ called when a node in the viewer is selected on left click. (emits the node object when the node is clicked) Args: node_id (str): node id emitted by the viewer. """ node = self.get_node_by_id(node_id) self.node_selected.emit(node) def _on_node_selection_changed(self, sel_ids, desel_ids): """ called when the node selection changes in the viewer. (emits node objects <selected nodes>, <deselected nodes>) Args: sel_ids (list[str]): new selected node ids. desel_ids (list[str]): deselected node ids. """ sel_nodes = [self.get_node_by_id(nid) for nid in sel_ids] unsel_nodes = [self.get_node_by_id(nid) for nid in desel_ids] self.node_selection_changed.emit(sel_nodes, unsel_nodes) def _on_node_data_dropped(self, data, pos): """ called when data has been dropped on the viewer. Args: data (QtCore.QMimeData): mime data. pos (QtCore.QPoint): scene position relative to the drop. """ # don't emit signal for internal widget drops. if data.hasFormat('text/plain'): if data.text().startswith('<${}>:'.format(DRAG_DROP_ID)): node_ids = data.text()[len('<${}>:'.format(DRAG_DROP_ID)):] x, y = pos.x(), pos.y() for node_id in node_ids.split(','): self.create_node(node_id, pos=[x, y]) x += 20 y += 20 return self.data_dropped.emit(data, pos) def _on_nodes_moved(self, node_data): """ called when selected nodes in the viewer has changed position. Args: node_data (dict): {<node_view>: <previous_pos>} """ self._undo_stack.beginMacro('move nodes') for node_view, prev_pos in node_data.items(): node = self._model.nodes[node_view.id] self._undo_stack.push(NodeMovedCmd(node, node.pos(), prev_pos)) self._undo_stack.endMacro() def _on_search_triggered(self, node_type, pos): """ called when the tab search widget is triggered in the viewer. Args: node_type (str): node identifier. pos (tuple): x,y position for the node. """ self.create_node(node_type, pos=pos) def _on_connection_changed(self, disconnected, connected): """ called when a pipe connection has been changed in the viewer. Args: disconnected (list[list[widgets.port.PortItem]): pair list of port view items. connected (list[list[widgets.port.PortItem]]): pair list of port view items. """ if not self._editable: return if not (disconnected or connected): return label = 'connect node(s)' if connected else 'disconnect node(s)' ptypes = {IN_PORT: 'inputs', OUT_PORT: 'outputs'} self._undo_stack.beginMacro(label) for p1_view, p2_view in disconnected: node1 = self._model.nodes[p1_view.node.id] node2 = self._model.nodes[p2_view.node.id] port1 = getattr(node1, ptypes[p1_view.port_type])()[p1_view.name] port2 = getattr(node2, ptypes[p2_view.port_type])()[p2_view.name] port1.disconnect_from(port2) for p1_view, p2_view in connected: node1 = self._model.nodes[p1_view.node.id] node2 = self._model.nodes[p2_view.node.id] port1 = getattr(node1, ptypes[p1_view.port_type])()[p1_view.name] port2 = getattr(node2, ptypes[p2_view.port_type])()[p2_view.name] port1.connect_to(port2) self._undo_stack.endMacro() def _on_connection_sliced(self, ports): """ slot when connection pipes have been sliced. Args: ports (list[list[widgets.port.PortItem]]): pair list of port connections (in port, out port) """ if not ports or not self._editable: return ptypes = {IN_PORT: 'inputs', OUT_PORT: 'outputs'} self._undo_stack.beginMacro('slice connections') for p1_view, p2_view in ports: node1 = self._model.nodes[p1_view.node.id] node2 = self._model.nodes[p2_view.node.id] port1 = getattr(node1, ptypes[p1_view.port_type])()[p1_view.name] port2 = getattr(node2, ptypes[p2_view.port_type])()[p2_view.name] port1.disconnect_from(port2) self._undo_stack.endMacro() @property def model(self): """ The model used for storing the node graph data. Returns: NodeGraphQt.base.model.NodeGraphModel: node graph model. """ return self._model @property def widget(self): """ The node graph widget for adding into a layout. Returns: PySide2.QtWidgets.QWidget: node graph widget. """ if self._widget is None: self._widget = QWidgetDrops() self._widget.import_session = self.import_session layout = QtWidgets.QVBoxLayout(self._widget) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) if self.root_node() is not None: layout.addWidget(self._node_space_bar) layout.addWidget(self._viewer) return self._widget @property def undo_view(self): """ Returns node graph undo view. Returns: PySide2.QtWidgets.QUndoView: node graph undo view. """ if self._undo_view is None: self._undo_view = QtWidgets.QUndoView(self._undo_stack) self._undo_view.setWindowTitle("Undo View") return self._undo_view @property def auto_update(self): """ Returns whether the graph can run node automatically. """ return self._auto_update @property def editable(self): """ Returns whether the graph is editable. """ return self._editable @editable.setter def editable(self, state): """ Set whether the graph is editable. Args: state(bool). """ self._editable = state self._viewer.editable = state self._viewer.scene().editable = state def show(self): """ Show node graph widget this is just a convenience function to :meth:`NodeGraph.widget.show()`. """ self.widget.show() def close(self): """ Close node graph NodeViewer widget this is just a convenience function to :meth:`NodeGraph.widget.close()`. """ self.widget.close() def viewer(self): """ Returns the view interface used by the node graph. Warnings: Methods in the ``NodeViewer`` are used internally by ``NodeGraphQt`` components. See Also: :attr:`NodeGraph.widget` for adding the node graph into a :class:`PySide2.QtWidgets.QLayout`. Returns: NodeGraphQt.widgets.viewer.NodeViewer: viewer interface. """ return self._viewer def scene(self): """ Returns the ``QGraphicsScene`` object used in the node graph. Returns: NodeGraphQt.widgets.scene.NodeScene: node scene. """ return self._viewer.scene() def background_color(self): """ Return the node graph background color. Returns: tuple: r, g ,b """ return self.scene().background_color def set_background_color(self, r, g, b): """ Set node graph background color. Args: r (int): red value. g (int): green value. b (int): blue value. """ self.scene().background_color = (r, g, b) self._viewer.force_update() def grid_color(self): """ Return the node graph grid color. Returns: tuple: r, g ,b """ return self.scene().grid_color def set_grid_color(self, r, g, b): """ Set node graph grid color. Args: r (int): red value. g (int): green value. b (int): blue value. """ self.scene().grid_color = (r, g, b) self._viewer.force_update() def set_grid_mode(self, mode=VIEWER_GRID_LINES): """ Set node graph grid mode. Args: mode: VIEWER_GRID_LINES/VIEWER_GRID_DOTS/VIEWER_GRID_NONE. """ self.scene().grid_mode = mode self._viewer.force_update() def add_properties_bin(self, prop_bin): """ Wire up a properties bin widget to the node graph. Args: prop_bin (NodeGraphQt.PropertiesBinWidget): properties widget. """ prop_bin.property_changed.connect(self._on_property_bin_changed) def undo_stack(self): """ Returns the undo stack used in the node graph. See Also: :meth:`NodeGraph.begin_undo()`, :meth:`NodeGraph.end_undo()` Returns: QtWidgets.QUndoStack: undo stack. """ return self._undo_stack def clear_undo_stack(self): """ Clears the undo stack. Note: Convenience function to :meth:`NodeGraph.undo_stack().clear()` See Also: :meth:`NodeGraph.begin_undo()`, :meth:`NodeGraph.end_undo()`, :meth:`NodeGraph.undo_stack()` """ self._undo_stack.clear() gc.collect() def begin_undo(self, name): """ Start of an undo block followed by a :meth:`NodeGraph.end_undo()`. Args: name (str): name for the undo block. """ self._undo_stack.beginMacro(name) def end_undo(self): """ End of an undo block started by :meth:`NodeGraph.begin_undo()`. """ self._undo_stack.endMacro() def context_menu(self): """ Returns the main context menu from the node graph. Note: This is a convenience function to :meth:`NodeGraphQt.NodeGraph.get_context_menu` with the arg ``menu="graph"`` Returns: NodeGraphQt.NodeGraphMenu: context menu object. """ return self.get_context_menu('graph') def context_nodes_menu(self): """ Returns the main context menu for the nodes. Note: This is a convenience function to :meth:`NodeGraphQt.NodeGraph.get_context_menu` with the arg ``menu="nodes"`` Returns: NodeGraphQt.NodesMenu: context menu object. """ return self.get_context_menu('nodes') def get_context_menu(self, menu): """ Returns the context menu specified by the name. Menu Types: - ``"graph"`` context menu from the node graph. - ``"nodes"`` context menu for the nodes. Args: menu (str): menu name. Returns: NodeGraphQt.NodeGraphMenu or NodeGraphQt.NodesMenu: context menu object. """ menus = self._viewer.context_menus() if menus.get(menu): if menu == 'graph': return NodeGraphMenu(self, menus[menu]) elif menu == 'nodes': return NodesMenu(self, menus[menu]) def disable_context_menu(self, disabled=True, name='all'): """ Disable/Enable context menus from the node graph. Menu Types: - ``"all"`` all context menus from the node graph. - ``"graph"`` context menu from the node graph. - ``"nodes"`` context menu for the nodes. Args: disabled (bool): true to enable context menu. name (str): menu name. (default: ``"all"``) """ if name == 'all': for k, menu in self._viewer.context_menus().items(): menu.setDisabled(disabled) menu.setVisible(not disabled) return menus = self._viewer.context_menus() if menus.get(name): menus[name].setDisabled(disabled) menus[name].setVisible(not disabled) def acyclic(self): """ Returns true if the current node graph is acyclic. See Also: :meth:`NodeGraphQt.NodeGraph.set_acyclic` Returns: bool: true if acyclic (default: ``True``). """ return self._model.acyclic def set_acyclic(self, mode=False): """ Enable the node graph to be a acyclic graph. (default: ``False``) See Also: :meth:`NodeGraphQt.NodeGraph.acyclic` Args: mode (bool): true to enable acyclic. """ self._model.acyclic = mode self._viewer.acyclic = mode def set_pipe_style(self, style=PIPE_LAYOUT_CURVED): """ Set node graph pipes to be drawn as straight, curved or angled. Note: By default all pipes are set curved. Pipe Layout Styles: * :attr:`NodeGraphQt.constants.PIPE_LAYOUT_CURVED` * :attr:`NodeGraphQt.constants.PIPE_LAYOUT_STRAIGHT` * :attr:`NodeGraphQt.constants.PIPE_LAYOUT_ANGLE` Args: style (int): pipe layout style. """ pipe_max = max([PIPE_LAYOUT_CURVED, PIPE_LAYOUT_STRAIGHT, PIPE_LAYOUT_ANGLE]) style = style if 0 <= style <= pipe_max else PIPE_LAYOUT_CURVED self._viewer.set_pipe_layout(style) def fit_to_selection(self): """ Sets the zoom level to fit selected nodes. If no nodes are selected then all nodes in the graph will be framed. """ if self._current_node_space is None: all_nodes = self.all_nodes() else: all_nodes = self._current_node_space.children() nodes = self.selected_nodes() or all_nodes if not nodes: return self._viewer.zoom_to_nodes([n.view for n in nodes]) def reset_zoom(self): """ Reset the zoom level """ self._viewer.reset_zoom() def set_zoom(self, zoom=0): """ Set the zoom factor of the Node Graph the default is ``0.0`` Args: zoom (float): zoom factor (max zoom out ``-0.9`` / max zoom in ``2.0``) """ self._viewer.set_zoom(zoom) def get_zoom(self): """ Get the current zoom level of the node graph. Returns: float: the current zoom level. """ return self._viewer.get_zoom() def center_on(self, nodes=None): """ Center the node graph on the given nodes or all nodes by default. Args: nodes (list[NodeGraphQt.BaseNode]): a list of nodes. """ self._viewer.center_selection(nodes) def center_selection(self): """ Centers on the current selected nodes. """ nodes = self._viewer.selected_nodes() self._viewer.center_selection(nodes) def registered_nodes(self): """ Return a list of all node types that have been registered. See Also: To register a node :meth:`NodeGraph.register_node` Returns: list[str]: list of node type identifiers. """ return sorted(self._node_factory.nodes.keys()) def register_node(self, node, alias=None): """ Register the node to the node graph vendor. Args: node (NodeGraphQt.NodeObject): node. alias (str): custom alias name for the node type. """ self._node_factory.register_node(node, alias) self._viewer.rebuild_tab_search() def create_node(self, node_type, name=None, selected=True, color=None, text_color=None, pos=None): """ Create a new node in the node graph. See Also: To list all node types :meth:`NodeGraph.registered_nodes` Args: node_type (str): node instance type. name (str): set name of the node. selected (bool): set created node to be selected. color (tuple or str): node color ``(255, 255, 255)`` or ``"#FFFFFF"``. text_color (tuple or str): text color ``(255, 255, 255)`` or ``"#FFFFFF"``. pos (list[int, int]): initial x, y position for the node (default: ``(0, 0)``). Returns: NodeGraphQt.BaseNode: the created instance of the node. """ if not self._editable: return NodeCls = self._node_factory.create_node_instance(node_type) if NodeCls: node = NodeCls() node.model._graph_model = self.model wid_types = node.model.__dict__.pop('_TEMP_property_widget_types') prop_attrs = node.model.__dict__.pop('_TEMP_property_attrs') if self.model.get_node_common_properties(node.type_) is None: node_attrs = {node.type_: { n: {'widget_type': wt} for n, wt in wid_types.items() }} for pname, pattrs in prop_attrs.items(): node_attrs[node.type_][pname].update(pattrs) self.model.set_node_common_properties(node_attrs) node.NODE_NAME = self.get_unique_name(name or node.NODE_NAME) node.model.name = node.NODE_NAME node.model.selected = selected node.set_graph(self) def format_color(clr): if isinstance(clr, str): clr = clr.strip('#') return tuple(int(clr[i:i + 2], 16) for i in (0, 2, 4)) return clr if color: node.model.color = format_color(color) if text_color: node.model.text_color = format_color(text_color) if pos: node.model.pos = [float(pos[0]), float(pos[1])] # set node parent if not node.has_property('root'): node.set_parent(self._current_node_space) else: node.set_parent(None) node.update() undo_cmd = NodeAddedCmd(self, node, node.model.pos) undo_cmd.setText('create node: "{}"'.format(node.NODE_NAME)) if isinstance(node, SubGraph): self.begin_undo('create sub graph node') self._undo_stack.push(undo_cmd) if node.get_property('create_from_select'): node.create_from_nodes(self.selected_nodes()) self.end_undo() else: self._undo_stack.push(undo_cmd) self.node_created.emit(node) return node raise Exception('\n\n>> Cannot find node:\t"{}"\n'.format(node_type)) def add_node(self, node, pos=None, unique_name=True): """ Add a node into the node graph. Args: node (NodeGraphQt.BaseNode): node object. pos (list[float]): node x,y position. (optional) unique_name (bool): make node name unique """ if not self._editable: return assert isinstance(node, NodeObject), 'node must be a Node instance.' wid_types = node.model.__dict__.pop('_TEMP_property_widget_types') prop_attrs = node.model.__dict__.pop('_TEMP_property_attrs') if self.model.get_node_common_properties(node.type_) is None: node_attrs = {node.type_: { n: {'widget_type': wt} for n, wt in wid_types.items() }} for pname, pattrs in prop_attrs.items(): node_attrs[node.type_][pname].update(pattrs) self.model.set_node_common_properties(node_attrs) node.set_graph(self) if unique_name: node.NODE_NAME = self.get_unique_name(node.NODE_NAME) node.model._graph_model = self.model node.model.name = node.NODE_NAME node.update() self._undo_stack.push(NodeAddedCmd(self, node, pos)) def set_node_space(self, node): """ Set the node space of the node graph. Args: node (NodeGraphQt.SubGraph): node object. """ if node is self._current_node_space or not isinstance(node, SubGraph): return if self._current_node_space is not None: self._current_node_space.exit() self._current_node_space = node if node is not None: node.enter() self._node_space_bar.set_node(node) self.editable = node.is_editable() [n.set_editable(self.editable) for n in node.children() if isinstance(n, BaseNode)] else: self.editable = True def get_node_space(self): """ Get the node space of the node graph. Returns: node (NodeGraphQt.SubGraph): node object or None. """ return self._current_node_space def delete_node(self, node): """ Remove the node from the node graph. Args: node (NodeGraphQt.BaseNode): node object. """ if not self._editable: return assert isinstance(node, NodeObject), \ 'node must be a instance of a NodeObject.' if node is self.root_node(): return self.nodes_deleted.emit([node.id]) if isinstance(node, SubGraph): self._undo_stack.beginMacro('delete sub graph') self.delete_nodes(node.children()) self._undo_stack.push(NodeRemovedCmd(self, node)) self._undo_stack.endMacro() else: self._undo_stack.push(NodeRemovedCmd(self, node)) def delete_nodes(self, nodes): """ Remove a list of specified nodes from the node graph. Args: nodes (list[NodeGraphQt.BaseNode]): list of node instances. """ if not self._editable: return root_node = self.root_node() self.nodes_deleted.emit([n.id for n in nodes]) self._undo_stack.beginMacro('delete nodes') [self.delete_nodes(n.children()) for n in nodes if isinstance(n, SubGraph)] [self._undo_stack.push(NodeRemovedCmd(self, n)) for n in nodes if n is not root_node] self._undo_stack.endMacro() def delete_pipe(self, pipe): self._on_connection_changed([(pipe.input_port, pipe.output_port)], []) def delete_pipes(self, pipes): disconnected = [] for pipe in pipes: disconnected.append((pipe.input_port, pipe.output_port)) if disconnected: self._on_connection_changed(disconnected, []) def all_nodes(self): """ Return all nodes in the node graph. Returns: list[NodeGraphQt.BaseNode]: list of nodes. """ return list(self._model.nodes.values()) def selected_nodes(self): """ Return all selected nodes that are in the node graph. Returns: list[NodeGraphQt.BaseNode]: list of nodes. """ nodes = [] for item in self._viewer.selected_nodes(): node = self._model.nodes[item.id] nodes.append(node) return nodes def select_all(self): """ Select all nodes in the node graph. """ self._undo_stack.beginMacro('select all') if self._current_node_space is not None: [node.set_selected(True) for node in self._current_node_space.children()] else: [node.set_selected(True) for node in self.all_nodes()] self._undo_stack.endMacro() def clear_selection(self): """ Clears the selection in the node graph. """ self._undo_stack.beginMacro('clear selection') [node.set_selected(False) for node in self.all_nodes()] self._undo_stack.endMacro() def get_node_by_id(self, node_id=None): """ Returns the node from the node id string. Args: node_id (str): node id (:attr:`NodeObject.id`) Returns: NodeGraphQt.NodeObject: node object. """ return self._model.nodes.get(node_id, None) def get_node_by_path(self, node_path): """ Returns the node from the node path string. Args: node_path (str): node path (:attr:`NodeObject.path()`) Returns: NodeGraphQt.NodeObject: node object. """ names = [name for name in node_path.split("/") if name] names.pop(0) node = self.root_node() if node is None: return None for name in names: find = False for n in node.children(): if n.name() == name: node = n find = True continue if not find: return None return node def get_node_by_name(self, name): """ Returns node that matches the name. Args: name (str): name of the node. Returns: NodeGraphQt.NodeObject: node object. """ if self._current_node_space is not None: nodes = self._current_node_space.children() else: nodes = self.all_nodes() for node in nodes: if node.name() == name: return node return None def get_unique_name(self, name): """ Creates a unique node name to avoid having nodes with the same name. Args: name (str): node name. Returns: str: unique node name. """ name = ' '.join(name.split()) if self._current_node_space is not None: node_names = [n.name() for n in self._current_node_space.children()] else: node_names = [n.name() for n in self.all_nodes()] if name not in node_names: return name regex = re.compile('[\w ]+(?: )*(\d+)') search = regex.search(name) if not search: for x in range(1, len(node_names) + 2): new_name = '{} {}'.format(name, x) if new_name not in node_names: return new_name version = search.group(1) name = name[:len(version) * -1].strip() for x in range(1, len(node_names) + 2): new_name = '{} {}'.format(name, x) if new_name not in node_names: return new_name return name + "_" def current_session(self): """ Returns the file path to the currently loaded session. Returns: str: path to the currently loaded session """ return self._model.session def clear_session(self): """ Clears the current node graph session. """ root_node = self.root_node() for n in self.all_nodes(): if n is root_node: continue self._undo_stack.push(NodeRemovedCmd(self, n)) self.set_node_space(root_node) self.clear_undo_stack() self._model.session = None self.session_changed.emit("") def _serialize(self, nodes): """ serialize nodes to a dict. (used internally by the node graph) Args: nodes (list[NodeGraphQt.Nodes]): list of node instances. Returns: dict: serialized data. """ serial_data = {'nodes': {}, 'connections': []} nodes_data = {} root_node = self.root_node() for n in nodes: if n is root_node: continue # update the node model. n.update_model() node_dict = n.model.to_dict if isinstance(n, SubGraph): published = n.get_property('published') if not published: children = n.children() if children: node_dict[n.model.id]['sub_graph'] = self._serialize(children) nodes_data.update(node_dict) for n_id, n_data in nodes_data.items(): serial_data['nodes'][n_id] = n_data inputs = n_data.pop('inputs') if n_data.get('inputs') else {} outputs = n_data.pop('outputs') if n_data.get('outputs') else {} for pname, conn_data in inputs.items(): for conn_id, prt_names in conn_data.items(): for conn_prt in prt_names: pipe = {IN_PORT: [n_id, pname], OUT_PORT: [conn_id, conn_prt]} if pipe not in serial_data['connections']: serial_data['connections'].append(pipe) for pname, conn_data in outputs.items(): for conn_id, prt_names in conn_data.items(): for conn_prt in prt_names: pipe = {OUT_PORT: [n_id, pname], IN_PORT: [conn_id, conn_prt]} if pipe not in serial_data['connections']: serial_data['connections'].append(pipe) if not serial_data['connections']: serial_data.pop('connections') return serial_data def _deserialize(self, data, relative_pos=False, pos=None, set_parent=True): """ deserialize node data. (used internally by the node graph) Args: data (dict): node data. relative_pos (bool): position node relative to the cursor. set_parent (bool): set node parent to current node space. Returns: list[NodeGraphQt.Nodes]: list of node instances. """ if not self._editable: return _temp_auto_update = self._auto_update self._auto_update = False nodes = {} # build the nodes. for n_id, n_data in data.get('nodes', {}).items(): identifier = n_data['type_'] NodeCls = self._node_factory.create_node_instance(identifier) if NodeCls: node = NodeCls() node.NODE_NAME = n_data.get('name', node.NODE_NAME) # set properties. for prop in node.model.properties.keys(): if prop in n_data.keys(): node.model.set_property(prop, n_data[prop]) # set custom properties. for prop, val in n_data.get('custom', {}).items(): node.model.set_property(prop, val) nodes[n_id] = node if isinstance(node, SubGraph): node.create_by_deserialize = True self.add_node(node, n_data.get('pos'), unique_name=set_parent) published = n_data['custom'].get('published', False) if not published: sub_graph = n_data.get('sub_graph', None) if sub_graph: children = self._deserialize(sub_graph, relative_pos, pos, False) [child.set_parent(node) for child in children] else: self.add_node(node, n_data.get('pos'), unique_name=set_parent) if n_data.get('dynamic_port', None): node.set_ports({'input_ports': n_data['input_ports'], 'output_ports': n_data['output_ports']}) # build the connections. for connection in data.get('connections', []): nid, pname = connection.get('in', ('', '')) in_node = nodes.get(nid) if not in_node: continue in_port = in_node.inputs().get(pname) if in_node else None nid, pname = connection.get('out', ('', '')) out_node = nodes.get(nid) if not out_node: continue out_port = out_node.outputs().get(pname) if out_node else None if in_port and out_port: self._undo_stack.push(PortConnectedCmd(in_port, out_port)) node_objs = list(nodes.values()) if relative_pos: self._viewer.move_nodes([n.view for n in node_objs]) [setattr(n.model, 'pos', n.view.xy_pos) for n in node_objs] elif pos: self._viewer.move_nodes([n.view for n in node_objs], pos=pos) [setattr(n.model, 'pos', n.view.xy_pos) for n in node_objs] if set_parent: [node.set_parent(self._current_node_space) for node in node_objs] self._auto_update = _temp_auto_update return node_objs def serialize_session(self): """ Serializes the current node graph layout to a dictionary. Returns: dict: serialized session of the current node layout. """ return self._serialize(self.all_nodes()) def deserialize_session(self, layout_data): """ Load node graph session from a dictionary object. Args: layout_data (dict): dictionary object containing a node session. """ self.clear_session() self._deserialize(layout_data) self.clear_undo_stack() def save_session(self, file_path): """ Saves the current node graph session layout to a `JSON` formatted file. Args: file_path (str): path to the saved node layout. """ root_node = self.root_node() if root_node is not None: nodes = root_node.children() else: nodes = self.all_nodes() serialized_data = self._serialize(nodes) node_space = self.get_node_space() if node_space is not None: node_space = node_space.id serialized_data['graph'] = {'node_space': node_space, 'pipe_layout': self._viewer.get_pipe_layout()} serialized_data['graph']['graph_rect'] = self._viewer.scene_rect() serialized_data['graph']['grid_mode'] = self.scene().grid_mode file_path = file_path.strip() with open(file_path, 'w') as file_out: json.dump(serialized_data, file_out, indent=2, separators=(',', ':')) self._model.session = file_path self.session_changed.emit(file_path) self._viewer.clear_key_state() def load_session(self, file_path): """ Load node graph session layout file. Args: file_path (str): path to the serialized layout file. """ self.clear_session() self.import_session(file_path) def import_session(self, file_path): """ Import node graph session layout file. Args: file_path (str): path to the serialized layout file. """ file_path = file_path.strip() if not os.path.isfile(file_path): raise IOError('file does not exist.') try: with open(file_path) as data_file: layout_data = json.load(data_file) except Exception as e: layout_data = None print('Cannot read data from file.\n{}'.format(e)) if not layout_data: return self._deserialize(layout_data) if 'graph' in layout_data.keys(): self.set_node_space(self.root_node()) self._viewer.set_pipe_layout(layout_data['graph']['pipe_layout']) self._viewer.set_scene_rect(layout_data['graph']['graph_rect']) self.set_grid_mode(layout_data['graph'].get('grid_mode', VIEWER_GRID_LINES)) self.set_node_space(self.root_node()) self.clear_undo_stack() self._model.session = file_path self.session_changed.emit(file_path) def copy_nodes(self, nodes=None): """ Copy nodes to the clipboard. Args: nodes (list[NodeGraphQt.BaseNode]): list of nodes (default: selected nodes). """ nodes = nodes or self.selected_nodes() if not nodes: return False clipboard = QtWidgets.QApplication.clipboard() serial_data = self._serialize(nodes) serial_str = json.dumps(serial_data) if serial_str: clipboard.setText(serial_str) return True return False def cut_nodes(self, nodes=None): """ Cut nodes to the clipboard. Args: nodes (list[NodeGraphQt.BaseNode]): list of nodes (default: selected nodes). """ self._undo_stack.beginMacro('cut nodes') nodes = nodes or self.selected_nodes() self.copy_nodes(nodes) self.delete_nodes(nodes) self._undo_stack.endMacro() def paste_nodes(self): """ Pastes nodes copied from the clipboard. """ if not self._editable: return clipboard = QtWidgets.QApplication.clipboard() cb_text = clipboard.text() if not cb_text: return self._undo_stack.beginMacro('pasted nodes') serial_data = json.loads(cb_text) self.clear_selection() nodes = self._deserialize(serial_data, relative_pos=True) [n.set_selected(True) for n in nodes] self._undo_stack.endMacro() def duplicate_nodes(self, nodes): """ Create duplicate copy from the list of nodes. Args: nodes (list[NodeGraphQt.BaseNode]): list of nodes. Returns: list[NodeGraphQt.BaseNode]: list of duplicated node instances. """ if not nodes or not self._editable: return self._undo_stack.beginMacro('duplicate nodes') self.clear_selection() serial = self._serialize(nodes) new_nodes = self._deserialize(serial) offset = 50 for n in new_nodes: x, y = n.pos() n.set_pos(x + offset, y + offset) n.set_property('selected', True) self._undo_stack.endMacro() return new_nodes def disable_nodes(self, nodes, mode=None): """ Set weather to Disable or Enable specified nodes. See Also: :meth:`NodeObject.set_disabled` Args: nodes (list[NodeGraphQt.BaseNode]): list of node instances. mode (bool): (optional) disable state of the nodes. """ if not nodes or not self._editable: return if mode is None: mode = not nodes[0].disabled() if len(nodes) > 1: text = {False: 'enable', True: 'disable'}[mode] text = '{} ({}) nodes'.format(text, len(nodes)) self._undo_stack.beginMacro(text) [n.set_disabled(mode) for n in nodes] self._undo_stack.endMacro() return nodes[0].set_disabled(mode) def question_dialog(self, text, title='Node Graph'): """ Prompts a question open dialog with ``"Yes"`` and ``"No"`` buttons in the node graph. Note: Convenience function to :meth:`NodeGraphQt.NodeGraph.viewer().question_dialog` Args: text (str): question text. title (str): dialog window title. Returns: bool: true if user clicked yes. """ return self._viewer.question_dialog(text, title) def message_dialog(self, text, title='Node Graph'): """ Prompts a file open dialog in the node graph. Note: Convenience function to :meth:`NodeGraphQt.NodeGraph.viewer().message_dialog` Args: text (str): message text. title (str): dialog window title. """ self._viewer.message_dialog(text, title) def load_dialog(self, current_dir=None, ext=None): """ Prompts a file open dialog in the node graph. Note: Convenience function to :meth:`NodeGraphQt.NodeGraph.viewer().load_dialog` Args: current_dir (str): path to a directory. ext (str): custom file type extension (default: ``"json"``) Returns: str: selected file path. """ return self._viewer.load_dialog(current_dir, ext) def save_dialog(self, current_dir=None, ext=None): """ Prompts a file save dialog in the node graph. Note: Convenience function to :meth:`NodeGraphQt.NodeGraph.viewer().save_dialog` Args: current_dir (str): path to a directory. ext (str): custom file type extension (default: ``"json"``) Returns: str: selected file path. """ return self._viewer.save_dialog(current_dir, ext) def use_OpenGL(self): """ Use OpenGL to draw the graph. """ self._viewer.use_OpenGL() def graph_rect(self): """ Get the graph viewer range. Returns: list: [x, y, width, height]. """ return self._viewer.scene_rect() def set_graph_rect(self, rect): """ Set the graph viewer range. Args: rect (list): [x, y, width, height]. """ self._viewer.set_scene_rect(rect) def root_node(self): """ Get the graph root node. Returns: node (BaseNode): node object. """ return self.get_node_by_id('0' * 13) class SubGraph(object): """ The ``NodeGraphQt.SubGraph`` class is the base class that all Sub Graph Node inherit from. *Implemented on NodeGraphQt: * ``v0.1.0`` .. image:: _images/example_subgraph.gif :width: 80% """ def __init__(self): self._children = set() def children(self): """ Returns the children of the sub graph. """ return list(self._children) def create_from_nodes(self, nodes): """ Create sub graph from the nodes. Args: nodes (list[NodeGraphQt.NodeObject]): nodes to create the sub graph. """ if self in nodes: nodes.remove(self) [n.set_parent(self) for n in nodes] def add_child(self, node): """ Add a node to the sub graph. Args: node (NodeGraphQt.BaseNode): node object. """ self._children.add(node) def remove_child(self, node): """ Remove a node from the sub graph. Args: node (NodeGraphQt.BaseNode): node object. """ if node in self._children: self._children.remove(node) def enter(self): """ Action when enter the sub graph. """ pass def exit(self): """ Action when exit the sub graph. """ pass
31.687233
114
0.571214
37b12337a7ef361d68cafe5a8fd78ff9c57a689c
18,819
py
Python
log_complete/model_542.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
log_complete/model_542.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
log_complete/model_542.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
# exported from PySB model 'model' from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD Model() Monomer('Ligand', ['Receptor']) Monomer('ParpU', ['C3A']) Monomer('C8A', ['BidU', 'C3pro']) Monomer('SmacM', ['BaxA']) Monomer('BaxM', ['BidM', 'BaxA']) Monomer('Apop', ['C3pro', 'Xiap']) Monomer('Fadd', ['Receptor', 'C8pro']) Monomer('SmacC', ['Xiap']) Monomer('ParpC') Monomer('Xiap', ['SmacC', 'Apop', 'C3A']) Monomer('C9') Monomer('C3ub') Monomer('C8pro', ['Fadd', 'C6A']) Monomer('C6A', ['C8pro']) Monomer('C3pro', ['Apop', 'C8A']) Monomer('CytoCM', ['BaxA']) Monomer('CytoCC') Monomer('BaxA', ['BaxM', 'BaxA_1', 'BaxA_2', 'SmacM', 'CytoCM']) Monomer('ApafI') Monomer('BidU', ['C8A']) Monomer('BidT') Monomer('C3A', ['Xiap', 'ParpU', 'C6pro']) Monomer('ApafA') Monomer('BidM', ['BaxM']) Monomer('Receptor', ['Ligand', 'Fadd']) Monomer('C6pro', ['C3A']) Parameter('bind_0_Ligand_binder_Receptor_binder_target_2kf', 1.0) Parameter('bind_0_Ligand_binder_Receptor_binder_target_1kr', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_2kf', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_1kr', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr', 1.0) Parameter('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0) Parameter('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr', 1.0) Parameter('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kf', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kr', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr', 1.0) Parameter('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr', 1.0) Parameter('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc', 1.0) Parameter('pore_formation_0_BaxA_pore_2kf', 1.0) Parameter('pore_formation_0_BaxA_pore_1kr', 1.0) Parameter('pore_formation_1_BaxA_pore_2kf', 1.0) Parameter('pore_formation_1_BaxA_pore_1kr', 1.0) Parameter('pore_formation_2_BaxA_pore_2kf', 1.0) Parameter('pore_formation_2_BaxA_pore_1kr', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc', 1.0) Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf', 1.0) Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr', 1.0) Parameter('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('Ligand_0', 1000.0) Parameter('ParpU_0', 1000000.0) Parameter('C8A_0', 0.0) Parameter('SmacM_0', 100000.0) Parameter('BaxM_0', 40000.0) Parameter('Apop_0', 0.0) Parameter('Fadd_0', 130000.0) Parameter('SmacC_0', 0.0) Parameter('ParpC_0', 0.0) Parameter('Xiap_0', 135500.0) Parameter('C9_0', 100000.0) Parameter('C3ub_0', 0.0) Parameter('C8pro_0', 130000.0) Parameter('C6A_0', 0.0) Parameter('C3pro_0', 21000.0) Parameter('CytoCM_0', 500000.0) Parameter('CytoCC_0', 0.0) Parameter('BaxA_0', 0.0) Parameter('ApafI_0', 100000.0) Parameter('BidU_0', 171000.0) Parameter('BidT_0', 0.0) Parameter('C3A_0', 0.0) Parameter('ApafA_0', 0.0) Parameter('BidM_0', 0.0) Parameter('Receptor_0', 100.0) Parameter('C6pro_0', 100.0) Observable('Ligand_obs', Ligand()) Observable('ParpU_obs', ParpU()) Observable('C8A_obs', C8A()) Observable('SmacM_obs', SmacM()) Observable('BaxM_obs', BaxM()) Observable('Apop_obs', Apop()) Observable('Fadd_obs', Fadd()) Observable('SmacC_obs', SmacC()) Observable('ParpC_obs', ParpC()) Observable('Xiap_obs', Xiap()) Observable('C9_obs', C9()) Observable('C3ub_obs', C3ub()) Observable('C8pro_obs', C8pro()) Observable('C6A_obs', C6A()) Observable('C3pro_obs', C3pro()) Observable('CytoCM_obs', CytoCM()) Observable('CytoCC_obs', CytoCC()) Observable('BaxA_obs', BaxA()) Observable('ApafI_obs', ApafI()) Observable('BidU_obs', BidU()) Observable('BidT_obs', BidT()) Observable('C3A_obs', C3A()) Observable('ApafA_obs', ApafA()) Observable('BidM_obs', BidM()) Observable('Receptor_obs', Receptor()) Observable('C6pro_obs', C6pro()) Rule('bind_0_Ligand_binder_Receptor_binder_target', Ligand(Receptor=None) + Receptor(Ligand=None, Fadd=None) | Ligand(Receptor=1) % Receptor(Ligand=1, Fadd=None), bind_0_Ligand_binder_Receptor_binder_target_2kf, bind_0_Ligand_binder_Receptor_binder_target_1kr) Rule('bind_0_Receptor_binder_Fadd_binder_target', Receptor(Ligand=ANY, Fadd=None) + Fadd(Receptor=None, C8pro=None) | Receptor(Ligand=ANY, Fadd=1) % Fadd(Receptor=1, C8pro=None), bind_0_Receptor_binder_Fadd_binder_target_2kf, bind_0_Receptor_binder_Fadd_binder_target_1kr) Rule('substrate_binding_0_Fadd_catalyzer_C8pro_substrate', Fadd(Receptor=ANY, C8pro=None) + C8pro(Fadd=None, C6A=None) | Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None), substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf, substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr) Rule('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product', Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None) >> Fadd(Receptor=ANY, C8pro=None) + C8A(BidU=None, C3pro=None), catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc) Rule('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=None, C3pro=None) + BidU(C8A=None) | C8A(BidU=1, C3pro=None) % BidU(C8A=1), catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf, catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr) Rule('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=1, C3pro=None) % BidU(C8A=1) >> C8A(BidU=None, C3pro=None) + BidT(), catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc) Rule('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex', ApafI() + CytoCC() | ApafA(), conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf, conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr) Rule('inhibition_0_SmacC_inhibitor_Xiap_inh_target', SmacC(Xiap=None) + Xiap(SmacC=None, Apop=None, C3A=None) | SmacC(Xiap=1) % Xiap(SmacC=1, Apop=None, C3A=None), inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf, inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr) Rule('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex', ApafA() + C9() | Apop(C3pro=None, Xiap=None), conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf, conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr) Rule('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=None, Xiap=None) + C3pro(Apop=None, C8A=None) | Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None), catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr) Rule('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None) >> Apop(C3pro=None, Xiap=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc) Rule('inhibition_0_Xiap_inhibitor_Apop_inh_target', Xiap(SmacC=None, Apop=None, C3A=None) + Apop(C3pro=None, Xiap=None) | Xiap(SmacC=None, Apop=1, C3A=None) % Apop(C3pro=None, Xiap=1), inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf, inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr) Rule('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=None) + C3A(Xiap=None, ParpU=None, C6pro=None) | Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None), catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf, catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr) Rule('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None) >> Xiap(SmacC=None, Apop=None, C3A=None) + C3ub(), catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc) Rule('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=None, C6pro=None) + ParpU(C3A=None) | C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1), catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf, catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr) Rule('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + ParpC(), catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc) Rule('equilibration_0_BidT_equil_a_BidM_equil_b', BidT() | BidM(BaxM=None), equilibration_0_BidT_equil_a_BidM_equil_b_1kf, equilibration_0_BidT_equil_a_BidM_equil_b_1kr) Rule('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=None) + BaxM(BidM=None, BaxA=None) | BidM(BaxM=1) % BaxM(BidM=1, BaxA=None), catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf, catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr) Rule('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=1) % BaxM(BidM=1, BaxA=None) >> BidM(BaxM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc) Rule('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxM(BidM=None, BaxA=None) | BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1), self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf, self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr) Rule('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1) >> BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc) Rule('pore_formation_0_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None), pore_formation_0_BaxA_pore_2kf, pore_formation_0_BaxA_pore_1kr) Rule('pore_formation_1_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None), pore_formation_1_BaxA_pore_2kf, pore_formation_1_BaxA_pore_1kr) Rule('pore_formation_2_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None), pore_formation_2_BaxA_pore_2kf, pore_formation_2_BaxA_pore_1kr) Rule('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5), transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf, transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr) Rule('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacC(Xiap=None), transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc) Rule('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5), transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf, transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr) Rule('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCC(), transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc) Rule('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=None) + C3pro(Apop=None, C8A=None) | C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1), catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr) Rule('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1) >> C8A(BidU=None, C3pro=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc) Rule('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=None) + C6pro(C3A=None) | C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1), catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf, catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr) Rule('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + C6A(C8pro=None), catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc) Rule('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=None) + C8pro(Fadd=None, C6A=None) | C6A(C8pro=1) % C8pro(Fadd=None, C6A=1), catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf, catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr) Rule('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=1) % C8pro(Fadd=None, C6A=1) >> C6A(C8pro=None) + C8A(BidU=None, C3pro=None), catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc) Initial(Ligand(Receptor=None), Ligand_0) Initial(ParpU(C3A=None), ParpU_0) Initial(C8A(BidU=None, C3pro=None), C8A_0) Initial(SmacM(BaxA=None), SmacM_0) Initial(BaxM(BidM=None, BaxA=None), BaxM_0) Initial(Apop(C3pro=None, Xiap=None), Apop_0) Initial(Fadd(Receptor=None, C8pro=None), Fadd_0) Initial(SmacC(Xiap=None), SmacC_0) Initial(ParpC(), ParpC_0) Initial(Xiap(SmacC=None, Apop=None, C3A=None), Xiap_0) Initial(C9(), C9_0) Initial(C3ub(), C3ub_0) Initial(C8pro(Fadd=None, C6A=None), C8pro_0) Initial(C6A(C8pro=None), C6A_0) Initial(C3pro(Apop=None, C8A=None), C3pro_0) Initial(CytoCM(BaxA=None), CytoCM_0) Initial(CytoCC(), CytoCC_0) Initial(BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), BaxA_0) Initial(ApafI(), ApafI_0) Initial(BidU(C8A=None), BidU_0) Initial(BidT(), BidT_0) Initial(C3A(Xiap=None, ParpU=None, C6pro=None), C3A_0) Initial(ApafA(), ApafA_0) Initial(BidM(BaxM=None), BidM_0) Initial(Receptor(Ligand=None, Fadd=None), Receptor_0) Initial(C6pro(C3A=None), C6pro_0)
91.354369
710
0.806525
51e3eab22fc98e26de4431fb6a35fcb993079975
1,031
py
Python
setup.py
wesleyit/sample_python_package
21d0cad1db304e7f2ec6b236dad6eb144cc16d3d
[ "MIT" ]
1
2020-11-20T21:28:30.000Z
2020-11-20T21:28:30.000Z
setup.py
wesleyit/sample_python_package
21d0cad1db304e7f2ec6b236dad6eb144cc16d3d
[ "MIT" ]
null
null
null
setup.py
wesleyit/sample_python_package
21d0cad1db304e7f2ec6b236dad6eb144cc16d3d
[ "MIT" ]
null
null
null
import io import os import re from setuptools import find_packages from setuptools import setup def read(filename): filename = os.path.join(os.path.dirname(__file__), filename) text_type = type(u"") with io.open(filename, mode="r", encoding='utf-8') as fd: f = r':[a-z]+:`~?(.*?)`' return re.sub(text_type(f), text_type(r'``\1``'), fd.read()) setup( name="sample_python_package", version="0.1.0", url="https://github.com/wesleyit/sample_python_package", license='MIT', author="Wesley Rodrigues da Silva", author_email="wesley.it@gmail.com", description="This is a sample package structure which \ you can apply to your projects.", long_description=read("README.md"), packages=find_packages(exclude=('tests',)), install_requires=[], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], )
28.638889
68
0.637245
76e608f0fd23f64a9b109e67089edd53d9ce59c5
238
py
Python
src/rendere/eml/eml_utils.py
PASTAplus/rendere
63cc5effae4118fa20545339c2f0b0ebbee35271
[ "Apache-2.0" ]
null
null
null
src/rendere/eml/eml_utils.py
PASTAplus/rendere
63cc5effae4118fa20545339c2f0b0ebbee35271
[ "Apache-2.0" ]
5
2021-04-01T02:12:50.000Z
2022-03-14T01:40:58.000Z
src/rendere/eml/eml_utils.py
PASTAplus/rendere
63cc5effae4118fa20545339c2f0b0ebbee35271
[ "Apache-2.0" ]
1
2020-09-22T21:47:31.000Z
2020-09-22T21:47:31.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :Mod: eml_utils :Synopsis: :Author: servilla :Created: 3/25/20 """ import daiquiri logger = daiquiri.getLogger(__name__) def clean(text): return " ".join(text.split())
10.347826
37
0.617647
50c533f043cbf4af4b7ff1a5630fa44d4d3e74f1
2,036
py
Python
tests/conftest.py
drawjk705/us-pls
6b9a696b18c18de81b279862f182fb990604b998
[ "MIT" ]
null
null
null
tests/conftest.py
drawjk705/us-pls
6b9a696b18c18de81b279862f182fb990604b998
[ "MIT" ]
null
null
null
tests/conftest.py
drawjk705/us-pls
6b9a696b18c18de81b279862f182fb990604b998
[ "MIT" ]
null
null
null
import inspect from typing import Dict, cast from unittest.mock import MagicMock import pandas import pytest import requests from pytest import FixtureRequest, MonkeyPatch from pytest_mock.plugin import MockerFixture from tests import utils # pyright: reportPrivateUsage=false # pandas mocks @pytest.fixture def mock_read_csv(mocker: MockerFixture) -> MagicMock: return mocker.patch.object(pandas, "read_csv") @pytest.fixture(autouse=True) def no_requests(monkeypatch: MonkeyPatch): """Remove requests.sessions.Session.request for all tests.""" monkeypatch.delattr("requests.sessions.Session.request") @pytest.fixture(scope="function") def api_fixture(request: FixtureRequest, mocker: MockerFixture): request.cls.requests_get_mock = mocker.patch.object(requests, "get") # type: ignore @pytest.fixture(scope="function") def inject_mocker_to_class(request: FixtureRequest, mocker: MockerFixture): request.cls.mocker = mocker # type: ignore @pytest.fixture(scope="function") def service_fixture(request: FixtureRequest): """ This mocks all of a service's dependencies, instantiates the service with those mocked dependencies, and assigns the service to the test class's `_service` variable """ req = cast(utils._RequestCls, request) obj = req.cls service = utils.extract_service(obj) dependencies: Dict[str, MagicMock] = {} # this lets us see all of the service's constructor types for dep_name, dep_type in inspect.signature(service).parameters.items(): # this condition will be true if the service inherits # from a generic class if hasattr(dep_type.annotation, "__origin__"): dependencies[dep_name] = MagicMock(dep_type.annotation.__origin__) else: dependencies[dep_name] = MagicMock(dep_type.annotation) # we call the service's constructor with the mocked dependencies # and set the test class obj's _service attribute to hold this service obj._service = service(**dependencies)
30.848485
88
0.74165
f0337781578bba2c9fe19a563e38eeecac72e122
2,074
py
Python
Finals Practice/6.py
ikramulkayes/Python_season2
d057460d07c5d2d218ecd52e08c1d355add44df2
[ "MIT" ]
null
null
null
Finals Practice/6.py
ikramulkayes/Python_season2
d057460d07c5d2d218ecd52e08c1d355add44df2
[ "MIT" ]
null
null
null
Finals Practice/6.py
ikramulkayes/Python_season2
d057460d07c5d2d218ecd52e08c1d355add44df2
[ "MIT" ]
null
null
null
class Student: def __init__(self,name,ID): self.name = name self.ID = ID def Details(self): return "Name: "+self.name+"\n"+"ID: "+self.ID+"\n" #Write your code here class CSEStudent(Student): def __init__(self, name, ID,sem): super().__init__(name, ID) self.sem = sem self.dic = {} def Details(self): k = super().Details() return k+ f"Current semester: {self.sem}" def addCourseWithMarks(self,*args): count = 0 for elm in range(0,len(args),2): self.dic[args[count]] = args[count+1] count += 2 def showGPA(self): print(f"{self.name} has taken {len(self.dic)} courses.") sum1 = 0 cgpa = 0 for k,v in self.dic.items(): if v>=85: cgpa = 4.0 elif v >= 80: cgpa = 3.3 elif v >= 70: cgpa = 3.0 elif v >=65: cgpa = 2.3 elif v >= 57: cgpa = 2.0 elif v >=55: cgpa = 1.3 elif v >= 50: cgpa = 1.0 else: cgpa = 0.0 sum1 += cgpa print(f"{k}: {cgpa}") print(f"GPA of {self.name} is : {round(sum1/len(self.dic),2)}") Bob = CSEStudent("Bob","20301018","Fall 2020") Carol = CSEStudent("Carol","16301814","Fall 2020") Anny = CSEStudent("Anny","18201234","Fall 2020") print("#########################") print(Bob.Details()) print("#########################") print(Carol.Details()) print("#########################") print(Anny.Details()) print("#########################") Bob.addCourseWithMarks("CSE111",83.5,"CSE230",73.0,"CSE260",92.5) Carol.addCourseWithMarks("CSE470",62.5,"CSE422",69.0,"CSE460",76.5,"CSE461",87.0) Anny.addCourseWithMarks("CSE340",45.5,"CSE321",95.0,"CSE370",91.0) print("----------------------------") Bob.showGPA() print("----------------------------") Carol.showGPA() print("----------------------------") Anny.showGPA()
26.935065
81
0.460463
46e1e5bd87c51704c5d75cd0d9012a45133e6f6b
1,790
py
Python
setup.py
pedrofran12/hpim_dm
fe949294b5e75ab544dcd40ff51ceafc1d3b2f0c
[ "MIT" ]
1
2020-02-04T20:59:03.000Z
2020-02-04T20:59:03.000Z
setup.py
pedrofran12/hpim_dm
fe949294b5e75ab544dcd40ff51ceafc1d3b2f0c
[ "MIT" ]
3
2020-06-09T16:37:01.000Z
2021-08-30T00:31:12.000Z
setup.py
pedrofran12/hpim_dm
fe949294b5e75ab544dcd40ff51ceafc1d3b2f0c
[ "MIT" ]
1
2020-11-23T06:47:46.000Z
2020-11-23T06:47:46.000Z
import sys from setuptools import setup, find_packages # we only support Python 3 version >= 3.3 if len(sys.argv) >= 2 and sys.argv[1] == "install" and sys.version_info < (3, 3): raise SystemExit("Python 3.3 or higher is required") dependencies = open("requirements.txt", "r").read().splitlines() setup( name="hpim-dm", description="HPIM-DM protocol", long_description=open("README.md", "r").read(), long_description_content_type="text/markdown", keywords="HPIM-DM Multicast Routing Protocol HPIM Dense-Mode Router IPv4 IPv6", version="1.5.1", url="http://github.com/pedrofran12/hpim_dm", author="Pedro Oliveira", author_email="pedro.francisco.oliveira@tecnico.ulisboa.pt", license="MIT", install_requires=dependencies, packages=find_packages(exclude=["docs"]), entry_points={ "console_scripts": [ "hpim-dm = hpimdm.Run:main", ] }, include_package_data=True, zip_safe=False, platforms="any", classifiers=[ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Information Technology", "Topic :: System :: Networking", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", ], python_requires=">=3.3", )
35.098039
83
0.622905
f1d99d13a2aef0e1ac895bd3c7ad2ce4949a6f13
16,079
py
Python
log_mito/model_727.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
log_mito/model_727.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
log_mito/model_727.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
# exported from PySB model 'model' from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD Model() Monomer('Ligand', ['Receptor']) Monomer('ParpU', ['C3A']) Monomer('C8A', ['BidU']) Monomer('SmacM', ['BaxA']) Monomer('BaxM', ['BidM', 'BaxA']) Monomer('Apop', ['C3pro', 'Xiap']) Monomer('Fadd', ['Receptor', 'C8pro']) Monomer('SmacC', ['Xiap']) Monomer('ParpC') Monomer('Xiap', ['SmacC', 'Apop', 'C3A']) Monomer('C9') Monomer('C3ub') Monomer('C8pro', ['Fadd']) Monomer('C3pro', ['Apop']) Monomer('CytoCM', ['BaxA']) Monomer('CytoCC') Monomer('BaxA', ['BaxM', 'BaxA_1', 'BaxA_2', 'SmacM', 'CytoCM']) Monomer('ApafI') Monomer('BidU', ['C8A']) Monomer('BidT') Monomer('C3A', ['Xiap', 'ParpU']) Monomer('ApafA') Monomer('BidM', ['BaxM']) Monomer('Receptor', ['Ligand', 'Fadd']) Parameter('bind_0_Ligand_binder_Receptor_binder_target_2kf', 1.0) Parameter('bind_0_Ligand_binder_Receptor_binder_target_1kr', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_2kf', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_1kr', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr', 1.0) Parameter('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0) Parameter('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr', 1.0) Parameter('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kf', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kr', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr', 1.0) Parameter('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr', 1.0) Parameter('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc', 1.0) Parameter('pore_formation_0_BaxA_pore_2kf', 1.0) Parameter('pore_formation_0_BaxA_pore_1kr', 1.0) Parameter('pore_formation_1_BaxA_pore_2kf', 1.0) Parameter('pore_formation_1_BaxA_pore_1kr', 1.0) Parameter('pore_formation_2_BaxA_pore_2kf', 1.0) Parameter('pore_formation_2_BaxA_pore_1kr', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc', 1.0) Parameter('Ligand_0', 1000.0) Parameter('ParpU_0', 1000000.0) Parameter('C8A_0', 0.0) Parameter('SmacM_0', 100000.0) Parameter('BaxM_0', 40000.0) Parameter('Apop_0', 0.0) Parameter('Fadd_0', 130000.0) Parameter('SmacC_0', 0.0) Parameter('ParpC_0', 0.0) Parameter('Xiap_0', 181750.0) Parameter('C9_0', 100000.0) Parameter('C3ub_0', 0.0) Parameter('C8pro_0', 130000.0) Parameter('C3pro_0', 21000.0) Parameter('CytoCM_0', 500000.0) Parameter('CytoCC_0', 0.0) Parameter('BaxA_0', 0.0) Parameter('ApafI_0', 100000.0) Parameter('BidU_0', 171000.0) Parameter('BidT_0', 0.0) Parameter('C3A_0', 0.0) Parameter('ApafA_0', 0.0) Parameter('BidM_0', 0.0) Parameter('Receptor_0', 100.0) Observable('Ligand_obs', Ligand()) Observable('ParpU_obs', ParpU()) Observable('C8A_obs', C8A()) Observable('SmacM_obs', SmacM()) Observable('BaxM_obs', BaxM()) Observable('Apop_obs', Apop()) Observable('Fadd_obs', Fadd()) Observable('SmacC_obs', SmacC()) Observable('ParpC_obs', ParpC()) Observable('Xiap_obs', Xiap()) Observable('C9_obs', C9()) Observable('C3ub_obs', C3ub()) Observable('C8pro_obs', C8pro()) Observable('C3pro_obs', C3pro()) Observable('CytoCM_obs', CytoCM()) Observable('CytoCC_obs', CytoCC()) Observable('BaxA_obs', BaxA()) Observable('ApafI_obs', ApafI()) Observable('BidU_obs', BidU()) Observable('BidT_obs', BidT()) Observable('C3A_obs', C3A()) Observable('ApafA_obs', ApafA()) Observable('BidM_obs', BidM()) Observable('Receptor_obs', Receptor()) Rule('bind_0_Ligand_binder_Receptor_binder_target', Ligand(Receptor=None) + Receptor(Ligand=None, Fadd=None) | Ligand(Receptor=1) % Receptor(Ligand=1, Fadd=None), bind_0_Ligand_binder_Receptor_binder_target_2kf, bind_0_Ligand_binder_Receptor_binder_target_1kr) Rule('bind_0_Receptor_binder_Fadd_binder_target', Receptor(Ligand=ANY, Fadd=None) + Fadd(Receptor=None, C8pro=None) | Receptor(Ligand=ANY, Fadd=1) % Fadd(Receptor=1, C8pro=None), bind_0_Receptor_binder_Fadd_binder_target_2kf, bind_0_Receptor_binder_Fadd_binder_target_1kr) Rule('substrate_binding_0_Fadd_catalyzer_C8pro_substrate', Fadd(Receptor=ANY, C8pro=None) + C8pro(Fadd=None) | Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1), substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf, substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr) Rule('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product', Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1) >> Fadd(Receptor=ANY, C8pro=None) + C8A(BidU=None), catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc) Rule('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=None) + BidU(C8A=None) | C8A(BidU=1) % BidU(C8A=1), catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf, catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr) Rule('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=1) % BidU(C8A=1) >> C8A(BidU=None) + BidT(), catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc) Rule('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex', ApafI() + CytoCC() | ApafA(), conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf, conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr) Rule('inhibition_0_SmacC_inhibitor_Xiap_inh_target', SmacC(Xiap=None) + Xiap(SmacC=None, Apop=None, C3A=None) | SmacC(Xiap=1) % Xiap(SmacC=1, Apop=None, C3A=None), inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf, inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr) Rule('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex', ApafA() + C9() | Apop(C3pro=None, Xiap=None), conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf, conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr) Rule('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=None, Xiap=None) + C3pro(Apop=None) | Apop(C3pro=1, Xiap=None) % C3pro(Apop=1), catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr) Rule('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=1, Xiap=None) % C3pro(Apop=1) >> Apop(C3pro=None, Xiap=None) + C3A(Xiap=None, ParpU=None), catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc) Rule('inhibition_0_Xiap_inhibitor_Apop_inh_target', Xiap(SmacC=None, Apop=None, C3A=None) + Apop(C3pro=None, Xiap=None) | Xiap(SmacC=None, Apop=1, C3A=None) % Apop(C3pro=None, Xiap=1), inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf, inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr) Rule('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=None) + C3A(Xiap=None, ParpU=None) | Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None), catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf, catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr) Rule('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None) >> Xiap(SmacC=None, Apop=None, C3A=None) + C3ub(), catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc) Rule('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=None) + ParpU(C3A=None) | C3A(Xiap=None, ParpU=1) % ParpU(C3A=1), catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf, catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr) Rule('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=1) % ParpU(C3A=1) >> C3A(Xiap=None, ParpU=None) + ParpC(), catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc) Rule('equilibration_0_BidT_equil_a_BidM_equil_b', BidT() | BidM(BaxM=None), equilibration_0_BidT_equil_a_BidM_equil_b_1kf, equilibration_0_BidT_equil_a_BidM_equil_b_1kr) Rule('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=None) + BaxM(BidM=None, BaxA=None) | BidM(BaxM=1) % BaxM(BidM=1, BaxA=None), catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf, catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr) Rule('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=1) % BaxM(BidM=1, BaxA=None) >> BidM(BaxM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc) Rule('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxM(BidM=None, BaxA=None) | BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1), self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf, self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr) Rule('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1) >> BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc) Rule('pore_formation_0_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None), pore_formation_0_BaxA_pore_2kf, pore_formation_0_BaxA_pore_1kr) Rule('pore_formation_1_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None), pore_formation_1_BaxA_pore_2kf, pore_formation_1_BaxA_pore_1kr) Rule('pore_formation_2_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None), pore_formation_2_BaxA_pore_2kf, pore_formation_2_BaxA_pore_1kr) Rule('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5), transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf, transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr) Rule('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacC(Xiap=None), transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc) Rule('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5), transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf, transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr) Rule('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCC(), transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc) Initial(Ligand(Receptor=None), Ligand_0) Initial(ParpU(C3A=None), ParpU_0) Initial(C8A(BidU=None), C8A_0) Initial(SmacM(BaxA=None), SmacM_0) Initial(BaxM(BidM=None, BaxA=None), BaxM_0) Initial(Apop(C3pro=None, Xiap=None), Apop_0) Initial(Fadd(Receptor=None, C8pro=None), Fadd_0) Initial(SmacC(Xiap=None), SmacC_0) Initial(ParpC(), ParpC_0) Initial(Xiap(SmacC=None, Apop=None, C3A=None), Xiap_0) Initial(C9(), C9_0) Initial(C3ub(), C3ub_0) Initial(C8pro(Fadd=None), C8pro_0) Initial(C3pro(Apop=None), C3pro_0) Initial(CytoCM(BaxA=None), CytoCM_0) Initial(CytoCC(), CytoCC_0) Initial(BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), BaxA_0) Initial(ApafI(), ApafI_0) Initial(BidU(C8A=None), BidU_0) Initial(BidT(), BidT_0) Initial(C3A(Xiap=None, ParpU=None), C3A_0) Initial(ApafA(), ApafA_0) Initial(BidM(BaxM=None), BidM_0) Initial(Receptor(Ligand=None, Fadd=None), Receptor_0)
87.863388
710
0.80347
d53a9bdb546eed37813770c33ab6f7c458ecbbea
8,721
py
Python
external/rocksdb/tools/advisor/test/test_db_options_parser.py
cashbitecrypto/cashbite
991200dc37234caa74c603cb8aee094cbd7ce429
[ "BSD-3-Clause" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
external/rocksdb/tools/advisor/test/test_db_options_parser.py
cashbitecrypto/cashbite
991200dc37234caa74c603cb8aee094cbd7ce429
[ "BSD-3-Clause" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
external/rocksdb/tools/advisor/test/test_db_options_parser.py
cashbitecrypto/cashbite
991200dc37234caa74c603cb8aee094cbd7ce429
[ "BSD-3-Clause" ]
1,731
2017-12-09T15:09:43.000Z
2022-03-30T18:23:38.000Z
# Copyright (c) 2011-present, Facebook, Inc. All rights reserved. # This source code is licensed under both the GPLv2 (found in the # COPYING file in the root directory) and Apache 2.0 License # (found in the LICENSE.Apache file in the root directory). from advisor.db_log_parser import NO_COL_FAMILY from advisor.db_options_parser import DatabaseOptions from advisor.rule_parser import Condition, OptionCondition import os import unittest class TestDatabaseOptions(unittest.TestCase): def setUp(self): self.this_path = os.path.abspath(os.path.dirname(__file__)) self.og_options = os.path.join( self.this_path, 'input_files/OPTIONS-000005' ) misc_options = [ 'bloom_bits = 4', 'rate_limiter_bytes_per_sec = 1024000' ] # create the options object self.db_options = DatabaseOptions(self.og_options, misc_options) # perform clean-up before running tests self.generated_options = os.path.join( self.this_path, '../temp/OPTIONS_testing.tmp' ) if os.path.isfile(self.generated_options): os.remove(self.generated_options) def test_get_options_diff(self): old_opt = { 'DBOptions.stats_dump_freq_sec': {NO_COL_FAMILY: '20'}, 'CFOptions.write_buffer_size': { 'default': '1024000', 'col_fam_A': '128000', 'col_fam_B': '128000000' }, 'DBOptions.use_fsync': {NO_COL_FAMILY: 'true'}, 'DBOptions.max_log_file_size': {NO_COL_FAMILY: '128000000'} } new_opt = { 'bloom_bits': {NO_COL_FAMILY: '4'}, 'CFOptions.write_buffer_size': { 'default': '128000000', 'col_fam_A': '128000', 'col_fam_C': '128000000' }, 'DBOptions.use_fsync': {NO_COL_FAMILY: 'true'}, 'DBOptions.max_log_file_size': {NO_COL_FAMILY: '0'} } diff = DatabaseOptions.get_options_diff(old_opt, new_opt) expected_diff = { 'DBOptions.stats_dump_freq_sec': {NO_COL_FAMILY: ('20', None)}, 'bloom_bits': {NO_COL_FAMILY: (None, '4')}, 'CFOptions.write_buffer_size': { 'default': ('1024000', '128000000'), 'col_fam_B': ('128000000', None), 'col_fam_C': (None, '128000000') }, 'DBOptions.max_log_file_size': {NO_COL_FAMILY: ('128000000', '0')} } self.assertDictEqual(diff, expected_diff) def test_is_misc_option(self): self.assertTrue(DatabaseOptions.is_misc_option('bloom_bits')) self.assertFalse( DatabaseOptions.is_misc_option('DBOptions.stats_dump_freq_sec') ) def test_set_up(self): options = self.db_options.get_all_options() self.assertEqual(22, len(options.keys())) expected_misc_options = { 'bloom_bits': '4', 'rate_limiter_bytes_per_sec': '1024000' } self.assertDictEqual( expected_misc_options, self.db_options.get_misc_options() ) self.assertListEqual( ['default', 'col_fam_A'], self.db_options.get_column_families() ) def test_get_options(self): opt_to_get = [ 'DBOptions.manual_wal_flush', 'DBOptions.db_write_buffer_size', 'bloom_bits', 'CFOptions.compaction_filter_factory', 'CFOptions.num_levels', 'rate_limiter_bytes_per_sec', 'TableOptions.BlockBasedTable.block_align', 'random_option' ] options = self.db_options.get_options(opt_to_get) expected_options = { 'DBOptions.manual_wal_flush': {NO_COL_FAMILY: 'false'}, 'DBOptions.db_write_buffer_size': {NO_COL_FAMILY: '0'}, 'bloom_bits': {NO_COL_FAMILY: '4'}, 'CFOptions.compaction_filter_factory': { 'default': 'nullptr', 'col_fam_A': 'nullptr' }, 'CFOptions.num_levels': {'default': '7', 'col_fam_A': '5'}, 'rate_limiter_bytes_per_sec': {NO_COL_FAMILY: '1024000'}, 'TableOptions.BlockBasedTable.block_align': { 'default': 'false', 'col_fam_A': 'true' } } self.assertDictEqual(expected_options, options) def test_update_options(self): # add new, update old, set old # before updating expected_old_opts = { 'DBOptions.db_log_dir': {NO_COL_FAMILY: None}, 'DBOptions.manual_wal_flush': {NO_COL_FAMILY: 'false'}, 'bloom_bits': {NO_COL_FAMILY: '4'}, 'CFOptions.num_levels': {'default': '7', 'col_fam_A': '5'}, 'TableOptions.BlockBasedTable.block_restart_interval': { 'col_fam_A': '16' } } get_opts = list(expected_old_opts.keys()) options = self.db_options.get_options(get_opts) self.assertEqual(expected_old_opts, options) # after updating options update_opts = { 'DBOptions.db_log_dir': {NO_COL_FAMILY: '/dev/shm'}, 'DBOptions.manual_wal_flush': {NO_COL_FAMILY: 'true'}, 'bloom_bits': {NO_COL_FAMILY: '2'}, 'CFOptions.num_levels': {'col_fam_A': '7'}, 'TableOptions.BlockBasedTable.block_restart_interval': { 'default': '32' }, 'random_misc_option': {NO_COL_FAMILY: 'something'} } self.db_options.update_options(update_opts) update_opts['CFOptions.num_levels']['default'] = '7' update_opts['TableOptions.BlockBasedTable.block_restart_interval'] = { 'default': '32', 'col_fam_A': '16' } get_opts.append('random_misc_option') options = self.db_options.get_options(get_opts) self.assertDictEqual(update_opts, options) expected_misc_options = { 'bloom_bits': '2', 'rate_limiter_bytes_per_sec': '1024000', 'random_misc_option': 'something' } self.assertDictEqual( expected_misc_options, self.db_options.get_misc_options() ) def test_generate_options_config(self): # make sure file does not exist from before self.assertFalse(os.path.isfile(self.generated_options)) self.db_options.generate_options_config('testing') self.assertTrue(os.path.isfile(self.generated_options)) def test_check_and_trigger_conditions(self): # options only from CFOptions # setup the OptionCondition objects to check and trigger update_dict = { 'CFOptions.level0_file_num_compaction_trigger': {'col_fam_A': '4'}, 'CFOptions.max_bytes_for_level_base': {'col_fam_A': '10'} } self.db_options.update_options(update_dict) cond1 = Condition('opt-cond-1') cond1 = OptionCondition.create(cond1) cond1.set_parameter( 'options', [ 'CFOptions.level0_file_num_compaction_trigger', 'TableOptions.BlockBasedTable.block_restart_interval', 'CFOptions.max_bytes_for_level_base' ] ) cond1.set_parameter( 'evaluate', 'int(options[0])*int(options[1])-int(options[2])>=0' ) # only DBOptions cond2 = Condition('opt-cond-2') cond2 = OptionCondition.create(cond2) cond2.set_parameter( 'options', [ 'DBOptions.db_write_buffer_size', 'bloom_bits', 'rate_limiter_bytes_per_sec' ] ) cond2.set_parameter( 'evaluate', '(int(options[2]) * int(options[1]) * int(options[0]))==0' ) # mix of CFOptions and DBOptions cond3 = Condition('opt-cond-3') cond3 = OptionCondition.create(cond3) cond3.set_parameter( 'options', [ 'DBOptions.db_write_buffer_size', # 0 'CFOptions.num_levels', # 5, 7 'bloom_bits' # 4 ] ) cond3.set_parameter( 'evaluate', 'int(options[2])*int(options[0])+int(options[1])>6' ) self.db_options.check_and_trigger_conditions([cond1, cond2, cond3]) cond1_trigger = {'col_fam_A': ['4', '16', '10']} self.assertDictEqual(cond1_trigger, cond1.get_trigger()) cond2_trigger = {NO_COL_FAMILY: ['0', '4', '1024000']} self.assertDictEqual(cond2_trigger, cond2.get_trigger()) cond3_trigger = {'default': ['0', '7', '4']} self.assertDictEqual(cond3_trigger, cond3.get_trigger()) if __name__ == '__main__': unittest.main()
40.18894
79
0.595803
5617134b605bded511fbc236c6c29c75ba13e157
2,654
py
Python
test/pyaz/mariadb/server/firewall_rule/__init__.py
bigdatamoore/py-az-cli
54383a4ee7cc77556f6183e74e992eec95b28e01
[ "MIT" ]
null
null
null
test/pyaz/mariadb/server/firewall_rule/__init__.py
bigdatamoore/py-az-cli
54383a4ee7cc77556f6183e74e992eec95b28e01
[ "MIT" ]
9
2021-09-24T16:37:24.000Z
2021-12-24T00:39:19.000Z
test/pyaz/mariadb/server/firewall_rule/__init__.py
bigdatamoore/py-az-cli
54383a4ee7cc77556f6183e74e992eec95b28e01
[ "MIT" ]
null
null
null
import json, subprocess from .... pyaz_utils import get_cli_name, get_params def create(resource_group, server_name, name, start_ip_address, end_ip_address): params = get_params(locals()) command = "az mariadb server firewall-rule create " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def delete(resource_group, server_name, name, yes=None): params = get_params(locals()) command = "az mariadb server firewall-rule delete " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def show(resource_group, server_name, name): params = get_params(locals()) command = "az mariadb server firewall-rule show " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def list(resource_group, server_name): params = get_params(locals()) command = "az mariadb server firewall-rule list " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def update(resource_group, server_name, name, start_ip_address=None, end_ip_address=None, set=None, add=None, remove=None, force_string=None): params = get_params(locals()) command = "az mariadb server firewall-rule update " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr)
35.864865
142
0.67257
5861f804ce95c74d096e68006505940e3d79a978
17,175
py
Python
fast_io/core.py
TarunKurella/micropython-async
45f51dd18de78caebb97c6445f47c178d00175a3
[ "MIT" ]
2
2019-07-20T11:33:22.000Z
2019-07-20T11:33:35.000Z
fast_io/core.py
TarunKurella/micropython-async
45f51dd18de78caebb97c6445f47c178d00175a3
[ "MIT" ]
null
null
null
fast_io/core.py
TarunKurella/micropython-async
45f51dd18de78caebb97c6445f47c178d00175a3
[ "MIT" ]
null
null
null
# uasyncio.core fast_io # (c) 2014-2018 Paul Sokolovsky. MIT license. # This is a fork of official MicroPython uasynco. It is recommended to use # the official version unless the specific features of this fork are required. # Changes copyright (c) Peter Hinch 2018, 2019 # Code at https://github.com/peterhinch/micropython-async.git # fork: peterhinch/micropython-lib branch: uasyncio-io-fast-and-rw version = ('fast_io', '0.25') try: import rtc_time as time # Low power timebase using RTC except ImportError: import utime as time import utimeq import ucollections type_gen = type((lambda: (yield))()) type_genf = type((lambda: (yield))) # Type of a generator function upy iss #3241 DEBUG = 0 log = None def set_debug(val): global DEBUG, log DEBUG = val if val: import logging log = logging.getLogger("uasyncio.core") class CancelledError(Exception): pass class TimeoutError(CancelledError): pass class EventLoop: def __init__(self, runq_len=16, waitq_len=16, ioq_len=0, lp_len=0): self.runq = ucollections.deque((), runq_len, True) self._max_od = 0 self.lpq = utimeq.utimeq(lp_len) if lp_len else None self.ioq_len = ioq_len self.canned = set() if ioq_len: self.ioq = ucollections.deque((), ioq_len, True) self._call_io = self._call_now else: self._call_io = self.call_soon self.waitq = utimeq.utimeq(waitq_len) # Current task being run. Task is a top-level coroutine scheduled # in the event loop (sub-coroutines executed transparently by # yield from/await, event loop "doesn't see" them). self.cur_task = None def time(self): return time.ticks_ms() def create_task(self, coro): # CPython 3.4.2 assert not isinstance(coro, type_genf), 'Coroutine arg expected.' # upy issue #3241 # create_task with a callable would work, so above assert only traps the easily-made error self.call_later_ms(0, coro) # CPython asyncio incompatibility: we don't return Task object def _call_now(self, callback, *args): # For stream I/O only if __debug__ and DEBUG: log.debug("Scheduling in ioq: %s", (callback, args)) self.ioq.append(callback) if not isinstance(callback, type_gen): self.ioq.append(args) def max_overdue_ms(self, t=None): if t is not None: self._max_od = int(t) return self._max_od # Low priority versions of call_later() call_later_ms() and call_at_() def call_after_ms(self, delay, callback, *args): self.call_at_lp_(time.ticks_add(self.time(), delay), callback, *args) def call_after(self, delay, callback, *args): self.call_at_lp_(time.ticks_add(self.time(), int(delay * 1000)), callback, *args) def call_at_lp_(self, time, callback, *args): if self.lpq is not None: self.lpq.push(time, callback, args) if isinstance(callback, type_gen): callback.pend_throw(id(callback)) else: raise OSError('No low priority queue exists.') def call_soon(self, callback, *args): if __debug__ and DEBUG: log.debug("Scheduling in runq: %s", (callback, args)) self.runq.append(callback) if not isinstance(callback, type_gen): self.runq.append(args) def call_later(self, delay, callback, *args): self.call_at_(time.ticks_add(self.time(), int(delay * 1000)), callback, args) def call_later_ms(self, delay, callback, *args): if not delay: return self.call_soon(callback, *args) self.call_at_(time.ticks_add(self.time(), delay), callback, args) def call_at_(self, time, callback, args=()): if __debug__ and DEBUG: log.debug("Scheduling in waitq: %s", (time, callback, args)) self.waitq.push(time, callback, args) if isinstance(callback, type_gen): callback.pend_throw(id(callback)) def wait(self, delay): # Default wait implementation, to be overriden in subclasses # with IO scheduling if __debug__ and DEBUG: log.debug("Sleeping for: %s", delay) time.sleep_ms(delay) def run_forever(self): cur_task = [0, 0, 0] # Put a task on the runq unless it was cancelled def runq_add(): if isinstance(cur_task[1], type_gen): tid = id(cur_task[1]) if tid in self.canned: self.canned.remove(tid) else: cur_task[1].pend_throw(None) self.call_soon(cur_task[1], *cur_task[2]) else: self.call_soon(cur_task[1], *cur_task[2]) while True: # Expire entries in waitq and move them to runq tnow = self.time() if self.lpq: # Schedule a LP task if overdue or if no normal task is ready to_run = False # Assume no LP task is to run t = self.lpq.peektime() tim = time.ticks_diff(t, tnow) to_run = self._max_od > 0 and tim < -self._max_od if not (to_run or self.runq): # No overdue LP task or task on runq # zero delay tasks go straight to runq. So don't schedule LP if runq to_run = tim <= 0 # True if LP task is due if to_run and self.waitq: # Set False if normal tasks due. t = self.waitq.peektime() to_run = time.ticks_diff(t, tnow) > 0 # No normal task is ready if to_run: self.lpq.pop(cur_task) runq_add() while self.waitq: t = self.waitq.peektime() delay = time.ticks_diff(t, tnow) if delay > 0: break self.waitq.pop(cur_task) if __debug__ and DEBUG: log.debug("Moving from waitq to runq: %s", cur_task[1]) runq_add() # Process runq. This can append tasks to the end of .runq so get initial # length so we only process those items on the queue at the start. l = len(self.runq) if __debug__ and DEBUG: log.debug("Entries in runq: %d", l) cur_q = self.runq # Default: always get tasks from runq dl = 1 # Subtract this from entry count l while l or self.ioq_len: if self.ioq_len: # Using fast_io self.wait(0) # Schedule I/O. Can append to ioq. if self.ioq: cur_q = self.ioq dl = 0 # No effect on l elif l == 0: break # Both queues are empty else: cur_q = self.runq dl = 1 l -= dl cb = cur_q.popleft() # Remove most current task args = () if not isinstance(cb, type_gen): # It's a callback not a generator so get args args = cur_q.popleft() l -= dl if __debug__ and DEBUG: log.info("Next callback to run: %s", (cb, args)) cb(*args) # Call it continue # Proceed to next runq entry if __debug__ and DEBUG: log.info("Next coroutine to run: %s", (cb, args)) self.cur_task = cb # Stored in a bound variable for TimeoutObj delay = 0 low_priority = False # Assume normal priority try: if args is (): ret = next(cb) # Schedule the coro, get result else: ret = cb.send(*args) if __debug__ and DEBUG: log.info("Coroutine %s yield result: %s", cb, ret) if isinstance(ret, SysCall1): # Coro returned a SysCall1: an object with an arg spcified in its constructor arg = ret.arg if isinstance(ret, SleepMs): delay = arg if isinstance(ret, AfterMs): low_priority = True if isinstance(ret, After): delay = int(delay*1000) elif isinstance(ret, IORead): # coro was a StreamReader read method cb.pend_throw(False) # Marks the task as waiting on I/O for cancellation/timeout # If task is cancelled or times out, it is put on runq to process exception. # Debug note: if task is scheduled other than by wait (which does pend_throw(None) # an exception (exception doesn't inherit from Exception) is thrown self.add_reader(arg, cb) # Set up select.poll for read and store the coro in object map continue # Don't reschedule. Coro is scheduled by wait() when poll indicates h/w ready elif isinstance(ret, IOWrite): # coro was StreamWriter.awrite. Above comments apply. cb.pend_throw(False) self.add_writer(arg, cb) continue elif isinstance(ret, IOReadDone): # update select.poll registration and if necessary remove coro from map self.remove_reader(arg) self._call_io(cb, args) # Next call produces StopIteration enabling result to be returned continue elif isinstance(ret, IOWriteDone): self.remove_writer(arg) self._call_io(cb, args) # Next call produces StopIteration: see StreamWriter.aclose continue elif isinstance(ret, StopLoop): # e.g. from run_until_complete. run_forever() terminates return arg else: assert False, "Unknown syscall yielded: %r (of type %r)" % (ret, type(ret)) elif isinstance(ret, type_gen): # coro has yielded a coro (or generator) self.call_soon(ret) # append to .runq elif isinstance(ret, int): # If coro issued yield N, delay = N ms delay = ret elif ret is None: # coro issued yield. delay == 0 so code below will put the current task back on runq pass elif ret is False: # yield False causes coro not to be rescheduled i.e. it stops. continue else: assert False, "Unsupported coroutine yield value: %r (of type %r)" % (ret, type(ret)) except StopIteration as e: if __debug__ and DEBUG: log.debug("Coroutine finished: %s", cb) continue except CancelledError as e: if __debug__ and DEBUG: log.debug("Coroutine cancelled: %s", cb) continue # Currently all syscalls don't return anything, so we don't # need to feed anything to the next invocation of coroutine. # If that changes, need to pass that value below. if low_priority: self.call_after_ms(delay, cb) # Put on lpq elif delay: self.call_later_ms(delay, cb) else: self.call_soon(cb) # Wait until next waitq task or I/O availability delay = 0 if not self.runq: delay = -1 if self.waitq: tnow = self.time() t = self.waitq.peektime() delay = time.ticks_diff(t, tnow) if delay < 0: delay = 0 if self.lpq: t = self.lpq.peektime() lpdelay = time.ticks_diff(t, tnow) if lpdelay < 0: lpdelay = 0 if lpdelay < delay or delay < 0: delay = lpdelay # waitq is empty or lp task is more current self.wait(delay) def run_until_complete(self, coro): assert not isinstance(coro, type_genf), 'Coroutine arg expected.' # upy issue #3241 def _run_and_stop(): ret = yield from coro # https://github.com/micropython/micropython-lib/pull/270 yield StopLoop(ret) self.call_soon(_run_and_stop()) return self.run_forever() def stop(self): self.call_soon((lambda: (yield StopLoop(0)))()) def close(self): pass class SysCall: def __init__(self, *args): self.args = args def handle(self): raise NotImplementedError # Optimized syscall with 1 arg class SysCall1(SysCall): def __init__(self, arg): self.arg = arg class StopLoop(SysCall1): pass class IORead(SysCall1): pass class IOWrite(SysCall1): pass class IOReadDone(SysCall1): pass class IOWriteDone(SysCall1): pass _event_loop = None _event_loop_class = EventLoop def get_event_loop(runq_len=16, waitq_len=16, ioq_len=0, lp_len=0): global _event_loop if _event_loop is None: _event_loop = _event_loop_class(runq_len, waitq_len, ioq_len, lp_len) return _event_loop # Allow user classes to determine prior event loop instantiation. def get_running_loop(): if _event_loop is None: raise RuntimeError('Event loop not instantiated') return _event_loop def got_event_loop(): # Kept to avoid breaking code return _event_loop is not None def sleep(secs): yield int(secs * 1000) # Implementation of sleep_ms awaitable with zero heap memory usage class SleepMs(SysCall1): def __init__(self): self.v = None self.arg = None def __call__(self, arg): self.v = arg #print("__call__") return self def __iter__(self): #print("__iter__") return self def __next__(self): if self.v is not None: #print("__next__ syscall enter") self.arg = self.v self.v = None return self #print("__next__ syscall exit") _stop_iter.__traceback__ = None raise _stop_iter _stop_iter = StopIteration() sleep_ms = SleepMs() def cancel(coro): prev = coro.pend_throw(CancelledError()) if prev is False: # Waiting on I/O. Not on q so put it there. _event_loop._call_io(coro) elif isinstance(prev, int): # On waitq or lpq # task id _event_loop.canned.add(prev) # Alas this allocates _event_loop._call_io(coro) # Put on runq/ioq else: assert prev is None class TimeoutObj: def __init__(self, coro): self.coro = coro def wait_for_ms(coro, timeout): def waiter(coro, timeout_obj): res = yield from coro if __debug__ and DEBUG: log.debug("waiter: cancelling %s", timeout_obj) timeout_obj.coro = None return res def timeout_func(timeout_obj): if timeout_obj.coro: if __debug__ and DEBUG: log.debug("timeout_func: cancelling %s", timeout_obj.coro) prev = timeout_obj.coro.pend_throw(TimeoutError()) if prev is False: # Waiting on I/O _event_loop._call_io(timeout_obj.coro) elif isinstance(prev, int): # On waitq or lpq # prev==task id _event_loop.canned.add(prev) # Alas this allocates _event_loop._call_io(timeout_obj.coro) # Put on runq/ioq else: assert prev is None timeout_obj = TimeoutObj(_event_loop.cur_task) _event_loop.call_later_ms(timeout, timeout_func, timeout_obj) return (yield from waiter(coro, timeout_obj)) def wait_for(coro, timeout): return wait_for_ms(coro, int(timeout * 1000)) def coroutine(f): return f # Low priority class AfterMs(SleepMs): pass class After(AfterMs): pass after_ms = AfterMs() after = After() # # The functions below are deprecated in uasyncio, and provided only # for compatibility with CPython asyncio # def ensure_future(coro, loop=_event_loop): _event_loop.call_soon(coro) # CPython asyncio incompatibility: we don't return Task object return coro # CPython asyncio incompatibility: Task is a function, not a class (for efficiency) def Task(coro, loop=_event_loop): # Same as async() _event_loop.call_soon(coro)
37.095032
130
0.556623
97c80505f26c630f80edd6e36be8433347786cc5
344
py
Python
setup.py
marcelogomess/glpi_api
395c913de5d7c8add74973eca0e232041606c224
[ "BSD-2-Clause" ]
null
null
null
setup.py
marcelogomess/glpi_api
395c913de5d7c8add74973eca0e232041606c224
[ "BSD-2-Clause" ]
null
null
null
setup.py
marcelogomess/glpi_api
395c913de5d7c8add74973eca0e232041606c224
[ "BSD-2-Clause" ]
null
null
null
from distutils.core import setup setup( name='glpi_api', version='0.0.1', packages=['requests'], url='https://github.com/marcelogomess/glpi_api.git', license='BSD 2', author='marcelogomess', author_email='celo.gomess@gmail.com', description='Just a app to start with glpi api communitacion. glpi-project.org' )
26.461538
83
0.686047
417fd1524c308419afcf07cfce29d03273fc209d
1,558
py
Python
backend/model/migrate/versions/4ac191f72d8_.py
deti/boss
bc0cfe3067bf1cbf26789f7443a36e7cdd2ac869
[ "Apache-2.0" ]
7
2018-05-20T08:56:08.000Z
2022-03-11T15:50:54.000Z
backend/model/migrate/versions/4ac191f72d8_.py
deti/boss
bc0cfe3067bf1cbf26789f7443a36e7cdd2ac869
[ "Apache-2.0" ]
2
2021-06-08T21:12:51.000Z
2022-01-13T01:25:27.000Z
backend/model/migrate/versions/4ac191f72d8_.py
deti/boss
bc0cfe3067bf1cbf26789f7443a36e7cdd2ac869
[ "Apache-2.0" ]
5
2016-10-09T14:52:09.000Z
2020-12-25T01:04:35.000Z
"""Change primary to unique constraint Revision ID: 4ac191f72d8 Revises: 2baf554c632 Create Date: 2015-07-29 22:20:58.116493 """ # revision identifiers, used by Alembic. revision = '4ac191f72d8' down_revision = '2baf554c632' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql def upgrade(engine_name): globals()["upgrade_%s" % engine_name]() def downgrade(engine_name): globals()["downgrade_%s" % engine_name]() def upgrade_account(): ### commands auto generated by Alembic - please adjust! ### op.execute("ALTER TABLE service_usage DROP PRIMARY KEY") op.execute("ALTER TABLE service_usage ADD service_usage_id INT NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY(service_usage_id)") op.alter_column('service_usage', 'resource_id', existing_type=mysql.VARCHAR(length=100), nullable=False) op.create_unique_constraint(None, 'service_usage', ['tenant_id', 'service_id', 'time_label', 'resource_id']) ### end Alembic commands ### def downgrade_account(): ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'service_usage', type_='unique') op.alter_column('service_usage', 'resource_id', existing_type=mysql.VARCHAR(length=100), nullable=True) op.drop_column('service_usage', 'service_usage_id') # TODO create composite primary key ### end Alembic commands ### def upgrade_fitter(): pass def downgrade_fitter(): pass
25.129032
127
0.70475
f8175a901299c04e915fcf6d51f547f2f21811e3
3,813
py
Python
identity_provider/api.py
PSauerborn/monty
9c0a1097b243803bdf37ca5dbc03983d3d4e77c0
[ "MIT" ]
2
2020-09-12T13:25:04.000Z
2021-09-04T06:53:09.000Z
identity_provider/api.py
PSauerborn/monty
9c0a1097b243803bdf37ca5dbc03983d3d4e77c0
[ "MIT" ]
null
null
null
identity_provider/api.py
PSauerborn/monty
9c0a1097b243803bdf37ca5dbc03983d3d4e77c0
[ "MIT" ]
null
null
null
"""Module containing API functions""" import logging import json from bottle import Bottle, request, response, abort from config import LISTEN_ADDRESS, LISTEN_PORT from data_models import dataclass_response, extract_request_body, HTTPResponse, NewUserRequest, \ TokenRequest from persistence import create_new_user from helpers import email_in_use, username_in_use, is_authenticated_user from token_helpers import generate_jwt LOGGER = logging.getLogger(__name__) def custom_error(error_details: str) -> dict: # pragma: no cover """Function used as custom error handler when uncaught exceptions are raised""" LOGGER.debug(error_details) # extract HTTP code and message from request body code, message = response.status_code, response.body response.content_type = 'application/json' return json.dumps({'success': False, 'http_code': code, 'message': message}) def cors(func: object) -> object: # pragma: no cover """Decorator used to apply CORS policy to a particular route. [GET, POST, PATCH, PUT, DELETE, OPTIONS] are all currently valid requests methods""" def wrapper(*args: tuple, **kwargs: dict) -> object: if 'Origin' in request.headers: response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] else: response.headers['Access-Control-Allow-Origin'] = '*' # set allowed methods and headers response.set_header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS") response.set_header("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization, X-Authenticated-Userid") if request.method == 'OPTIONS': return return func(*args, **kwargs) return wrapper APP = Bottle() APP.default_error_handler = custom_error @APP.route('/authenticate/health', method=['GET', 'OPTIONS']) @cors @dataclass_response def health_check() -> HTTPResponse: """API route used to perform a health check operation Returns: HTTPResponse object contianing success message """ return HTTPResponse(success=True, http_code=200, message='api running') @APP.route('/authenticate/token', method=['POST', 'OPTIONS']) @cors @extract_request_body(TokenRequest, source='json', raise_on_error=True) @dataclass_response def get_token(body: TokenRequest) -> HTTPResponse: """API route used to perform a health check operation Returns: HTTPResponse object contianing success message """ if not is_authenticated_user(body.uid, body.password): LOGGER.warning('received unauthorized request from user %s', body.uid) abort(400, 'invalid username or password') LOGGER.debug('successfully authenticated user %s', body.uid) token = generate_jwt(body.uid) return HTTPResponse(success=True, http_code=200, payload={'token': token.decode()}) @APP.route('/authenticate/signup', method=['POST', 'OPTIONS']) @cors @extract_request_body(NewUserRequest, source='json', raise_on_error=True) @dataclass_response def create_user(body: NewUserRequest) -> HTTPResponse: """API route used to perform a health check operation Returns: HTTPResponse object contianing success message """ if email_in_use(body.email): LOGGER.error('email %s already in use', body.email) abort(400, 'email already in use') if username_in_use(body.uid): LOGGER.error('uid %s already in use', body.uid) abort(400, 'username already in use') LOGGER.debug('create new user %s', body.uid) user_id = create_new_user(body.uid, body.password, body.email) return HTTPResponse(success=True, http_code=200, payload={'userId': user_id}) if __name__ == '__main__': APP.run(host=LISTEN_ADDRESS, port=LISTEN_PORT, server='waitress')
36.663462
122
0.713611
275258e32c158aba11479dccbc2edde11606786b
5,577
py
Python
elecsus/tests/fitting_tests.py
fsponciano/ElecSus
c79444edb18154906caddf438c7e33b02865fa66
[ "Apache-2.0" ]
22
2016-07-11T15:25:18.000Z
2021-10-04T08:16:33.000Z
elecsus/tests/fitting_tests.py
Quantum-Light-and-Matter/ElecSus
c79444edb18154906caddf438c7e33b02865fa66
[ "Apache-2.0" ]
8
2019-08-12T09:46:21.000Z
2021-07-29T09:01:10.000Z
elecsus/tests/fitting_tests.py
Quantum-Light-and-Matter/ElecSus
c79444edb18154906caddf438c7e33b02865fa66
[ "Apache-2.0" ]
20
2016-06-09T14:35:14.000Z
2021-09-30T13:43:46.000Z
""" Series of tests and example code to run elecsus via the API Last updated 2018-07-04 MAZ """ # py 2.7 compatibility from __future__ import (division, print_function, absolute_import) import matplotlib.pyplot as plt import numpy as np import time import sys sys.path.append('../') import elecsus_methods as EM sys.path.append('../libs') from spectra import get_spectra def test_MLfit(): """ Test simple Marquart-Levenburg fit for S1 spectrum. Generate a data set and add random noise, then run an ML fit to the noisy data set, with randomised initial parameters that are the correct ones plus some small change """ p_dict = {'Elem':'Rb','Dline':'D2','T':80.,'lcell':2e-3,'Bfield':600.,'Btheta':0., 'Bphi':0.,'GammaBuf':0.,'shift':0.} p_dict_guess = p_dict # only need to specify parameters that are varied p_dict_bools = {'T':True,'Bfield':True} E_in = np.sqrt(1./2) * np.array([1.,1.,0]) # need to express E_in as Ex, Ey and phase difference for fitting E_in_angle = [E_in[0].real,[abs(E_in[1]),np.angle(E_in[1])]] # Generate spectrum and add some random noise x = np.linspace(-10000,10000,300) [y] = get_spectra(x,E_in,p_dict,outputs=['S1']) + np.random.randn(len(x))*0.01 # randomise the starting parameters a little p_dict_guess = p_dict p_dict_guess['T'] += np.random.randn()*1 p_dict_guess['Bfield'] += np.random.randn()*10 data = [x,y.real] best_params, RMS, result = EM.fit_data(data, p_dict_guess, p_dict_bools, E_in=E_in_angle, data_type='S1',fit_algorithm='ML') report = result.fit_report() fit = result.best_fit print(report) plt.plot(x,y,'k.',label='Data') plt.plot(x,fit,'r-',lw=2,label='Fit') plt.legend(loc=0) plt.show() def compare_fit_methods(): """ Compare ML and RR, SA and differential_evolution (DE) fitting for a more complicated case where there is a chi-squared local minimum in parameter space. In this case, the simple ML fit doesn't work, since it gets stuck in a very bad local minimum. The RR, SA and DE methods all converge to a good solution, but in different times. The RR fit takes somewhere in the region of 50x longer than ML, but produces a much better fit. The SA fit takes somewhere in the region of 100x longer than ML, but produces a much better fit. The DE fit takes somewhere in the region of 20x longer than ML, but produces a much better fit. From this test (and others which are broadly similar but for different data sets), we see that for global minimisation, we recommend using DE """ p_dict = {'Elem':'Rb','Dline':'D2','T':100.,'lcell':5e-3,'Bfield':7000.,'Btheta':0., 'Bphi':0.,'GammaBuf':50,'shift':0.} # only need to specify parameters that are varied p_dict_bools = {'T':True,'Bfield':True,'GammaBuf':True}#,'E_x':True,'E_y':True,'E_phase':True} E_in = np.array([0.7,0.7,0]) # need to express E_in as Ex, Ey and phase difference for fitting E_in_angle = [E_in[0].real,[abs(E_in[1]),np.angle(E_in[1])]] x = np.linspace(-21000,-13000,300) y = get_spectra(x,E_in,p_dict,outputs=['S0'])[0] + np.random.randn(len(x))*0.01 # <<< RMS error should be around 0.01 for the best case fit data = [x,y.real] # start at not the optimal parameters (near a local minimum in chi-squared) p_dict['T'] = 90 p_dict['Bfield'] = 6100 p_dict['GammaBuf'] = 150 p_dict_bounds = {} # time it... st_ML = time.time() best_paramsML, RMS_ML, resultML = EM.fit_data(data, p_dict, p_dict_bools, E_in=E_in_angle, data_type='S0') et_ML = time.time() -st_ML print('ML complete') # RR and SA need range over which to search p_dict_bounds['T'] = [30] p_dict_bounds['Bfield'] = [3000] p_dict_bounds['GammaBuf'] = [150] st_RR = time.time() best_paramsRR, RMS_RR, resultRR = EM.fit_data(data, p_dict, p_dict_bools, E_in=E_in_angle, p_dict_bounds=p_dict_bounds, data_type='S0', fit_algorithm='RR') et_RR = time.time() - st_RR print('RR complete') st_SA = time.time() best_paramsSA, RMS_SA, resultSA = EM.fit_data(data, p_dict, p_dict_bools, E_in=E_in_angle, p_dict_bounds=p_dict_bounds, data_type='S0', fit_algorithm='SA') et_SA = time.time() - st_SA print('SA complete') # differential evolution needs upper and lower bounds on fit parameters p_dict_bounds['T'] = [70,130] p_dict_bounds['Bfield'] = [4000,8000] p_dict_bounds['GammaBuf'] = [0, 100] st_DE = time.time() best_paramsDE, RMS_DE, resultDE = EM.fit_data(data, p_dict, p_dict_bools, E_in=E_in_angle, p_dict_bounds=p_dict_bounds, data_type='S0', fit_algorithm='differential_evolution') et_DE = time.time() - st_DE print('DE complete') print(('ML found best params in ', et_ML, 'seconds. RMS error, ', RMS_ML)) print(('RR found best params in ', et_RR, 'seconds. RMS error, ', RMS_RR)) print(('SA found best params in ', et_SA, 'seconds. RMS error, ', RMS_SA)) print(('DE found best params in ', et_DE, 'seconds. RMS error, ', RMS_DE)) reportML = resultML.fit_report() fitML = resultML.best_fit reportRR = resultRR.fit_report() fitRR = resultRR.best_fit reportSA = resultSA.fit_report() fitSA = resultSA.best_fit reportDE = resultDE.fit_report() fitDE = resultDE.best_fit #print '\n ML fit report:' #print reportML #print '\n DE fit report:' #print reportDE plt.plot(x,y,'k.',label='Data') plt.plot(x,fitML,'-',lw=2,label='ML fit') plt.plot(x,fitDE,'-',lw=2,label='RR fit') plt.plot(x,fitDE,'--',lw=2,label='SA fit') plt.plot(x,fitDE,':',lw=2,label='DE fit') plt.legend(loc=0) plt.show() if __name__ == '__main__': compare_fit_methods()
34.214724
153
0.69177
bd03bfb1cdb326b40ef4fd6c8c424f9065594e49
1,307
py
Python
src/experiment/run_exp.py
nilax97/DL-Sys-Perf-Project
bb6d2e8587272e37903f0f7e30ba38f98690c899
[ "MIT" ]
null
null
null
src/experiment/run_exp.py
nilax97/DL-Sys-Perf-Project
bb6d2e8587272e37903f0f7e30ba38f98690c899
[ "MIT" ]
1
2022-02-09T23:43:36.000Z
2022-02-09T23:43:36.000Z
src/experiment/run_exp.py
nilax97/DL-Sys-Perf-Project
bb6d2e8587272e37903f0f7e30ba38f98690c899
[ "MIT" ]
null
null
null
import os import pickle import numpy as np from experiment.create_config import get_params from experiment.ranges import get_ranges from experiment.create_config import create_base_params,create_config from experiment.utils import run_model def run_experiment(model_type,folder): if not os.path.exists(folder): print("Pickle path not found") return params = get_params(get_ranges()[model_type]) for key in params: base_param = create_base_params(params) for value in params[key]: print(f'[{model_type}] Running {key} : {value}') filename = f'{folder}/{model_type}/{model_type}-{key}-{value}.pickle' if os.path.exists(filename): with open(filename, 'rb') as handle: output_config = pickle.load(handle) print("Training time :",np.round(np.mean(output_config['train_times']),3),"seconds") continue base_param[key] = value output_config = run_model(create_config()[model_type](base_param),model_type) print("Training time :",np.round(np.mean(output_config['train_times']),3),"seconds") with open(filename, 'wb') as handle: pickle.dump(output_config, handle, protocol=pickle.HIGHEST_PROTOCOL)
42.16129
104
0.6557
c2f2079c858435a8db576319ee725dbab1c86d9e
16,051
py
Python
bot/exts/evergreen/battleship.py
imranshaji7/sir-lancebot
67caea1f737f86c2394cc9a280acbfe71588c917
[ "MIT" ]
1
2021-08-31T12:52:15.000Z
2021-08-31T12:52:15.000Z
bot/exts/evergreen/battleship.py
imranshaji7/sir-lancebot
67caea1f737f86c2394cc9a280acbfe71588c917
[ "MIT" ]
null
null
null
bot/exts/evergreen/battleship.py
imranshaji7/sir-lancebot
67caea1f737f86c2394cc9a280acbfe71588c917
[ "MIT" ]
null
null
null
import asyncio import logging import random import re import typing from dataclasses import dataclass from functools import partial import discord from discord.ext import commands from bot.bot import Bot from bot.constants import Colours log = logging.getLogger(__name__) @dataclass class Square: """Each square on the battleship grid - if they contain a boat and if they've been aimed at.""" boat: typing.Optional[str] aimed: bool Grid = typing.List[typing.List[Square]] EmojiSet = typing.Dict[typing.Tuple[bool, bool], str] @dataclass class Player: """Each player in the game - their messages for the boards and their current grid.""" user: typing.Optional[discord.Member] board: typing.Optional[discord.Message] opponent_board: discord.Message grid: Grid # The name of the ship and its size SHIPS = { "Carrier": 5, "Battleship": 4, "Cruiser": 3, "Submarine": 3, "Destroyer": 2, } # For these two variables, the first boolean is whether the square is a ship (True) or not (False). # The second boolean is whether the player has aimed for that square (True) or not (False) # This is for the player's own board which shows the location of their own ships. SHIP_EMOJIS = { (True, True): ":fire:", (True, False): ":ship:", (False, True): ":anger:", (False, False): ":ocean:", } # This is for the opposing player's board which only shows aimed locations. HIDDEN_EMOJIS = { (True, True): ":red_circle:", (True, False): ":black_circle:", (False, True): ":white_circle:", (False, False): ":black_circle:", } # For the top row of the board LETTERS = ( ":stop_button::regional_indicator_a::regional_indicator_b::regional_indicator_c::regional_indicator_d:" ":regional_indicator_e::regional_indicator_f::regional_indicator_g::regional_indicator_h:" ":regional_indicator_i::regional_indicator_j:" ) # For the first column of the board NUMBERS = [ ":one:", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:", ":nine:", ":keycap_ten:", ] CROSS_EMOJI = "\u274e" HAND_RAISED_EMOJI = "\U0001f64b" class Game: """A Battleship Game.""" def __init__( self, bot: Bot, channel: discord.TextChannel, player1: discord.Member, player2: discord.Member ) -> None: self.bot = bot self.public_channel = channel self.p1 = Player(player1, None, None, self.generate_grid()) self.p2 = Player(player2, None, None, self.generate_grid()) self.gameover: bool = False self.turn: typing.Optional[discord.Member] = None self.next: typing.Optional[discord.Member] = None self.match: typing.Optional[typing.Match] = None self.surrender: bool = False self.setup_grids() @staticmethod def generate_grid() -> Grid: """Generates a grid by instantiating the Squares.""" return [[Square(None, False) for _ in range(10)] for _ in range(10)] @staticmethod def format_grid(player: Player, emojiset: EmojiSet) -> str: """ Gets and formats the grid as a list into a string to be output to the DM. Also adds the Letter and Number indexes. """ grid = [ [emojiset[bool(square.boat), square.aimed] for square in row] for row in player.grid ] rows = ["".join([number] + row) for number, row in zip(NUMBERS, grid)] return "\n".join([LETTERS] + rows) @staticmethod def get_square(grid: Grid, square: str) -> Square: """Grabs a square from a grid with an inputted key.""" index = ord(square[0].upper()) - ord("A") number = int(square[1:]) return grid[number-1][index] # -1 since lists are indexed from 0 async def game_over( self, *, winner: discord.Member, loser: discord.Member ) -> None: """Removes games from list of current games and announces to public chat.""" await self.public_channel.send(f"Game Over! {winner.mention} won against {loser.mention}") for player in (self.p1, self.p2): grid = self.format_grid(player, SHIP_EMOJIS) await self.public_channel.send(f"{player.user}'s Board:\n{grid}") @staticmethod def check_sink(grid: Grid, boat: str) -> bool: """Checks if all squares containing a given boat have sunk.""" return all(square.aimed for row in grid for square in row if square.boat == boat) @staticmethod def check_gameover(grid: Grid) -> bool: """Checks if all boats have been sunk.""" return all(square.aimed for row in grid for square in row if square.boat) def setup_grids(self) -> None: """Places the boats on the grids to initialise the game.""" for player in (self.p1, self.p2): for name, size in SHIPS.items(): while True: # Repeats if about to overwrite another boat ship_collision = False coords = [] coord1 = random.randint(0, 9) coord2 = random.randint(0, 10 - size) if random.choice((True, False)): # Vertical or Horizontal x, y = coord1, coord2 xincr, yincr = 0, 1 else: x, y = coord2, coord1 xincr, yincr = 1, 0 for i in range(size): new_x = x + (xincr * i) new_y = y + (yincr * i) if player.grid[new_x][new_y].boat: # Check if there's already a boat ship_collision = True break coords.append((new_x, new_y)) if not ship_collision: # If not overwriting any other boat spaces, break loop break for x, y in coords: player.grid[x][y].boat = name async def print_grids(self) -> None: """Prints grids to the DM channels.""" # Convert squares into Emoji boards = [ self.format_grid(player, emojiset) for emojiset in (HIDDEN_EMOJIS, SHIP_EMOJIS) for player in (self.p1, self.p2) ] locations = ( (self.p2, "opponent_board"), (self.p1, "opponent_board"), (self.p1, "board"), (self.p2, "board") ) for board, location in zip(boards, locations): player, attr = location if getattr(player, attr): await getattr(player, attr).edit(content=board) else: setattr(player, attr, await player.user.send(board)) def predicate(self, message: discord.Message) -> bool: """Predicate checking the message typed for each turn.""" if message.author == self.turn.user and message.channel == self.turn.user.dm_channel: if message.content.lower() == "surrender": self.surrender = True return True self.match = re.fullmatch("([A-J]|[a-j]) ?((10)|[1-9])", message.content.strip()) if not self.match: self.bot.loop.create_task(message.add_reaction(CROSS_EMOJI)) return bool(self.match) async def take_turn(self) -> typing.Optional[Square]: """Lets the player who's turn it is choose a square.""" square = None turn_message = await self.turn.user.send( "It's your turn! Type the square you want to fire at. Format it like this: A1\n" "Type `surrender` to give up." ) await self.next.user.send("Their turn", delete_after=3.0) while True: try: await self.bot.wait_for("message", check=self.predicate, timeout=60.0) except asyncio.TimeoutError: await self.turn.user.send("You took too long. Game over!") await self.next.user.send(f"{self.turn.user} took too long. Game over!") await self.public_channel.send( f"Game over! {self.turn.user.mention} timed out so {self.next.user.mention} wins!" ) self.gameover = True break else: if self.surrender: await self.next.user.send(f"{self.turn.user} surrendered. Game over!") await self.public_channel.send( f"Game over! {self.turn.user.mention} surrendered to {self.next.user.mention}!" ) self.gameover = True break square = self.get_square(self.next.grid, self.match.string) if square.aimed: await self.turn.user.send("You've already aimed at this square!", delete_after=3.0) else: break await turn_message.delete() return square async def hit(self, square: Square, alert_messages: typing.List[discord.Message]) -> None: """Occurs when a player successfully aims for a ship.""" await self.turn.user.send("Hit!", delete_after=3.0) alert_messages.append(await self.next.user.send("Hit!")) if self.check_sink(self.next.grid, square.boat): await self.turn.user.send(f"You've sunk their {square.boat} ship!", delete_after=3.0) alert_messages.append(await self.next.user.send(f"Oh no! Your {square.boat} ship sunk!")) if self.check_gameover(self.next.grid): await self.turn.user.send("You win!") await self.next.user.send("You lose!") self.gameover = True await self.game_over(winner=self.turn.user, loser=self.next.user) async def start_game(self) -> None: """Begins the game.""" await self.p1.user.send(f"You're playing battleship with {self.p2.user}.") await self.p2.user.send(f"You're playing battleship with {self.p1.user}.") alert_messages = [] self.turn = self.p1 self.next = self.p2 while True: await self.print_grids() if self.gameover: return square = await self.take_turn() if not square: return square.aimed = True for message in alert_messages: await message.delete() alert_messages = [] alert_messages.append(await self.next.user.send(f"{self.turn.user} aimed at {self.match.string}!")) if square.boat: await self.hit(square, alert_messages) if self.gameover: return else: await self.turn.user.send("Miss!", delete_after=3.0) alert_messages.append(await self.next.user.send("Miss!")) self.turn, self.next = self.next, self.turn class Battleship(commands.Cog): """Play the classic game Battleship!""" def __init__(self, bot: Bot) -> None: self.bot = bot self.games: typing.List[Game] = [] self.waiting: typing.List[discord.Member] = [] def predicate( self, ctx: commands.Context, announcement: discord.Message, reaction: discord.Reaction, user: discord.Member ) -> bool: """Predicate checking the criteria for the announcement message.""" if self.already_playing(ctx.author): # If they've joined a game since requesting a player 2 return True # Is dealt with later on if ( user.id not in (ctx.me.id, ctx.author.id) and str(reaction.emoji) == HAND_RAISED_EMOJI and reaction.message.id == announcement.id ): if self.already_playing(user): self.bot.loop.create_task(ctx.send(f"{user.mention} You're already playing a game!")) self.bot.loop.create_task(announcement.remove_reaction(reaction, user)) return False if user in self.waiting: self.bot.loop.create_task(ctx.send( f"{user.mention} Please cancel your game first before joining another one." )) self.bot.loop.create_task(announcement.remove_reaction(reaction, user)) return False return True if ( user.id == ctx.author.id and str(reaction.emoji) == CROSS_EMOJI and reaction.message.id == announcement.id ): return True return False def already_playing(self, player: discord.Member) -> bool: """Check if someone is already in a game.""" return any(player in (game.p1.user, game.p2.user) for game in self.games) @commands.group(invoke_without_command=True) @commands.guild_only() async def battleship(self, ctx: commands.Context) -> None: """ Play a game of Battleship with someone else! This will set up a message waiting for someone else to react and play along. The game takes place entirely in DMs. Make sure you have your DMs open so that the bot can message you. """ if self.already_playing(ctx.author): await ctx.send("You're already playing a game!") return if ctx.author in self.waiting: await ctx.send("You've already sent out a request for a player 2.") return announcement = await ctx.send( "**Battleship**: A new game is about to start!\n" f"Press {HAND_RAISED_EMOJI} to play against {ctx.author.mention}!\n" f"(Cancel the game with {CROSS_EMOJI}.)" ) self.waiting.append(ctx.author) await announcement.add_reaction(HAND_RAISED_EMOJI) await announcement.add_reaction(CROSS_EMOJI) try: reaction, user = await self.bot.wait_for( "reaction_add", check=partial(self.predicate, ctx, announcement), timeout=60.0 ) except asyncio.TimeoutError: self.waiting.remove(ctx.author) await announcement.delete() await ctx.send(f"{ctx.author.mention} Seems like there's no one here to play...") return if str(reaction.emoji) == CROSS_EMOJI: self.waiting.remove(ctx.author) await announcement.delete() await ctx.send(f"{ctx.author.mention} Game cancelled.") return await announcement.delete() self.waiting.remove(ctx.author) if self.already_playing(ctx.author): return game = Game(self.bot, ctx.channel, ctx.author, user) self.games.append(game) try: await game.start_game() self.games.remove(game) except discord.Forbidden: await ctx.send( f"{ctx.author.mention} {user.mention} " "Game failed. This is likely due to you not having your DMs open. Check and try again." ) self.games.remove(game) except Exception: # End the game in the event of an unforseen error so the players aren't stuck in a game await ctx.send(f"{ctx.author.mention} {user.mention} An error occurred. Game failed.") self.games.remove(game) raise @battleship.command(name="ships", aliases=("boats",)) async def battleship_ships(self, ctx: commands.Context) -> None: """Lists the ships that are found on the battleship grid.""" embed = discord.Embed(colour=Colours.blue) embed.add_field(name="Name", value="\n".join(SHIPS)) embed.add_field(name="Size", value="\n".join(str(size) for size in SHIPS.values())) await ctx.send(embed=embed) def setup(bot: Bot) -> None: """Load the Battleship Cog.""" bot.add_cog(Battleship(bot))
35.74833
111
0.581521
54004b674b456d2919a9660c30a39c30ecf04c16
1,842
py
Python
api/migrations/0003_auto_20180519_2341.py
hueyjj/MangoMountain
5b1df750d620a8967f48e41d5e38286b92ccfa93
[ "MIT" ]
null
null
null
api/migrations/0003_auto_20180519_2341.py
hueyjj/MangoMountain
5b1df750d620a8967f48e41d5e38286b92ccfa93
[ "MIT" ]
null
null
null
api/migrations/0003_auto_20180519_2341.py
hueyjj/MangoMountain
5b1df750d620a8967f48e41d5e38286b92ccfa93
[ "MIT" ]
null
null
null
# Generated by Django 2.0.5 on 2018-05-20 06:41 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20180517_2354'), ] operations = [ migrations.RemoveField( model_name='sectionlab', name='sectionlab', ), migrations.AddField( model_name='sectionlab', name='class_id', field=models.CharField(blank=True, max_length=999), ), migrations.AddField( model_name='sectionlab', name='enrollment', field=models.CharField(blank=True, max_length=999), ), migrations.AddField( model_name='sectionlab', name='instructor', field=models.CharField(blank=True, max_length=999), ), migrations.AddField( model_name='sectionlab', name='location', field=models.CharField(blank=True, max_length=999), ), migrations.AddField( model_name='sectionlab', name='status', field=models.CharField(blank=True, max_length=999), ), migrations.AddField( model_name='sectionlab', name='time', field=models.CharField(blank=True, max_length=999), ), migrations.AddField( model_name='sectionlab', name='wait', field=models.CharField(blank=True, max_length=999), ), migrations.AlterField( model_name='course', name='section_and_labs', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='api.SectionLab'), ), ]
31.220339
115
0.547774
a6b1a614d0c53dcd4cd0b8920ec79f5f103f1098
334
py
Python
src/utils/strings/streams.py
JoelLefkowitz/templ8
c377e9aeb24d9a4ffa6ffba08afc0e2da258ac3f
[ "MIT" ]
1
2021-08-03T17:33:24.000Z
2021-08-03T17:33:24.000Z
src/utils/strings/streams.py
JoelLefkowitz/templ8
c377e9aeb24d9a4ffa6ffba08afc0e2da258ac3f
[ "MIT" ]
null
null
null
src/utils/strings/streams.py
JoelLefkowitz/templ8
c377e9aeb24d9a4ffa6ffba08afc0e2da258ac3f
[ "MIT" ]
null
null
null
def indent_lines(string: str, indent: str) -> str: return indent + string.replace("\n", "\n" + indent) if string else "" def truncate_lines(string: str, limit: int) -> str: return "\n".join( [ line[:limit] + "..." if len(line) > limit else line for line in string.split("\n") ] )
27.833333
73
0.541916
6849d403cf6e333f2670b11fe6d4d27032d2905e
593
py
Python
scripts/quest/q20820s.py
Snewmy/swordie
ae01ed4ec0eb20a18730e8cd209eea0b84a8dd17
[ "MIT" ]
2
2020-04-15T03:16:07.000Z
2020-08-12T23:28:32.000Z
scripts/quest/q20820s.py
Snewmy/swordie
ae01ed4ec0eb20a18730e8cd209eea0b84a8dd17
[ "MIT" ]
null
null
null
scripts/quest/q20820s.py
Snewmy/swordie
ae01ed4ec0eb20a18730e8cd209eea0b84a8dd17
[ "MIT" ]
3
2020-08-25T06:55:25.000Z
2020-12-01T13:07:43.000Z
# Start of The City of Ereve KIMU = 1102004 sm.setSpeakerID(KIMU) sm.removeEscapeButton() sm.sendNext("Welcome to Ereve! This is the safest and most peaceful place in all of Maple World. " "Empress Cygnus keeps it nice all the time!\r\n" "You're #b#h ##k, right? Here to join the #p1064023# Knights. I'm your guide, #p" + str(KIMU) + "#. All the Noblesses in town come to me first!") sm.sendSay("You need to get over to the Knight's Orientation right away. They're getting started already. Follow me, okay?") sm.completeQuestNoRewards(parentID) sm.warp(130030100) # Knight Orientation Area
42.357143
145
0.74199
4903f2f6d28938c4bc3e0eb67787b41eb5d51052
5,137
py
Python
phase_1/Extracting_morgan.py
fgentile89/Deep-Docking-NonAutomated
cbde2df913f6f0e5e151cc0913e20f8443a788ed
[ "MIT" ]
21
2021-03-05T23:46:07.000Z
2022-03-26T09:23:09.000Z
phase_1/Extracting_morgan.py
fgentile89/Deep-Docking-NonAutomated
cbde2df913f6f0e5e151cc0913e20f8443a788ed
[ "MIT" ]
14
2021-04-07T11:03:28.000Z
2022-01-14T22:42:08.000Z
phase_1/Extracting_morgan.py
fgentile89/Deep-Docking-NonAutomated
cbde2df913f6f0e5e151cc0913e20f8443a788ed
[ "MIT" ]
9
2021-03-16T08:32:12.000Z
2022-02-10T02:03:29.000Z
# Reads the ids found in sampling and finds the corresponding morgan fingerprint import argparse import glob parser = argparse.ArgumentParser() parser.add_argument('-pt', '--protein_name', required=True, help='Name of the DD project') parser.add_argument('-fp', '--file_path', required=True, help='Path to the project directory, excluding project directory name') parser.add_argument('-it', '--n_iteration', required=True, help='Number of current iteration') parser.add_argument('-md', '--morgan_directory', required=True, help='Path to directory containing Morgan fingerprints for the database') parser.add_argument('-t_pos', '--tot_process', required=True, help='Number of CPUs to use for multiprocessing') io_args = parser.parse_args() import os from multiprocessing import Pool import time from contextlib import closing import numpy as np protein = io_args.protein_name file_path = io_args.file_path n_it = int(io_args.n_iteration) morgan_directory = io_args.morgan_directory tot_process = int(io_args.tot_process) def extract_morgan(file_name): train = {} test = {} valid = {} with open(file_path + '/' + protein + "/iteration_" + str(n_it) + "/train_set.txt", 'r') as ref: for line in ref: train[line.rstrip()] = 0 with open(file_path + '/' + protein + "/iteration_" + str(n_it) + "/valid_set.txt", 'r') as ref: for line in ref: valid[line.rstrip()] = 0 with open(file_path + '/' + protein + "/iteration_" + str(n_it) + "/test_set.txt", 'r') as ref: for line in ref: test[line.rstrip()] = 0 # for file_name in file_names: ref1 = open( file_path + '/' + protein + '/iteration_' + str(n_it) + '/morgan/' + 'train_' + file_name.split('/')[-1], 'w') ref2 = open( file_path + '/' + protein + '/iteration_' + str(n_it) + '/morgan/' + 'valid_' + file_name.split('/')[-1], 'w') ref3 = open(file_path + '/' + protein + '/iteration_' + str(n_it) + '/morgan/' + 'test_' + file_name.split('/')[-1], 'w') with open(file_name, 'r') as ref: flag = 0 for line in ref: tmpp = line.strip().split(',')[0] if tmpp in train.keys(): train[tmpp] += 1 fn = 1 if train[tmpp] == 1: flag = 1 elif tmpp in valid.keys(): valid[tmpp] += 1 fn = 2 if valid[tmpp] == 1: flag = 1 elif tmpp in test.keys(): test[tmpp] += 1 fn = 3 if test[tmpp] == 1: flag = 1 if flag == 1: if fn == 1: ref1.write(line) if fn == 2: ref2.write(line) if fn == 3: ref3.write(line) flag = 0 def alternate_concat(files): to_return = [] with open(files, 'r') as ref: for line in ref: to_return.append(line) return to_return def delete_all(files): os.remove(files) def morgan_duplicacy(f_name): flag = 0 mol_list = {} ref1 = open(f_name[:-4] + '_updated.csv', 'a') with open(f_name, 'r') as ref: for line in ref: tmpp = line.strip().split(',')[0] if tmpp not in mol_list: mol_list[tmpp] = 1 flag = 1 if flag == 1: ref1.write(line) flag = 0 os.remove(f_name) if __name__ == '__main__': try: os.mkdir(file_path + '/' + protein + '/iteration_' + str(n_it) + '/morgan') except: pass files = [] for f in glob.glob(morgan_directory + "/*.txt"): files.append(f) t = time.time() with closing(Pool(np.min([tot_process, len(files)]))) as pool: pool.map(extract_morgan, files) print(time.time() - t) all_to_delete = [] for type_to in ['train', 'valid', 'test']: t = time.time() files = [] for f in glob.glob(file_path + '/' + protein + '/iteration_' + str(n_it) + '/morgan/' + type_to + '*'): files.append(f) all_to_delete.append(f) print(len(files)) if len(files) == 0: print("Error in address above") break with closing(Pool(np.min([tot_process, len(files)]))) as pool: to_print = pool.map(alternate_concat, files) with open(file_path + '/' + protein + '/iteration_' + str(n_it) + '/morgan/' + type_to + '_morgan_1024.csv', 'w') as ref: for file_data in to_print: for line in file_data: ref.write(line) to_print = [] print(type_to, time.time() - t) f_names = [] for f in glob.glob(file_path + '/' + protein + '/iteration_' + str(n_it) + '/morgan/*morgan*'): f_names.append(f) t = time.time() with closing(Pool(np.min([tot_process, len(f_names)]))) as pool: pool.map(morgan_duplicacy, f_names) print(time.time() - t) with closing(Pool(np.min([tot_process, len(all_to_delete)]))) as pool: pool.map(delete_all, all_to_delete)
34.246667
137
0.553631
0c974cece4952a3761c7933ee950860c8ab2c3ed
8,483
py
Python
backupper/connect/ftpstorage.py
dolfinsbizou/backupper
f8f1047e880c802ba70bf6264a2e13ba604f8b1f
[ "MIT" ]
null
null
null
backupper/connect/ftpstorage.py
dolfinsbizou/backupper
f8f1047e880c802ba70bf6264a2e13ba604f8b1f
[ "MIT" ]
null
null
null
backupper/connect/ftpstorage.py
dolfinsbizou/backupper
f8f1047e880c802ba70bf6264a2e13ba604f8b1f
[ "MIT" ]
null
null
null
import os from ftplib import FTP from .utils import * _all_ = ["FTPStorage"] class FTPStorage(AbstractStorageContext): """ FTP storage system. A handy wrapper for ftplib.FTP methods. """ CONNEXION_TYPE = "ftp" def __init__(self, host, user="anonymous", passwd=""): if not host: raise ValueError("__init__: please provide a host.") self.host = host self.user = user self.passwd = passwd self._connection = None def connect(self): if not self._connection is None: raise AlreadyConnectedError("connect: you're already connected to {}.".format(self._connection.host)) # We use self._connection.host because the user could modify the host after the connection was opened try: self._connection = FTP(host=self.host) self._connection.login(user=self.user, passwd=self.passwd) except Exception as e: if not self._connection is None: self._connection.close() raise UnableToConnectError("connect: FTP module returned an error ({}).".format(e)) def disconnect(self): if self._connection is None: raise NotConnectedError("disconnect: you're not connected to {}.".format(self.host)) try: self._connection.quit() except: self._connection.close() finally: self._connection = None def upload(self, src, dest="."): if self._connection is None: raise NotConnectedError("upload: you're not connected to {}.".format(self.host)) dest_filename = "" try: dest_files = self.listdir(dest) if not self.isdir(dest): raise UnpermittedOperationError("upload: {} is a file.".format(dest)) if os.path.basename(src) in dest_files: raise UnpermittedOperationError("upload: {} already exists.".format(src)) dest_filename = os.path.basename(src) except NotFoundError as e: try: dest, dest_filename = os.path.split(dest) self.listdir(dest) if not self.isdir(dest): raise UnpermittedOperationError("upload: {} is a file.".format(os.path.normpath(dest))) except NotFoundError: raise NotFoundError("upload: {} doesn't exist.".format(os.path.normpath(os.path.dirname(dest)))) if not os.path.exists(src): raise NotFoundError("upload: {} doesn't exist.".format(src)) try: if os.path.isdir(src): full_dest = os.path.join(dest, dest_filename) self._connection.mkd(full_dest) self._recursive_upload(src, full_dest) else: with open(src, "rb") as f: self._connection.storbinary('STOR {}'.format(os.path.join(dest, dest_filename)), f) except Exception as e: raise StorageError("upload: FTP module returned an error ({}).".format(e)) def _recursive_upload(self, current_file, dest): """ Internal recursive upload subroutine. When uploading a directory, recursively creates its structure. :param current_file: The directory to upload. :type current_file: str :param dest: Destination. :type dest: str """ files = os.listdir(current_file) for f in files: subfile = os.path.join(current_file, f) next_dest = os.path.join(dest, f) if os.path.isdir(subfile): self._connection.mkd(next_dest) self._recursive_upload(subfile, next_dest) else: with open(subfile, 'rb') as fp: self._connection.storbinary('STOR {}'.format(next_dest), fp) def download(self, src, dest="."): #TODO Implement me raise NotImplementedError("download: Method not implemented yet.") if self._connection is None: raise NotConnectedError("download: you're not connected to {}.".format(self.host)) try: pass except Exception as e: raise StorageError("download: FTP module returned an error ({}).".format(e)) def listdir(self, path="."): if self._connection is None: raise NotConnectedError("listdir: you're not connected to {}.".format(self.host)) last_path = self.getcwd() abs_path = os.path.normpath(os.path.join(last_path, path)) try: if not self.isdir(path): return [os.path.basename(path)] self.chdir(abs_path) result = [os.path.basename(f) for f in self._connection.nlst("-a") if not os.path.basename(f) in [".", "..", ""]] self.chdir(last_path) return result except NotFoundError as e: self.chdir(last_path) raise NotFoundError("listdir: FTP module returned an error ({}).".format(e)) except Exception as e: self.chdir(last_path) raise StorageError("listdir: FTP module returned an error ({}).".format(e)) def isdir(self, path): """ Tests if the path is an existing directory. :param path: File to test. :type path: str :return: True if the path is a directory. :rtype: bool """ if self._connection is None: raise NotConnectedError("isdir: you're not connected to {}.".format(self.host)) basename, filename = os.path.split(os.path.normpath(os.path.join(self.getcwd(), path))) files = {} # Case where our canonical path is the root if filename == "": return True try: list_log = [] old_cwd = self._connection.pwd() self._connection.cwd(basename) self._connection.dir("-a", list_log.append) self._connection.cwd(old_cwd) files = {' '.join(line.split()[8:]): line[0] for line in list_log} except Exception as e: raise StorageError("isdir: FTP module returned an error ({}).".format(e)) if not filename in files: raise NotFoundError("isdir: {} doesn't exist.".format(path)) return files[filename] == "d" def remove(self, path): if self._connection is None: raise NotConnectedError("remove: you're not connected to {}.".format(self.host)) try: if self.isdir(path): # TODO We should recursively delete the contents of path before removing the directory, otherwise we get an error raise NotImplementedError("remove: Directory deletion isn't implemented yet.") self._connection.rmd(path) else: self._connection.delete(path) except Exception as e: raise StorageError("remove: FTP module returned an error ({}).".format(e)) def _recursive_remove(self, current_file): """ TODO IMPLEMENT ME """ def mkdir(self, path): if self._connection is None: raise NotConnectedError("mkdir: you're not connected to {}.".format(self.host)) try: self._connection.mkd(path) except Exception as e: raise StorageError("mkdir: FTP module returned an error ({}).".format(e)) def rename(self, path, new_path): if self._connection is None: raise NotConnectedError("rename: you're not connected to {}.".format(self.host)) try: self._connection.rename(path, new_path) except Exception as e: raise StorageError("rename: FTP module returned an error ({}).".format(e)) def chdir(self, path="/"): if self._connection is None: raise NotConnectedError("chdir: you're not connected to {}.".format(self.host)) try: self._connection.cwd(path) except Exception as e: raise NotFoundError("chdir: FTP module returned an error ({}).".format(e)) def getcwd(self): if self._connection is None: raise NotConnectedError("getcwd: you're not connected to {}.".format(self.host)) try: return self._connection.pwd() except Exception as e: raise StorageError("getcwd: FTP module returned an error ({}).".format(e))
36.407725
215
0.583048
fcdb495602744fe6a676fd14096b50428889d3ee
14,242
py
Python
funcgen.py
thomaseichhorn/funcgen
8bd99012780e312ef6a9db6d5da2b3187496dab7
[ "MIT" ]
1
2021-01-20T21:26:49.000Z
2021-01-20T21:26:49.000Z
funcgen.py
thomaseichhorn/funcgen
8bd99012780e312ef6a9db6d5da2b3187496dab7
[ "MIT" ]
null
null
null
funcgen.py
thomaseichhorn/funcgen
8bd99012780e312ef6a9db6d5da2b3187496dab7
[ "MIT" ]
null
null
null
import sys, os, glob, serial import curses import time from jds6600 import jds6600 from math import * def draw_menu ( stdscr, theport ) : # Require minimum terminal size height, width = stdscr.getmaxyx ( ) if ( height < 24 or width < 80 ) : curses.endwin ( ) print ( "The required minimum terminal size is 80 columns by 24 rows!\nYour terminal is {} by {}!" .format ( width, height ) ) return -1 j = jds6600 ( theport ) # User input key k = 0 # Clear and refresh the screen for a blank canvas stdscr.clear ( ) stdscr.refresh ( ) # Start colors in curses curses.start_color ( ) curses.init_pair ( 1, curses.COLOR_YELLOW, curses.COLOR_BLACK ) curses.init_pair ( 2, curses.COLOR_CYAN, curses.COLOR_BLACK ) curses.init_pair ( 3, curses.COLOR_RED, curses.COLOR_BLACK ) curses.init_pair ( 4, curses.COLOR_BLACK, curses.COLOR_WHITE ) curses.init_pair ( 5, curses.COLOR_WHITE, curses.COLOR_BLACK ) # Refresh time in 1/10 sec curses.halfdelay ( 1 ) # The channel we are editing activechan = 1 # Loop where k is the last character pressed while ( k != ord ( 'q' ) ) : # Initialization stdscr.clear ( ) # Select SW active chan if ( k == ord ( '1' ) ) : activechan = 1 if ( k == ord ( '2' ) ) : activechan = 2 # Read device status_ch1 = "Indef" status_ch2 = "Indef" bool_ch1, bool_ch2 = j.getchannelenable ( ) # Chan on/off if ( k == ord ( 'o' ) or k == ord ( 'O' ) ) : if ( activechan == 1 ) : j.setchannelenable ( not bool_ch1, bool_ch2 ) if ( activechan == 2 ) : j.setchannelenable ( bool_ch1, not bool_ch2 ) stdscr.refresh ( ) if ( bool_ch1 == True ) : status_ch1 = "ON" else : status_ch1 = "OFF" if ( bool_ch2 == True ) : status_ch2 = "ON" else : status_ch2 = "OFF" #User input box position size_y_box = 6 size_x_box = 24 start_y_box = 17 if ( activechan == 1 ) : start_x_box = 4 else : start_x_box = 34 # Wave status_wave1 = j.getwaveform ( 1 ) status_wave2 = j.getwaveform ( 2 ) if ( k == ord ( 'w' ) or k == ord ( 'W' ) ) : waves = [ "Sine","Square","Pulse","Triangle","Partial Sine","CMOS","DC","Half-Wave","Full-Wave","Pos-Ladder","Neg-Ladder", "Noise", "Exp-Rise","Exp-Decay","Multi-Tone","Sinc","Lorenz" ] help_win = stdscr.subwin ( 21, 19, 2, 61 ) help_win.bkgd ( curses.color_pair ( 5 ) ) help_win.box ( ) help_win.addstr ( 1, 2, "Waveforms:" ) for i in range ( 0, 17, 1 ) : help_win.addstr ( i + 3, 2, "{}: {}". format ( i, waves[i] ) ) curses.echo ( ) help_win.refresh ( ) wave_win = stdscr.subwin ( size_y_box, size_x_box, start_y_box, start_x_box ) wave_win.bkgd ( curses.color_pair ( activechan ) ) wave_win.box ( ) wave_win.addstr ( 1, 2, "Waveform Channel {}:" .format ( activechan ) ) curses.echo ( ) wave_win.addstr ( 3, 2, "[#] : " ) wave_win.refresh ( ) waveinput = -1 input = wave_win.getstr ( 3, 8, 10 ) try : waveinput = int ( input ) except ValueError : wave_win.addstr ( 4, 2, "Invalid! W=[0..16]" ) wave_win.refresh ( ) if ( waveinput < 0 or waveinput > 16 ) : wave_win.addstr ( 4, 2, "Invalid! W=[0..16]" ) wave_win.refresh ( ) curses.napms ( 2500 ) del wave_win del help_win stdscr.refresh ( ) curses.halfdelay ( 1 ) else : j.setwaveform ( activechan, waveinput ) del wave_win del help_win stdscr.refresh ( ) curses.halfdelay ( 1 ) # Frequency status_freq1 = j.getfrequency ( 1 ) status_freq2 = j.getfrequency ( 2 ) freq_ch1_unit = "Hz" freq_ch2_unit = "Hz" if status_freq1 >= 10000.0 : status_freq1 = status_freq1 / 1000.0 freq_ch1_unit = "KHz" if status_freq1 >= 10000.0 : status_freq1 = status_freq1 / 1000.0 freq_ch1_unit = "MHz" if status_freq2 >= 10000.0 : status_freq2 = status_freq2 / 1000.0 freq_ch2_unit = "KHz" if status_freq2 >= 10000.0 : status_freq2 = status_freq2 / 1000.0 freq_ch2_unit = "MHz" if ( k == ord ( 'f' ) or k == ord ( 'F' ) ) : freq_win = stdscr.subwin ( size_y_box, size_x_box, start_y_box, start_x_box ) freq_win.bkgd ( curses.color_pair ( activechan ) ) freq_win.box ( ) freq_win.addstr ( 1, 2, "Frequency Channel {}:" .format ( activechan ) ) curses.echo ( ) freq_win.addstr ( 3, 2, "[Hz] : " ) freq_win.refresh ( ) freqinput = -1 input = freq_win.getstr ( 3, 9, 10 ) try : freqinput = float ( input ) except ValueError : freq_win.addstr ( 4, 2, "Invalid! F=[0..1.5e7]" ) freq_win.refresh ( ) # TODO: Check range! if ( freqinput < 0.0 or freqinput > 15000000 ) : freq_win.addstr ( 4, 2, "Invalid! F=[0..1.5e7]" ) freq_win.refresh ( ) curses.napms ( 2500 ) del freq_win stdscr.refresh ( ) curses.halfdelay ( 1 ) else : j.setfrequency ( activechan, freqinput, 0 ) del freq_win stdscr.refresh ( ) curses.halfdelay ( 1 ) # Amplitude status_amp1 = j.getamplitude ( 1 ) status_amp2 = j.getamplitude ( 2 ) if ( k == ord ( 'a' ) or k == ord ( 'A' ) ) : amp_win = stdscr.subwin ( size_y_box, size_x_box, start_y_box, start_x_box ) amp_win.bkgd ( curses.color_pair ( activechan ) ) amp_win.box ( ) amp_win.addstr ( 1, 2, "Amplitude Channel {}:" .format ( activechan ) ) curses.echo ( ) amp_win.addstr ( 3, 2, "[V] : " ) amp_win.refresh ( ) ampinput = -1 input = amp_win.getstr ( 3, 8, 10 ) try : ampinput = float ( input ) except ValueError : amp_win.addstr ( 4, 2, "Invalid! V=[0..20]" ) amp_win.refresh ( ) if ( ampinput < 0.0 or ampinput > 20.0 ) : amp_win.addstr ( 4, 2, "Invalid! V=[0..20]" ) amp_win.refresh ( ) curses.napms ( 2500 ) del amp_win stdscr.refresh ( ) curses.halfdelay ( 1 ) else : j.setamplitude ( activechan, ampinput ) del amp_win stdscr.refresh ( ) curses.halfdelay ( 1 ) # Offset status_offs1 = j.getoffset ( 1 ) status_offs2 = j.getoffset ( 2 ) if ( k == ord ( 's' ) or k == ord ( 'S' ) ) : offs_win = stdscr.subwin ( size_y_box, size_x_box, start_y_box, start_x_box ) offs_win.bkgd ( curses.color_pair ( activechan ) ) offs_win.box ( ) offs_win.addstr ( 1, 2, "Offset Channel {}:" .format ( activechan ) ) curses.echo ( ) offs_win.addstr ( 3, 2, "[V] : " ) offs_win.refresh ( ) offsinput = 0 input = offs_win.getstr ( 3, 8, 10 ) try : offsinput = float ( input ) except ValueError : offs_win.addstr ( 4, 2, "Invalid! V=[-9.99..9.99]" ) offs_win.refresh ( ) if ( offsinput < -9.99 or offsinput > 9.99 ) : offs_win.addstr ( 4, 2, "Invalid! V=[-9.99..9.99]" ) offs_win.refresh ( ) curses.napms ( 2500 ) del offs_win stdscr.refresh ( ) curses.halfdelay ( 1 ) else : j.setoffset ( activechan, offsinput ) del offs_win stdscr.refresh ( ) curses.halfdelay ( 1 ) # Duty cycle status_duty1 = j.getdutycycle ( 1 ) status_duty2 = j.getdutycycle ( 2 ) if ( k == ord ( 'd' ) or k == ord ( 'D' ) ) : duty_win = stdscr.subwin ( size_y_box, size_x_box, start_y_box, start_x_box ) duty_win.bkgd ( curses.color_pair ( activechan ) ) duty_win.box ( ) duty_win.addstr ( 1, 2, "Duty Cycle Channel {}:" .format ( activechan ) ) curses.echo ( ) duty_win.addstr ( 3, 2, "[%] : " ) duty_win.refresh ( ) dutyinput = 0 input = duty_win.getstr ( 3, 8, 10 ) try : dutyinput = float ( input ) except ValueError : duty_win.addstr ( 4, 2, "Invalid! %=[0..99.9]" ) duty_win.refresh ( ) if ( dutyinput < 0.9 or dutyinput > 99.9 ) : duty_win.addstr ( 4, 2, "Invalid! %=[0..99.9]" ) duty_win.refresh ( ) curses.napms ( 2500 ) del duty_win stdscr.refresh ( ) curses.halfdelay ( 1 ) else : j.setdutycycle ( activechan, dutyinput ) del duty_win stdscr.refresh ( ) curses.halfdelay ( 1 ) # Phase status_phase = j.getphase ( ) if ( k == ord ( 'p' ) or k == ord ( 'P' ) ) : # only on right side start_x_box = 34 phase_win = stdscr.subwin ( size_y_box, size_x_box, start_y_box, start_x_box ) phase_win.bkgd ( curses.color_pair ( 2 ) ) phase_win.box ( ) phase_win.addstr ( 1, 2, "Phase:" ) curses.echo ( ) phase_win.addstr ( 3, 2, "[Deg] : " ) phase_win.refresh ( ) phaseinput = 0 input = phase_win.getstr ( 3, 10, 10 ) try : phaseinput = float ( input ) except ValueError : phase_win.addstr ( 4, 2, "Invalid! P=[0..360]" ) phase_win.refresh ( ) if ( phaseinput < 0.0 or phaseinput > 360.0 ) : phase_win.addstr ( 4, 2, "Invalid! P=[0..360]" ) phase_win.refresh ( ) curses.napms ( 2500 ) del phase_win stdscr.refresh ( ) curses.halfdelay ( 1 ) else : j.setphase ( phaseinput ) del phase_win stdscr.refresh ( ) curses.halfdelay ( 1 ) # Common box strings title_str1 = "Channel" title_str3 = "utput" wave_str2 = "ave:" freq_str2 = "requency:" amp_str2 = "mplitude:" offset_str2 = "Off" offset_str3 = "et:" duty_str2 = "uty Cycle:" phase_str2= "hase:" # Chan 1 Box start_x_ch1 = 1 start_y_ch1 = 2 size_x_ch1 = 30 size_y_ch1 = 15 # Chan 2 Box start_x_ch2 = 31 start_y_ch2 = 2 size_x_ch2 = 30 size_y_ch2 = 15 # Draw Box 1 win_ch1 = stdscr.subwin ( size_y_ch1, size_x_ch1, start_y_ch1, start_x_ch1 ) win_ch1.bkgd ( curses.color_pair ( 1 ) ) win_ch1.box ( ) win_ch1.addstr ( 1, 2, title_str1 ) win_ch1.addstr ( 1, 10, "1", curses.A_UNDERLINE ) win_ch1.addstr ( 1, 11, ":" ) win_ch1.addstr ( 1, 16, "O", curses.A_UNDERLINE ) win_ch1.addstr ( 1, 17, title_str3 ) win_ch1.addstr ( 1, 24, status_ch1, curses.color_pair ( 3 ) ) win_ch1.addstr ( 3, 2, "W", curses.A_UNDERLINE ) win_ch1.addstr ( 3, 3, wave_str2 ) win_ch1.addstr ( 3, 16, "{} ".format ( status_wave1[1] ), curses.color_pair ( 3 ) ) win_ch1.addstr ( 5, 2, "F", curses.A_UNDERLINE ) win_ch1.addstr ( 5, 3, freq_str2 ) win_ch1.addstr ( 5, 16, "{0:.3f} ".format ( status_freq1 ), curses.color_pair ( 3 ) ) win_ch1.addstr ( 5, 25, freq_ch1_unit ) win_ch1.addstr ( 7, 2, "A", curses.A_UNDERLINE ) win_ch1.addstr ( 7, 3, amp_str2 ) win_ch1.addstr ( 7, 16, "{0:.3f} ".format ( status_amp1 ), curses.color_pair ( 3 ) ) win_ch1.addstr ( 7, 25, "V" ) win_ch1.addstr ( 9, 2, offset_str2 ) win_ch1.addstr ( 9, 5, "s", curses.A_UNDERLINE ) win_ch1.addstr ( 9, 6, offset_str3 ) win_ch1.addstr ( 9, 16, "{0:.2f} ".format ( status_offs1 ), curses.color_pair ( 3 ) ) win_ch1.addstr ( 9, 25, "V" ) win_ch1.addstr ( 11, 2, "D", curses.A_UNDERLINE ) win_ch1.addstr ( 11, 3, duty_str2 ) win_ch1.addstr ( 11, 16, "{0:.1f} ".format ( status_duty1 ), curses.color_pair ( 3 ) ) win_ch1.addstr ( 11, 25, "%" ) # Draw Box 2 win_ch2 = stdscr.subwin ( size_y_ch2, size_x_ch2, start_y_ch2, start_x_ch2 ) win_ch2.bkgd ( curses.color_pair ( 2 ) ) win_ch2.box ( ) win_ch2.addstr ( 1, 2, title_str1 ) win_ch2.addstr ( 1, 10, "2", curses.A_UNDERLINE ) win_ch2.addstr ( 1, 11, ":" ) win_ch2.addstr ( 1, 16, "O", curses.A_UNDERLINE ) win_ch2.addstr ( 1, 17, title_str3 ) win_ch2.addstr ( 1, 24, status_ch2, curses.color_pair ( 3 ) ) win_ch2.addstr ( 3, 2, "W", curses.A_UNDERLINE ) win_ch2.addstr ( 3, 3, wave_str2 ) win_ch2.addstr ( 3, 16, "{} ".format ( status_wave2[1] ), curses.color_pair ( 3 ) ) win_ch2.addstr ( 5, 2, "F", curses.A_UNDERLINE ) win_ch2.addstr ( 5, 3, freq_str2 ) win_ch2.addstr ( 5, 16, "{0:.3f} ".format ( status_freq2 ), curses.color_pair ( 3 ) ) win_ch2.addstr ( 5, 25, freq_ch2_unit ) win_ch2.addstr ( 7, 2, "A", curses.A_UNDERLINE ) win_ch2.addstr ( 7, 3, amp_str2 ) win_ch2.addstr ( 7, 16, "{0:.3f} ".format ( status_amp2 ), curses.color_pair ( 3 ) ) win_ch2.addstr ( 7, 25, "V" ) win_ch2.addstr ( 9, 2, offset_str2 ) win_ch2.addstr ( 9, 5, "s", curses.A_UNDERLINE ) win_ch2.addstr ( 9, 6, offset_str3 ) win_ch2.addstr ( 9, 16, "{0:.2f} ".format ( status_offs2 ), curses.color_pair ( 3 ) ) win_ch2.addstr ( 9, 25, "V" ) win_ch2.addstr ( 11, 2, "D", curses.A_UNDERLINE ) win_ch2.addstr ( 11, 3, duty_str2 ) win_ch2.addstr ( 11, 16, "{0:.1f} ".format ( status_duty2 ), curses.color_pair ( 3 ) ) win_ch2.addstr ( 11, 25, "%" ) win_ch2.addstr ( 13, 2, "P", curses.A_UNDERLINE ) win_ch2.addstr ( 13, 3, phase_str2 ) win_ch2.addstr ( 13, 16, "{0:.1f} ".format ( status_phase ), curses.color_pair ( 3 ) ) win_ch2.addstr ( 13, 25, "Deg" ) ## Declaration of strings topstatusstr = "Selected Channel: {} Connected to: {}" .format ( activechan, theport ) statusbarstr = "Press 'q' to exit | '1' or '2' selects channel" # Render top and status bar stdscr.attron ( curses.color_pair ( 4 ) ) stdscr.addstr ( 0, 0, topstatusstr ) stdscr.addstr ( 0, len ( topstatusstr ), " " * ( width - len ( topstatusstr ) - 1 ) ) stdscr.attroff ( curses.color_pair ( 4 ) ) stdscr.attron ( curses.color_pair ( 4 ) ) stdscr.addstr ( height - 1, 0, statusbarstr ) stdscr.addstr ( height - 1, len ( statusbarstr ), " " * ( width - len ( statusbarstr ) - 1 ) ) stdscr.attroff ( curses.color_pair ( 4 ) ) # Refresh the screen stdscr.refresh ( ) # Wait for next input k = stdscr.getch ( ) # Catch capital Q if k == ord ( 'Q' ) : k = ord ( 'q' ) def main ( ) : # Find available ports if sys.platform.startswith ( 'win' ) : ports = ['COM%s' % ( i + 1 ) for i in range ( 256 ) ] elif sys.platform.startswith ( 'linux' ) or sys.platform.startswith ( 'cygwin' ) : # Assume that we are connected via USB, for 'real' serial remove USB ports = glob.glob ( '/dev/ttyUSB*' ) elif sys.platform.startswith ( 'darwin' ) : # Dito ports = glob.glob ( '/dev/tty.usb*' ) else : raise EnvironmentError ( 'Unsupported platform!' ) # Check if port is a serial port result = [] for port in ports : try : s = serial.Serial ( port ) s.close ( ) result.append ( port ) except ( OSError, serial.SerialException ) : pass # If none found if not result : print ( "No device found!" ) return -1 # Find our device for res in result : print ( "Trying {}" .format ( res ) ) try: j = jds6600 ( res ) theport = res except : pass # Start curses curses.wrapper ( draw_menu, theport ) if __name__ == "__main__" : main ( ) #
30.562232
188
0.613678
c1161d4e68a1c1c9f8e577c79a429a8bf650d2d9
9,411
py
Python
src/pythae/models/nn/default_architectures.py
clementchadebec/benchmark_VAE
943e231f9e5dfa40b4eec14d4536f1c229ad9be1
[ "Apache-2.0" ]
143
2021-10-17T08:43:33.000Z
2022-03-31T11:10:53.000Z
src/pythae/models/nn/default_architectures.py
louis-j-vincent/benchmark_VAE
943e231f9e5dfa40b4eec14d4536f1c229ad9be1
[ "Apache-2.0" ]
6
2022-01-21T17:40:09.000Z
2022-03-16T13:09:22.000Z
src/pythae/models/nn/default_architectures.py
louis-j-vincent/benchmark_VAE
943e231f9e5dfa40b4eec14d4536f1c229ad9be1
[ "Apache-2.0" ]
18
2021-12-16T15:17:08.000Z
2022-03-15T01:30:13.000Z
from typing import List import numpy as np import torch import torch.nn as nn from pythae.models.nn import (BaseDecoder, BaseDiscriminator, BaseEncoder, BaseMetric) from ..base.base_utils import ModelOutput class Encoder_AE_MLP(BaseEncoder): def __init__(self, args: dict): BaseEncoder.__init__(self) self.input_dim = args.input_dim self.latent_dim = args.latent_dim layers = nn.ModuleList() layers.append(nn.Sequential(nn.Linear(np.prod(args.input_dim), 512), nn.ReLU())) self.layers = layers self.depth = len(layers) self.embedding = nn.Linear(512, self.latent_dim) def forward(self, x, output_layer_levels: List[int] = None): output = ModelOutput() max_depth = self.depth if output_layer_levels is not None: assert all( self.depth >= levels > 0 or levels == -1 for levels in output_layer_levels ), ( f"Cannot output layer deeper than depth ({self.depth}). " f"Got ({output_layer_levels})." ) if -1 in output_layer_levels: max_depth = self.depth else: max_depth = max(output_layer_levels) out = x.reshape(-1, np.prod(self.input_dim)) for i in range(max_depth): out = self.layers[i](out) if output_layer_levels is not None: if i + 1 in output_layer_levels: output[f"embedding_layer_{i+1}"] = out if i + 1 == self.depth: output["embedding"] = self.embedding(out) return output class Encoder_VAE_MLP(BaseEncoder): def __init__(self, args: dict): BaseEncoder.__init__(self) self.input_dim = args.input_dim self.latent_dim = args.latent_dim layers = nn.ModuleList() layers.append(nn.Sequential(nn.Linear(np.prod(args.input_dim), 512), nn.ReLU())) self.layers = layers self.depth = len(layers) self.embedding = nn.Linear(512, self.latent_dim) self.log_var = nn.Linear(512, self.latent_dim) def forward(self, x, output_layer_levels: List[int] = None): output = ModelOutput() max_depth = self.depth if output_layer_levels is not None: assert all( self.depth >= levels > 0 or levels == -1 for levels in output_layer_levels ), ( f"Cannot output layer deeper than depth ({self.depth}). " f"Got ({output_layer_levels})." ) if -1 in output_layer_levels: max_depth = self.depth else: max_depth = max(output_layer_levels) out = x.reshape(-1, np.prod(self.input_dim)) for i in range(max_depth): out = self.layers[i](out) if output_layer_levels is not None: if i + 1 in output_layer_levels: output[f"embedding_layer_{i+1}"] = out if i + 1 == self.depth: output["embedding"] = self.embedding(out) output["log_covariance"] = self.log_var(out) return output class Encoder_SVAE_MLP(BaseEncoder): def __init__(self, args: dict): BaseEncoder.__init__(self) self.input_dim = args.input_dim self.latent_dim = args.latent_dim layers = nn.ModuleList() layers.append(nn.Sequential(nn.Linear(np.prod(args.input_dim), 512), nn.ReLU())) self.layers = layers self.depth = len(layers) self.embedding = nn.Linear(512, self.latent_dim) self.log_concentration = nn.Linear(512, 1) def forward(self, x, output_layer_levels: List[int] = None): output = ModelOutput() max_depth = self.depth if output_layer_levels is not None: assert all( self.depth >= levels > 0 or levels == -1 for levels in output_layer_levels ), ( f"Cannot output layer deeper than depth ({self.depth}). " f"Got ({output_layer_levels})." ) if -1 in output_layer_levels: max_depth = self.depth else: max_depth = max(output_layer_levels) out = x.reshape(-1, np.prod(self.input_dim)) for i in range(max_depth): out = self.layers[i](out) if output_layer_levels is not None: if i + 1 in output_layer_levels: output[f"embedding_layer_{i+1}"] = out if i + 1 == self.depth: output["embedding"] = self.embedding(out) output["log_concentration"] = self.log_concentration(out) return output class Decoder_AE_MLP(BaseDecoder): def __init__(self, args: dict): BaseDecoder.__init__(self) self.input_dim = args.input_dim # assert 0, np.prod(args.input_dim) layers = nn.ModuleList() layers.append(nn.Sequential(nn.Linear(args.latent_dim, 512), nn.ReLU())) layers.append( nn.Sequential(nn.Linear(512, int(np.prod(args.input_dim))), nn.Sigmoid()) ) self.layers = layers self.depth = len(layers) def forward(self, z: torch.Tensor, output_layer_levels: List[int] = None): output = ModelOutput() max_depth = self.depth if output_layer_levels is not None: assert all( self.depth >= levels > 0 or levels == -1 for levels in output_layer_levels ), ( f"Cannot output layer deeper than depth ({self.depth}). " f"Got ({output_layer_levels})." ) if -1 in output_layer_levels: max_depth = self.depth else: max_depth = max(output_layer_levels) out = z for i in range(max_depth): out = self.layers[i](out) if output_layer_levels is not None: if i + 1 in output_layer_levels: output[f"reconstruction_layer_{i+1}"] = out if i + 1 == self.depth: output["reconstruction"] = out.reshape((z.shape[0],) + self.input_dim) return output class Metric_MLP(BaseMetric): def __init__(self, args: dict): BaseMetric.__init__(self) if args.input_dim is None: raise AttributeError( "No input dimension provided !" "'input_dim' parameter of ModelConfig instance must be set to 'data_shape' where " "the shape of the data is [mini_batch x data_shape]. Unable to build metric " "automatically" ) self.input_dim = args.input_dim self.latent_dim = args.latent_dim self.layers = nn.Sequential(nn.Linear(np.prod(args.input_dim), 400), nn.ReLU()) self.diag = nn.Linear(400, self.latent_dim) k = int(self.latent_dim * (self.latent_dim - 1) / 2) self.lower = nn.Linear(400, k) def forward(self, x): h1 = self.layers(x.reshape(-1, np.prod(self.input_dim))) h21, h22 = self.diag(h1), self.lower(h1) L = torch.zeros((x.shape[0], self.latent_dim, self.latent_dim)).to(x.device) indices = torch.tril_indices( row=self.latent_dim, col=self.latent_dim, offset=-1 ) # get non-diagonal coefficients L[:, indices[0], indices[1]] = h22 # add diagonal coefficients L = L + torch.diag_embed(h21.exp()) output = ModelOutput(L=L) return output class Discriminator_MLP(BaseDiscriminator): def __init__(self, args: dict): BaseDiscriminator.__init__(self) self.discriminator_input_dim = args.discriminator_input_dim layers = nn.ModuleList() layers.append( nn.Sequential( nn.Linear(np.prod(args.discriminator_input_dim), 256), nn.ReLU() ) ) layers.append(nn.Sequential(nn.Linear(256, 1), nn.Sigmoid())) self.layers = layers self.depth = len(layers) def forward(self, z: torch.Tensor, output_layer_levels: List[int] = None): """Forward method Returns: ModelOutput: An instance of ModelOutput containing the reconstruction of the latent code under the key `reconstruction` """ output = ModelOutput() max_depth = self.depth if output_layer_levels is not None: assert all( self.depth >= levels > 0 or levels == -1 for levels in output_layer_levels ), ( f"Cannot output layer deeper than depth ({self.depth}). " f"Got ({output_layer_levels})." ) if -1 in output_layer_levels: max_depth = self.depth else: max_depth = max(output_layer_levels) out = z.reshape(z.shape[0], -1) for i in range(max_depth): out = self.layers[i](out) if output_layer_levels is not None: if i + 1 in output_layer_levels: output[f"embedding_layer_{i+1}"] = out if i + 1 == self.depth: output["embedding"] = out return output
29.781646
100
0.563915
e632e99a6559935d550ea8383ffe5a51185b1334
7,812
py
Python
uhd_restpy/testplatform/sessions/ixnetwork/topology/isissrlbdescriptorlist_1eec075b53920dfd5040006478718f6a.py
OpenIxia/ixnetwork_restpy
f628db450573a104f327cf3c737ca25586e067ae
[ "MIT" ]
20
2019-05-07T01:59:14.000Z
2022-02-11T05:24:47.000Z
uhd_restpy/testplatform/sessions/ixnetwork/topology/isissrlbdescriptorlist_1eec075b53920dfd5040006478718f6a.py
OpenIxia/ixnetwork_restpy
f628db450573a104f327cf3c737ca25586e067ae
[ "MIT" ]
60
2019-04-03T18:59:35.000Z
2022-02-22T12:05:05.000Z
uhd_restpy/testplatform/sessions/ixnetwork/topology/isissrlbdescriptorlist_1eec075b53920dfd5040006478718f6a.py
OpenIxia/ixnetwork_restpy
f628db450573a104f327cf3c737ca25586e067ae
[ "MIT" ]
13
2019-05-20T10:48:31.000Z
2021-10-06T07:45:44.000Z
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from uhd_restpy.base import Base from uhd_restpy.files import Files from typing import List, Any, Union class IsisSRLBDescriptorList(Base): """Isis SRLB Descriptor Entries The IsisSRLBDescriptorList class encapsulates a list of isisSRLBDescriptorList resources that are managed by the system. A list of resources can be retrieved from the server using the IsisSRLBDescriptorList.find() method. """ __slots__ = () _SDM_NAME = 'isisSRLBDescriptorList' _SDM_ATT_MAP = { 'Count': 'count', 'DescriptiveName': 'descriptiveName', 'Name': 'name', 'SIDCount': 'sIDCount', 'StartSIDLabel': 'startSIDLabel', } _SDM_ENUM_MAP = { } def __init__(self, parent, list_op=False): super(IsisSRLBDescriptorList, self).__init__(parent, list_op) @property def Count(self): # type: () -> int """ Returns ------- - number: Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group. """ return self._get_attribute(self._SDM_ATT_MAP['Count']) @property def DescriptiveName(self): # type: () -> str """ Returns ------- - str: Longer, more descriptive name for element. It's not guaranteed to be unique like -name-, but may offer more context. """ return self._get_attribute(self._SDM_ATT_MAP['DescriptiveName']) @property def Name(self): # type: () -> str """ Returns ------- - str: Name of NGPF element, guaranteed to be unique in Scenario """ return self._get_attribute(self._SDM_ATT_MAP['Name']) @Name.setter def Name(self, value): # type: (str) -> None self._set_attribute(self._SDM_ATT_MAP['Name'], value) @property def SIDCount(self): # type: () -> 'Multivalue' """ Returns ------- - obj(uhd_restpy.multivalue.Multivalue): SID Count """ from uhd_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['SIDCount'])) @property def StartSIDLabel(self): # type: () -> 'Multivalue' """ Returns ------- - obj(uhd_restpy.multivalue.Multivalue): Start SID/Label """ from uhd_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['StartSIDLabel'])) def update(self, Name=None): # type: (str) -> IsisSRLBDescriptorList """Updates isisSRLBDescriptorList resource on the server. This method has some named parameters with a type: obj (Multivalue). The Multivalue class has documentation that details the possible values for those named parameters. Args ---- - Name (str): Name of NGPF element, guaranteed to be unique in Scenario Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._update(self._map_locals(self._SDM_ATT_MAP, locals())) def add(self, Name=None): # type: (str) -> IsisSRLBDescriptorList """Adds a new isisSRLBDescriptorList resource on the json, only valid with config assistant Args ---- - Name (str): Name of NGPF element, guaranteed to be unique in Scenario Returns ------- - self: This instance with all currently retrieved isisSRLBDescriptorList resources using find and the newly added isisSRLBDescriptorList resources available through an iterator or index Raises ------ - Exception: if this function is not being used with config assistance """ return self._add_xpath(self._map_locals(self._SDM_ATT_MAP, locals())) def find(self, Count=None, DescriptiveName=None, Name=None): # type: (int, str, str) -> IsisSRLBDescriptorList """Finds and retrieves isisSRLBDescriptorList resources from the server. All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve isisSRLBDescriptorList resources from the server. To retrieve an exact match ensure the parameter value starts with ^ and ends with $ By default the find method takes no parameters and will retrieve all isisSRLBDescriptorList resources from the server. Args ---- - Count (number): Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group. - DescriptiveName (str): Longer, more descriptive name for element. It's not guaranteed to be unique like -name-, but may offer more context. - Name (str): Name of NGPF element, guaranteed to be unique in Scenario Returns ------- - self: This instance with matching isisSRLBDescriptorList resources retrieved from the server available through an iterator or index Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._select(self._map_locals(self._SDM_ATT_MAP, locals())) def read(self, href): """Retrieves a single instance of isisSRLBDescriptorList data from the server. Args ---- - href (str): An href to the instance to be retrieved Returns ------- - self: This instance with the isisSRLBDescriptorList resources from the server available through an iterator or index Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ return self._read(href) def get_device_ids(self, PortNames=None, SIDCount=None, StartSIDLabel=None): """Base class infrastructure that gets a list of isisSRLBDescriptorList device ids encapsulated by this object. Use the optional regex parameters in the method to refine the list of device ids encapsulated by this object. Args ---- - PortNames (str): optional regex of port names - SIDCount (str): optional regex of sIDCount - StartSIDLabel (str): optional regex of startSIDLabel Returns ------- - list(int): A list of device ids that meets the regex criteria provided in the method parameters Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._get_ngpf_device_ids(locals())
38.865672
194
0.665003
54b1feeda82dd02f635a8fa1ef6ba907114ea80a
3,857
py
Python
pyfolio/interesting_periods.py
vantoshkin/pyfolio
7733d8cc4a9532f90f2322846aba84145e2d8a35
[ "Apache-2.0" ]
null
null
null
pyfolio/interesting_periods.py
vantoshkin/pyfolio
7733d8cc4a9532f90f2322846aba84145e2d8a35
[ "Apache-2.0" ]
null
null
null
pyfolio/interesting_periods.py
vantoshkin/pyfolio
7733d8cc4a9532f90f2322846aba84145e2d8a35
[ "Apache-2.0" ]
1
2022-03-24T21:37:17.000Z
2022-03-24T21:37:17.000Z
# # Copyright 2016 Quantopian, 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. """Generates a list of historical event dates that may have had significant impact on markets. See extract_interesting_date_ranges.""" import pandas as pd from collections import OrderedDict PERIODS = OrderedDict() # Dotcom bubble PERIODS['Dotcom'] = (pd.Timestamp('20000310').tz_localize('UTC'), pd.Timestamp('20000910').tz_localize('UTC')) # Lehmann Brothers PERIODS['Lehman'] = (pd.Timestamp('20080801').tz_localize('UTC'), pd.Timestamp('20081001').tz_localize('UTC')) # 9/11 PERIODS['9/11'] = (pd.Timestamp('20010911').tz_localize('UTC'), pd.Timestamp('20011011').tz_localize('UTC')) # 05/08/11 US down grade and European Debt Crisis 2011 PERIODS[ 'US downgrade/European Debt Crisis'] = ( pd.Timestamp('20110805').tz_localize('UTC'), pd.Timestamp('20110905').tz_localize('UTC')) # 16/03/11 Fukushima melt down 2011 PERIODS['Fukushima'] = (pd.Timestamp('20110316').tz_localize('UTC'), pd.Timestamp('20110416').tz_localize('UTC')) # 01/08/03 US Housing Bubble 2003 PERIODS['US Housing'] = ( pd.Timestamp('20030108').tz_localize('UTC'), pd.Timestamp('20030208').tz_localize('UTC')) # 06/09/12 EZB IR Event 2012 PERIODS['EZB IR Event'] = ( pd.Timestamp('20120910').tz_localize('UTC'), pd.Timestamp('20121010').tz_localize('UTC') ) # August 2007, March and September of 2008, Q1 & Q2 2009, PERIODS['Aug07'] = (pd.Timestamp('20070801').tz_localize('UTC'), pd.Timestamp('20070901').tz_localize('UTC')) PERIODS['Mar08'] = (pd.Timestamp('20080301').tz_localize('UTC'), pd.Timestamp('20080401').tz_localize('UTC')) PERIODS['Sept08'] = (pd.Timestamp('20080901').tz_localize('UTC'), pd.Timestamp('20081001').tz_localize('UTC')) PERIODS['2009Q1'] = (pd.Timestamp('20090101').tz_localize('UTC'), pd.Timestamp('20090301').tz_localize('UTC')) PERIODS['2009Q2'] = (pd.Timestamp('20090301').tz_localize('UTC'), pd.Timestamp('20090601').tz_localize('UTC')) # Flash Crash (May 6, 2010 + 1 week post), PERIODS['Flash Crash'] = ( pd.Timestamp('20100505').tz_localize('UTC'), pd.Timestamp('20100510').tz_localize('UTC')) # April and October 2014). PERIODS['Apr14'] = (pd.Timestamp('20140401').tz_localize('UTC'), pd.Timestamp('20140501').tz_localize('UTC')) PERIODS['Oct14'] = (pd.Timestamp('20141001').tz_localize('UTC'), pd.Timestamp('20141101').tz_localize('UTC')) # Market down-turn in August/Sept 2015 PERIODS['Fall2015'] = (pd.Timestamp('20150815').tz_localize('UTC'), pd.Timestamp('20150930').tz_localize('UTC')) # Market regimes PERIODS['Low Volatility Bull Market'] = ( pd.Timestamp('20050101').tz_localize('UTC'), pd.Timestamp('20070801').tz_localize('UTC')) PERIODS['GFC Crash'] = (pd.Timestamp('20070801').tz_localize('UTC'), pd.Timestamp('20090401').tz_localize('UTC')) PERIODS['Recovery'] = (pd.Timestamp('20090401').tz_localize('UTC'), pd.Timestamp('20130101').tz_localize('UTC')) PERIODS['New Normal'] = (pd.Timestamp('20130101').tz_localize('UTC'), pd.Timestamp('today').tz_localize('UTC'))
40.177083
92
0.654654
120909f8acb9e642018f879c1a7496a5b8ad471f
194
py
Python
tests/test_settings.py
davidszotten/speccify
7c3f114d3a5f2c1a4cb7538df0319c66c1c70cb0
[ "Apache-2.0" ]
5
2021-06-28T14:02:01.000Z
2021-12-20T13:04:09.000Z
tests/test_settings.py
davidszotten/speccify
7c3f114d3a5f2c1a4cb7538df0319c66c1c70cb0
[ "Apache-2.0" ]
null
null
null
tests/test_settings.py
davidszotten/speccify
7c3f114d3a5f2c1a4cb7538df0319c66c1c70cb0
[ "Apache-2.0" ]
1
2021-06-25T12:08:11.000Z
2021-06-25T12:08:11.000Z
INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.contenttypes", ] SECRET_KEY = "secret" REST_FRAMEWORK = { "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", }
17.636364
65
0.71134
4f02fc9eac259b5c21ad8782e4e3798cec850b88
7,517
py
Python
tests/integration/order/creator_tests.py
akiyoko/oscar_sandbox
b384f1c0b5f297fd4b84509a575f6766a48630a5
[ "BSD-3-Clause" ]
2
2015-12-11T00:19:15.000Z
2021-11-14T19:44:42.000Z
tests/integration/order/creator_tests.py
akiyoko/oscar_sandbox
b384f1c0b5f297fd4b84509a575f6766a48630a5
[ "BSD-3-Clause" ]
null
null
null
tests/integration/order/creator_tests.py
akiyoko/oscar_sandbox
b384f1c0b5f297fd4b84509a575f6766a48630a5
[ "BSD-3-Clause" ]
null
null
null
from decimal import Decimal as D from django.test import TestCase from django.test.utils import override_settings from mock import Mock from oscar.apps.catalogue.models import ProductClass, Product from oscar.apps.offer.utils import Applicator from oscar.apps.order.models import Order from oscar.apps.order.utils import OrderCreator from oscar.apps.shipping.methods import Free, FixedPrice from oscar.apps.shipping.repository import Repository from oscar.core.loading import get_class from oscar.test import factories from oscar.test.basket import add_product from oscar.apps.checkout import calculators Range = get_class('offer.models', 'Range') Benefit = get_class('offer.models', 'Benefit') def place_order(creator, **kwargs): """ Helper function to place an order without the boilerplate """ if 'shipping_method' not in kwargs: kwargs['shipping_method'] = Free() shipping_charge = kwargs['shipping_method'].calculate(kwargs['basket']) kwargs['total'] = calculators.OrderTotalCalculator().calculate( basket=kwargs['basket'], shipping_charge=shipping_charge) kwargs['shipping_charge'] = shipping_charge return creator.place_order(**kwargs) class TestOrderCreatorErrorCases(TestCase): def setUp(self): self.creator = OrderCreator() self.basket = factories.create_basket(empty=True) def test_raises_exception_when_empty_basket_passed(self): with self.assertRaises(ValueError): place_order(self.creator, basket=self.basket) def test_raises_exception_if_duplicate_order_number_passed(self): add_product(self.basket, D('12.00')) place_order(self.creator, basket=self.basket, order_number='1234') with self.assertRaises(ValueError): place_order(self.creator, basket=self.basket, order_number='1234') class TestSuccessfulOrderCreation(TestCase): def setUp(self): self.creator = OrderCreator() self.basket = factories.create_basket(empty=True) def test_saves_shipping_code(self): add_product(self.basket, D('12.00')) free_method = Free() order = place_order(self.creator, basket=self.basket, order_number='1234', shipping_method=free_method) self.assertEqual(order.shipping_code, free_method.code) def test_creates_order_and_line_models(self): add_product(self.basket, D('12.00')) place_order(self.creator, basket=self.basket, order_number='1234') order = Order.objects.get(number='1234') lines = order.lines.all() self.assertEqual(1, len(lines)) def test_sets_correct_order_status(self): add_product(self.basket, D('12.00')) place_order(self.creator, basket=self.basket, order_number='1234', status='Active') order = Order.objects.get(number='1234') self.assertEqual('Active', order.status) def test_defaults_to_using_free_shipping(self): add_product(self.basket, D('12.00')) place_order(self.creator, basket=self.basket, order_number='1234') order = Order.objects.get(number='1234') self.assertEqual(order.total_incl_tax, self.basket.total_incl_tax) self.assertEqual(order.total_excl_tax, self.basket.total_excl_tax) def test_uses_default_order_status_from_settings(self): add_product(self.basket, D('12.00')) with override_settings(OSCAR_INITIAL_ORDER_STATUS='A'): place_order(self.creator, basket=self.basket, order_number='1234') order = Order.objects.get(number='1234') self.assertEqual('A', order.status) def test_uses_default_line_status_from_settings(self): add_product(self.basket, D('12.00')) with override_settings(OSCAR_INITIAL_LINE_STATUS='A'): place_order(self.creator, basket=self.basket, order_number='1234') order = Order.objects.get(number='1234') line = order.lines.all()[0] self.assertEqual('A', line.status) def test_partner_name_is_optional(self): for partner_name, order_number in [('', 'A'), ('p1', 'B')]: self.basket = factories.create_basket(empty=True) product = factories.create_product(partner_name=partner_name) add_product(self.basket, D('12.00'), product=product) place_order( self.creator, basket=self.basket, order_number=order_number) line = Order.objects.get(number=order_number).lines.all()[0] partner = product.stockrecords.all()[0].partner self.assertTrue(partner_name == line.partner_name == partner.name) class TestPlacingOrderForDigitalGoods(TestCase): def setUp(self): self.creator = OrderCreator() self.basket = factories.create_basket(empty=True) def test_does_not_allocate_stock(self): ProductClass.objects.create( name="Digital", track_stock=False) product = factories.create_product(product_class="Digital") record = factories.create_stockrecord(product, num_in_stock=None) self.assertTrue(record.num_allocated is None) add_product(self.basket, D('12.00'), product=product) place_order(self.creator, basket=self.basket, order_number='1234') product = Product.objects.get(id=product.id) stockrecord = product.stockrecords.all()[0] self.assertTrue(stockrecord.num_in_stock is None) self.assertTrue(stockrecord.num_allocated is None) class TestShippingOfferForOrder(TestCase): def setUp(self): self.creator = OrderCreator() self.basket = factories.create_basket(empty=True) def apply_20percent_shipping_offer(self): """Shipping offer 20% off""" range = Range.objects.create(name="All products range", includes_all_products=True) benefit = Benefit.objects.create( range=range, type=Benefit.SHIPPING_PERCENTAGE, value=20) offer = factories.create_offer(range=range, benefit=benefit) Applicator().apply_offers(self.basket, [offer]) return offer def test_shipping_offer_is_applied(self): add_product(self.basket, D('12.00')) offer = self.apply_20percent_shipping_offer() shipping = FixedPrice(D('5.00'), D('5.00')) shipping = Repository().apply_shipping_offer( self.basket, shipping, offer) place_order(self.creator, basket=self.basket, order_number='1234', shipping_method=shipping) order = Order.objects.get(number='1234') self.assertEqual(1, len(order.shipping_discounts)) self.assertEqual(D('4.00'), order.shipping_incl_tax) self.assertEqual(D('16.00'), order.total_incl_tax) def test_zero_shipping_discount_is_not_created(self): add_product(self.basket, D('12.00')) offer = self.apply_20percent_shipping_offer() shipping = Free() shipping = Repository().apply_shipping_offer( self.basket, shipping, offer) place_order(self.creator, basket=self.basket, order_number='1234', shipping_method=shipping) order = Order.objects.get(number='1234') # No shipping discount self.assertEqual(0, len(order.shipping_discounts)) self.assertEqual(D('0.00'), order.shipping_incl_tax) self.assertEqual(D('12.00'), order.total_incl_tax)
39.772487
78
0.680724
d2ec5b53aa1564536c44c9b81730ecd3a45192f5
18,563
py
Python
rest_framework_json_api/serializers.py
SafaAlfulaij/django-rest-framework-json-api
1187411af4bfb05adc06e49bac88528a56fe1aa0
[ "BSD-2-Clause" ]
null
null
null
rest_framework_json_api/serializers.py
SafaAlfulaij/django-rest-framework-json-api
1187411af4bfb05adc06e49bac88528a56fe1aa0
[ "BSD-2-Clause" ]
null
null
null
rest_framework_json_api/serializers.py
SafaAlfulaij/django-rest-framework-json-api
1187411af4bfb05adc06e49bac88528a56fe1aa0
[ "BSD-2-Clause" ]
null
null
null
import warnings from collections import OrderedDict from collections.abc import Mapping import inflection from django.core.exceptions import ObjectDoesNotExist from django.db.models.query import QuerySet from django.utils.module_loading import import_string as import_class_from_dotted_path from django.utils.translation import gettext_lazy as _ from rest_framework.exceptions import ParseError # star import defined so `rest_framework_json_api.serializers` can be # a simple drop in for `rest_framework.serializers` from rest_framework.serializers import * # noqa: F401, F403 from rest_framework.serializers import ( BaseSerializer, HyperlinkedModelSerializer, ModelSerializer, Serializer, SerializerMetaclass, ) from rest_framework.settings import api_settings from rest_framework_json_api.exceptions import Conflict from rest_framework_json_api.relations import ResourceRelatedField from rest_framework_json_api.utils import ( get_included_resources, get_resource_type_from_instance, get_resource_type_from_model, get_resource_type_from_serializer, ) class ResourceIdentifierObjectSerializer(BaseSerializer): default_error_messages = { "incorrect_model_type": _( "Incorrect model type. Expected {model_type}, received {received_type}." ), "does_not_exist": _('Invalid pk "{pk_value}" - object does not exist.'), "incorrect_type": _("Incorrect type. Expected pk value, received {data_type}."), } model_class = None def __init__(self, *args, **kwargs): self.model_class = kwargs.pop("model_class", self.model_class) # this has no fields but assumptions are made elsewhere that self.fields exists. self.fields = {} super().__init__(*args, **kwargs) def to_representation(self, instance): return { "type": get_resource_type_from_instance(instance), "id": str(instance.pk), } def to_internal_value(self, data): if data["type"] != get_resource_type_from_model(self.model_class): self.fail( "incorrect_model_type", model_type=self.model_class, received_type=data["type"], ) pk = data["id"] try: return self.model_class.objects.get(pk=pk) except ObjectDoesNotExist: self.fail("does_not_exist", pk_value=pk) except (TypeError, ValueError): self.fail("incorrect_type", data_type=type(data["pk"]).__name__) class SparseFieldsetsMixin: """ A serializer mixin that adds support for sparse fieldsets through `fields` query parameter. Specification: https://jsonapi.org/format/#fetching-sparse-fieldsets """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) context = kwargs.get("context") request = context.get("request") if context else None if request: sparse_fieldset_query_param = "fields[{}]".format( get_resource_type_from_serializer(self) ) try: param_name = next( key for key in request.query_params if sparse_fieldset_query_param == key ) except StopIteration: pass else: fieldset = request.query_params.get(param_name).split(",") # iterate over a *copy* of self.fields' underlying OrderedDict, because we may # modify the original during the iteration. # self.fields is a `rest_framework.utils.serializer_helpers.BindingDict` for field_name, field in self.fields.fields.copy().items(): if ( field_name == api_settings.URL_FIELD_NAME ): # leave self link there continue if field_name not in fieldset: self.fields.pop(field_name) class IncludedResourcesValidationMixin: """ A serializer mixin that adds validation of `include` query parameter to support compound documents. Specification: https://jsonapi.org/format/#document-compound-documents) """ def __init__(self, *args, **kwargs): context = kwargs.get("context") request = context.get("request") if context else None view = context.get("view") if context else None def validate_path(serializer_class, field_path, path): serializers = getattr(serializer_class, "included_serializers", None) if serializers is None: raise ParseError("This endpoint does not support the include parameter") this_field_name = inflection.underscore(field_path[0]) this_included_serializer = serializers.get(this_field_name) if this_included_serializer is None: raise ParseError( "This endpoint does not support the include parameter for path {}".format( path ) ) if len(field_path) > 1: new_included_field_path = field_path[1:] # We go down one level in the path validate_path(this_included_serializer, new_included_field_path, path) if request and view: included_resources = get_included_resources(request) for included_field_name in included_resources: included_field_path = included_field_name.split(".") if "related_field" in view.kwargs: this_serializer_class = view.get_related_serializer_class() else: this_serializer_class = view.get_serializer_class() # lets validate the current path validate_path( this_serializer_class, included_field_path, included_field_name ) super().__init__(*args, **kwargs) class ReservedFieldNamesMixin: """Ensures that reserved field names are not used and an error raised instead.""" _reserved_field_names = {"meta", "results"} def get_fields(self): fields = super().get_fields() found_reserved_field_names = self._reserved_field_names.intersection( fields.keys() ) if found_reserved_field_names: raise AttributeError( f"Serializer class {self.__class__.__module__}.{self.__class__.__qualname__} " f"uses following reserved field name(s) which is not allowed: " f"{', '.join(sorted(found_reserved_field_names))}" ) if "type" in fields: # see https://jsonapi.org/format/#document-resource-object-fields warnings.warn( DeprecationWarning( f"Field name 'type' found in serializer class " f"{self.__class__.__module__}.{self.__class__.__qualname__} " f"which is not allowed according to the JSON:API spec and " f"won't be supported anymore in the next major DJA release. " f"Rename 'type' field to something else. " ) ) return fields class LazySerializersDict(Mapping): """ A dictionary of serializers which lazily import dotted class path and self. """ def __init__(self, parent, serializers): self.parent = parent self.serializers = serializers def __getitem__(self, key): value = self.serializers[key] if not isinstance(value, type): if value == "self": value = self.parent else: value = import_class_from_dotted_path(value) self.serializers[key] = value return value def __iter__(self): return iter(self.serializers) def __len__(self): return len(self.serializers) def __repr__(self): return dict.__repr__(self.serializers) class SerializerMetaclass(SerializerMetaclass): def __new__(cls, name, bases, attrs): serializer = super().__new__(cls, name, bases, attrs) if attrs.get("included_serializers", None): setattr( serializer, "included_serializers", LazySerializersDict(serializer, attrs["included_serializers"]), ) if attrs.get("related_serializers", None): setattr( serializer, "related_serializers", LazySerializersDict(serializer, attrs["related_serializers"]), ) return serializer # If user imports serializer from here we can catch class definition and check # nested serializers for depricated use. class Serializer( IncludedResourcesValidationMixin, SparseFieldsetsMixin, ReservedFieldNamesMixin, Serializer, metaclass=SerializerMetaclass, ): """ A `Serializer` is a model-less serializer class with additional support for JSON:API spec features. As in JSON:API specification a type is always required you need to make sure that you define `resource_name` in your `Meta` class when deriving from this class. Included Mixins: * A mixin class to enable sparse fieldsets is included * A mixin class to enable validation of included resources is included """ pass class HyperlinkedModelSerializer( IncludedResourcesValidationMixin, SparseFieldsetsMixin, ReservedFieldNamesMixin, HyperlinkedModelSerializer, metaclass=SerializerMetaclass, ): """ A type of `ModelSerializer` that uses hyperlinked relationships instead of primary key relationships. Specifically: * A 'url' field is included instead of the 'id' field. * Relationships to other instances are hyperlinks, instead of primary keys. Included Mixins: * A mixin class to enable sparse fieldsets is included * A mixin class to enable validation of included resources is included """ class ModelSerializer( IncludedResourcesValidationMixin, SparseFieldsetsMixin, ReservedFieldNamesMixin, ModelSerializer, metaclass=SerializerMetaclass, ): """ A `ModelSerializer` is just a regular `Serializer`, except that: * A set of default fields are automatically populated. * A set of default validators are automatically populated. * Default `.create()` and `.update()` implementations are provided. The process of automatically determining a set of serializer fields based on the model fields is reasonably complex, but you almost certainly don't need to dig into the implementation. If the `ModelSerializer` class *doesn't* generate the set of fields that you need you should either declare the extra/differing fields explicitly on the serializer class, or simply use a `Serializer` class. Included Mixins: * A mixin class to enable sparse fieldsets is included * A mixin class to enable validation of included resources is included """ serializer_related_field = ResourceRelatedField def get_field_names(self, declared_fields, info): """ We override the parent to omit explicity defined meta fields (such as SerializerMethodFields) from the list of declared fields """ meta_fields = getattr(self.Meta, "meta_fields", []) declared = OrderedDict() for field_name in set(declared_fields.keys()): field = declared_fields[field_name] if field_name not in meta_fields: declared[field_name] = field fields = super(ModelSerializer, self).get_field_names(declared, info) return list(fields) + list(getattr(self.Meta, "meta_fields", list())) class PolymorphicSerializerMetaclass(SerializerMetaclass): """ This metaclass ensures that the `polymorphic_serializers` is correctly defined on a `PolymorphicSerializer` class and make a cache of model/serializer/type mappings. """ def __new__(cls, name, bases, attrs): new_class = super().__new__(cls, name, bases, attrs) # Ensure initialization is only performed for subclasses of PolymorphicModelSerializer # (excluding PolymorphicModelSerializer class itself). parents = [b for b in bases if isinstance(b, PolymorphicSerializerMetaclass)] if not parents: return new_class polymorphic_serializers = getattr(new_class, "polymorphic_serializers", None) if not polymorphic_serializers: raise NotImplementedError( "A PolymorphicModelSerializer must define a `polymorphic_serializers` attribute." ) serializer_to_model = { serializer: serializer.Meta.model for serializer in polymorphic_serializers } model_to_serializer = { serializer.Meta.model: serializer for serializer in polymorphic_serializers } type_to_serializer = { get_resource_type_from_serializer(serializer): serializer for serializer in polymorphic_serializers } new_class._poly_serializer_model_map = serializer_to_model new_class._poly_model_serializer_map = model_to_serializer new_class._poly_type_serializer_map = type_to_serializer new_class._poly_force_type_resolution = True # Flag each linked polymorphic serializer to force type resolution based on instance for serializer in polymorphic_serializers: serializer._poly_force_type_resolution = True return new_class class PolymorphicModelSerializer( ModelSerializer, metaclass=PolymorphicSerializerMetaclass ): """ A serializer for polymorphic models. Useful for "lazy" parent models. Leaves should be represented with a regular serializer. """ def get_fields(self): """ Return an exhaustive list of the polymorphic serializer fields. """ if self.instance not in (None, []): if not isinstance(self.instance, QuerySet): serializer_class = self.get_polymorphic_serializer_for_instance( self.instance ) return serializer_class( self.instance, context=self.context ).get_fields() else: raise Exception( "Cannot get fields from a polymorphic serializer given a queryset" ) return super().get_fields() @classmethod def get_polymorphic_serializer_for_instance(cls, instance): """ Return the polymorphic serializer associated with the given instance/model. Raise `NotImplementedError` if no serializer is found for the given model. This usually means that a serializer is missing in the class's `polymorphic_serializers` attribute. """ try: return cls._poly_model_serializer_map[instance._meta.model] except KeyError: raise NotImplementedError( "No polymorphic serializer has been found for model {}".format( instance._meta.model.__name__ ) ) @classmethod def get_polymorphic_model_for_serializer(cls, serializer): """ Return the polymorphic model associated with the given serializer. Raise `NotImplementedError` if no model is found for the given serializer. This usually means that a serializer is missing in the class's `polymorphic_serializers` attribute. """ try: return cls._poly_serializer_model_map[serializer] except KeyError: raise NotImplementedError( "No polymorphic model has been found for serializer {}".format( serializer.__name__ ) ) @classmethod def get_polymorphic_serializer_for_type(cls, obj_type): """ Return the polymorphic serializer associated with the given type. Raise `NotImplementedError` if no serializer is found for the given type. This usually means that a serializer is missing in the class's `polymorphic_serializers` attribute. """ try: return cls._poly_type_serializer_map[obj_type] except KeyError: raise NotImplementedError( "No polymorphic serializer has been found for type {}".format(obj_type) ) @classmethod def get_polymorphic_model_for_type(cls, obj_type): """ Return the polymorphic model associated with the given type. Raise `NotImplementedError` if no model is found for the given type. This usually means that a serializer is missing in the class's `polymorphic_serializers` attribute. """ return cls.get_polymorphic_model_for_serializer( cls.get_polymorphic_serializer_for_type(obj_type) ) @classmethod def get_polymorphic_types(cls): """ Return the list of accepted types. """ return cls._poly_type_serializer_map.keys() def to_representation(self, instance): """ Retrieve the appropriate polymorphic serializer and use this to handle representation. """ serializer_class = self.get_polymorphic_serializer_for_instance(instance) return serializer_class(instance, context=self.context).to_representation( instance ) def to_internal_value(self, data): """ Ensure that the given type is one of the expected polymorphic types, then retrieve the appropriate polymorphic serializer and use this to handle internal value. """ received_type = data.get("type") expected_types = self.get_polymorphic_types() if received_type not in expected_types: raise Conflict( "Incorrect relation type. Expected on of [{expected_types}], " "received {received_type}.".format( expected_types=", ".join(expected_types), received_type=received_type, ) ) serializer_class = self.get_polymorphic_serializer_for_type(received_type) self.__class__ = serializer_class return serializer_class( self.instance, data, context=self.context, partial=self.partial ).to_internal_value(data)
37.425403
97
0.650972
fd18a99e555fabbcc57f19f487ef3875e4eb2ad8
12,549
py
Python
tests/test_file_io.py
Dufy24/flake
1256a64f388eb177859c7660558a651e18b7d7d1
[ "Apache-2.0" ]
1
2020-07-22T18:44:12.000Z
2020-07-22T18:44:12.000Z
tests/test_file_io.py
Dufy24/flake
1256a64f388eb177859c7660558a651e18b7d7d1
[ "Apache-2.0" ]
null
null
null
tests/test_file_io.py
Dufy24/flake
1256a64f388eb177859c7660558a651e18b7d7d1
[ "Apache-2.0" ]
null
null
null
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import os import shutil import tempfile import unittest import uuid from contextlib import contextmanager from typing import Generator, Optional from unittest.mock import MagicMock, patch from fvcore.common import file_io from fvcore.common.file_io import ( HTTPURLHandler, LazyPath, PathManager, PathManagerBase, get_cache_dir, ) class TestNativeIO(unittest.TestCase): _tmpdir: Optional[str] = None _tmpfile: Optional[str] = None _tmpfile_contents = "Hello, World" @classmethod def setUpClass(cls) -> None: cls._tmpdir = tempfile.mkdtemp() # pyre-ignore with open(os.path.join(cls._tmpdir, "test.txt"), "w") as f: cls._tmpfile = f.name f.write(cls._tmpfile_contents) f.flush() @classmethod def tearDownClass(cls) -> None: # Cleanup temp working dir. if cls._tmpdir is not None: shutil.rmtree(cls._tmpdir) # type: ignore def test_open(self) -> None: # pyre-ignore with PathManager.open(self._tmpfile, "r") as f: self.assertEqual(f.read(), self._tmpfile_contents) def test_open_args(self) -> None: PathManager.set_strict_kwargs_checking(True) f = PathManager.open( self._tmpfile, # type: ignore mode="r", buffering=1, encoding="UTF-8", errors="ignore", newline=None, closefd=True, opener=None, ) f.close() def test_get_local_path(self) -> None: self.assertEqual( # pyre-ignore PathManager.get_local_path(self._tmpfile), self._tmpfile, ) def test_exists(self) -> None: # pyre-ignore self.assertTrue(PathManager.exists(self._tmpfile)) # pyre-ignore fake_path = os.path.join(self._tmpdir, uuid.uuid4().hex) self.assertFalse(PathManager.exists(fake_path)) def test_isfile(self) -> None: self.assertTrue(PathManager.isfile(self._tmpfile)) # pyre-ignore # This is a directory, not a file, so it should fail self.assertFalse(PathManager.isfile(self._tmpdir)) # pyre-ignore # This is a non-existing path, so it should fail fake_path = os.path.join(self._tmpdir, uuid.uuid4().hex) # pyre-ignore self.assertFalse(PathManager.isfile(fake_path)) def test_isdir(self) -> None: # pyre-ignore self.assertTrue(PathManager.isdir(self._tmpdir)) # This is a file, not a directory, so it should fail # pyre-ignore self.assertFalse(PathManager.isdir(self._tmpfile)) # This is a non-existing path, so it should fail # pyre-ignore fake_path = os.path.join(self._tmpdir, uuid.uuid4().hex) self.assertFalse(PathManager.isdir(fake_path)) def test_ls(self) -> None: # Create some files in the tempdir to ls out. root_dir = os.path.join(self._tmpdir, "ls") # pyre-ignore os.makedirs(root_dir, exist_ok=True) files = sorted(["foo.txt", "bar.txt", "baz.txt"]) for f in files: open(os.path.join(root_dir, f), "a").close() children = sorted(PathManager.ls(root_dir)) self.assertListEqual(children, files) # Cleanup the tempdir shutil.rmtree(root_dir) def test_mkdirs(self) -> None: # pyre-ignore new_dir_path = os.path.join(self._tmpdir, "new", "tmp", "dir") self.assertFalse(PathManager.exists(new_dir_path)) PathManager.mkdirs(new_dir_path) self.assertTrue(PathManager.exists(new_dir_path)) def test_copy(self) -> None: _tmpfile_2 = self._tmpfile + "2" # pyre-ignore _tmpfile_2_contents = "something else" with open(_tmpfile_2, "w") as f: f.write(_tmpfile_2_contents) f.flush() # pyre-ignore assert PathManager.copy(self._tmpfile, _tmpfile_2, True) with PathManager.open(_tmpfile_2, "r") as f: self.assertEqual(f.read(), self._tmpfile_contents) def test_symlink(self) -> None: _symlink = self._tmpfile + "_symlink" # pyre-ignore assert PathManager.symlink(self._tmpfile, _symlink) # pyre-ignore with PathManager.open(_symlink) as f: self.assertEqual(f.read(), self._tmpfile_contents) assert os.readlink(_symlink) == self._tmpfile os.remove(_symlink) def test_rm(self) -> None: # pyre-ignore with open(os.path.join(self._tmpdir, "test_rm.txt"), "w") as f: rm_file = f.name f.write(self._tmpfile_contents) f.flush() self.assertTrue(PathManager.exists(rm_file)) self.assertTrue(PathManager.isfile(rm_file)) PathManager.rm(rm_file) self.assertFalse(PathManager.exists(rm_file)) self.assertFalse(PathManager.isfile(rm_file)) def test_bad_args(self) -> None: # TODO (T58240718): Replace with dynamic checks with self.assertRaises(ValueError): PathManager.copy( self._tmpfile, self._tmpfile, foo="foo" # type: ignore ) with self.assertRaises(ValueError): PathManager.exists(self._tmpfile, foo="foo") # type: ignore with self.assertRaises(ValueError): PathManager.get_local_path(self._tmpfile, foo="foo") # type: ignore with self.assertRaises(ValueError): PathManager.isdir(self._tmpfile, foo="foo") # type: ignore with self.assertRaises(ValueError): PathManager.isfile(self._tmpfile, foo="foo") # type: ignore with self.assertRaises(ValueError): PathManager.ls(self._tmpfile, foo="foo") # type: ignore with self.assertRaises(ValueError): PathManager.mkdirs(self._tmpfile, foo="foo") # type: ignore with self.assertRaises(ValueError): PathManager.open(self._tmpfile, foo="foo") # type: ignore with self.assertRaises(ValueError): PathManager.rm(self._tmpfile, foo="foo") # type: ignore PathManager.set_strict_kwargs_checking(False) PathManager.copy( self._tmpfile, self._tmpfile, foo="foo" # type: ignore ) PathManager.exists(self._tmpfile, foo="foo") # type: ignore PathManager.get_local_path(self._tmpfile, foo="foo") # type: ignore PathManager.isdir(self._tmpfile, foo="foo") # type: ignore PathManager.isfile(self._tmpfile, foo="foo") # type: ignore PathManager.ls(self._tmpdir, foo="foo") # type: ignore PathManager.mkdirs(self._tmpdir, foo="foo") # type: ignore f = PathManager.open(self._tmpfile, foo="foo") # type: ignore f.close() # pyre-ignore with open(os.path.join(self._tmpdir, "test_rm.txt"), "w") as f: rm_file = f.name f.write(self._tmpfile_contents) f.flush() PathManager.rm(rm_file, foo="foo") # type: ignore class TestHTTPIO(unittest.TestCase): _remote_uri = "https://www.facebook.com" _filename = "facebook.html" _cache_dir: str = os.path.join(get_cache_dir(), __name__) @contextmanager def _patch_download(self) -> Generator[None, None, None]: def fake_download(url: str, dir: str, *, filename: str) -> str: dest = os.path.join(dir, filename) with open(dest, "w") as f: f.write("test") return dest with patch.object( file_io, "get_cache_dir", return_value=self._cache_dir ), patch.object(file_io, "download", side_effect=fake_download): yield def setUp(self) -> None: if os.path.exists(self._cache_dir): shutil.rmtree(self._cache_dir) os.makedirs(self._cache_dir, exist_ok=True) def test_get_local_path(self) -> None: with self._patch_download(): local_path = PathManager.get_local_path(self._remote_uri) self.assertTrue(os.path.exists(local_path)) self.assertTrue(os.path.isfile(local_path)) def test_open(self) -> None: with self._patch_download(): with PathManager.open(self._remote_uri, "rb") as f: self.assertTrue(os.path.exists(f.name)) self.assertTrue(os.path.isfile(f.name)) self.assertTrue(f.read() != "") def test_open_writes(self) -> None: # HTTPURLHandler does not support writing, only reading. with self.assertRaises(AssertionError): with PathManager.open(self._remote_uri, "w") as f: f.write("foobar") # pyre-ignore def test_open_new_path_manager(self) -> None: with self._patch_download(): path_manager = PathManagerBase() with self.assertRaises(OSError): # no handler registered f = path_manager.open(self._remote_uri, "rb") path_manager.register_handler(HTTPURLHandler()) with path_manager.open(self._remote_uri, "rb") as f: self.assertTrue(os.path.isfile(f.name)) self.assertTrue(f.read() != "") def test_bad_args(self) -> None: with self.assertRaises(NotImplementedError): PathManager.copy( self._remote_uri, self._remote_uri, foo="foo" # type: ignore ) with self.assertRaises(NotImplementedError): PathManager.exists(self._remote_uri, foo="foo") # type: ignore with self.assertRaises(ValueError): PathManager.get_local_path( self._remote_uri, foo="foo" # type: ignore ) with self.assertRaises(NotImplementedError): PathManager.isdir(self._remote_uri, foo="foo") # type: ignore with self.assertRaises(NotImplementedError): PathManager.isfile(self._remote_uri, foo="foo") # type: ignore with self.assertRaises(NotImplementedError): PathManager.ls(self._remote_uri, foo="foo") # type: ignore with self.assertRaises(NotImplementedError): PathManager.mkdirs(self._remote_uri, foo="foo") # type: ignore with self.assertRaises(ValueError): PathManager.open(self._remote_uri, foo="foo") # type: ignore with self.assertRaises(NotImplementedError): PathManager.rm(self._remote_uri, foo="foo") # type: ignore PathManager.set_strict_kwargs_checking(False) PathManager.get_local_path(self._remote_uri, foo="foo") # type: ignore f = PathManager.open(self._remote_uri, foo="foo") # type: ignore f.close() PathManager.set_strict_kwargs_checking(True) class TestLazyPath(unittest.TestCase): def test_materialize(self) -> None: f = MagicMock(return_value="test") x = LazyPath(f) f.assert_not_called() p = os.fspath(x) f.assert_called() self.assertEqual(p, "test") p = os.fspath(x) # should only be called once f.assert_called_once() self.assertEqual(p, "test") def test_join(self) -> None: f = MagicMock(return_value="test") x = LazyPath(f) p = os.path.join(x, "a.txt") f.assert_called_once() self.assertEqual(p, "test/a.txt") def test_getattr(self) -> None: x = LazyPath(lambda: "abc") with self.assertRaises(AttributeError): x.startswith("ab") _ = os.fspath(x) self.assertTrue(x.startswith("ab")) def test_PathManager(self) -> None: x = LazyPath(lambda: "./") output = PathManager.ls(x) # pyre-ignore output_gt = PathManager.ls("./") self.assertEqual(sorted(output), sorted(output_gt)) def test_getitem(self) -> None: x = LazyPath(lambda: "abc") with self.assertRaises(TypeError): x[0] _ = os.fspath(x) self.assertEqual(x[0], "a") class TestOneDrive(unittest.TestCase): _url = "https://1drv.ms/u/s!Aus8VCZ_C_33gQbJsUPTIj3rQu99" def test_one_drive_download(self) -> None: from fvcore.common.file_io import OneDrivePathHandler _direct_url = OneDrivePathHandler().create_one_drive_direct_download(self._url) _gt_url = ( "https://api.onedrive.com/v1.0/shares/u!aHR0cHM6Ly8xZHJ2Lm1zL3UvcyFBd" + "XM4VkNaX0NfMzNnUWJKc1VQVElqM3JRdTk5/root/content" ) self.assertEquals(_direct_url, _gt_url)
38.027273
87
0.622042
585c5cd744ff60ef8cf99817c42efe9069556e5c
60
py
Python
src/Learn/Cozy/LearnCSharp/K/Details/Script.py
zpublic/cozy
dde5f2bcf7482e2e5042f9e51266d9fd272e1456
[ "WTFPL" ]
48
2015-04-11T13:25:45.000Z
2022-03-28T08:27:40.000Z
src/Learn/Cozy/LearnCSharp/K/Details/Script.py
ToraiRei/cozy
c8197d9c6531f1864d6063ae149db53b669241f0
[ "WTFPL" ]
4
2016-04-06T09:30:57.000Z
2022-02-26T01:21:18.000Z
src/Learn/Cozy/LearnCSharp/K/Details/Script.py
ToraiRei/cozy
c8197d9c6531f1864d6063ae149db53b669241f0
[ "WTFPL" ]
33
2015-06-03T10:06:54.000Z
2020-12-15T00:50:28.000Z
import clr import sys def GetPaths(): return sys.path
10
19
0.7
da069719d3440989d504ba53a66ed6d130819412
15,928
py
Python
parlai/core/dict.py
kimiyoung/ParlAI
d7dbeb88e796593ec41a090ba69c6c7f78ad59d7
[ "BSD-3-Clause" ]
2
2017-09-30T23:23:44.000Z
2021-07-08T17:12:58.000Z
parlai/core/dict.py
kimiyoung/ParlAI
d7dbeb88e796593ec41a090ba69c6c7f78ad59d7
[ "BSD-3-Clause" ]
null
null
null
parlai/core/dict.py
kimiyoung/ParlAI
d7dbeb88e796593ec41a090ba69c6c7f78ad59d7
[ "BSD-3-Clause" ]
null
null
null
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. """Contains code for parsing and building a dictionary from text.""" from .agents import Agent from collections import defaultdict import copy import numpy as np import nltk import os def escape(s): """Replace potential special characters with escaped version. For example, newline => \\n and tab => \\t """ return s.replace('\n', '\\n').replace('\t', '\\t').replace('\r', '\\r') def unescape(s): """Revert escaped characters back to their special version. For example, \\n => newline and \\t => tab """ return s.replace('\\n', '\n').replace('\\t', '\t').replace('\\r', '\r') def find_ngrams(token_dict, text, n): """Breaks text into ngrams that appear in ``token_dict``.""" # base case if n <= 1: return text # tokens committed to output saved_tokens = [] # tokens remaining to be searched in sentence search_tokens = text[:] # tokens stored until next ngram found next_search = [] while len(search_tokens) >= n: ngram = ' '.join(search_tokens[:n]) if ngram in token_dict: # first, search previous unmatched words for smaller ngrams sub_n = min(len(next_search), n - 1) saved_tokens.extend(find_ngrams(token_dict, next_search, sub_n)) next_search.clear() # then add this ngram saved_tokens.append(ngram) # then pop this ngram from the remaining words to search search_tokens = search_tokens[n:] else: next_search.append(search_tokens.pop(0)) remainder = next_search + search_tokens sub_n = min(len(remainder), n - 1) saved_tokens.extend(find_ngrams(token_dict, remainder, sub_n)) return saved_tokens class DictionaryAgent(Agent): """Builds and/or loads a dictionary. The dictionary provides access to the frequency of each token, functions to translate sentences from tokens to their vectors (list of ints, each int is the index of a token in the dictionary) and back from vectors to tokenized text. """ default_lang = 'english' default_maxngram = -1 default_minfreq = 0 default_null = '__NULL__' default_start = '__START__' default_end = '__END__' default_unk = '__UNK__' @staticmethod def add_cmdline_args(argparser): dictionary = argparser.add_argument_group('Dictionary Arguments') dictionary.add_argument( '--dict-file', help='if set, the dictionary will automatically save to this path' ' during shutdown') dictionary.add_argument( '--dict-initpath', help='path to a saved dictionary to load tokens / counts from to ' 'seed the dictionary with initial tokens and/or frequencies') dictionary.add_argument( '--dict-language', default=DictionaryAgent.default_lang, help='sets language for the punkt sentence tokenizer') dictionary.add_argument( '--dict-max-ngram-size', type=int, default=DictionaryAgent.default_maxngram, help='looks for ngrams of up to this size. this is ignored when ' 'building the dictionary. note: this takes approximate ' 'runtime of len(sentence)^max_ngram_size') dictionary.add_argument( '--dict-minfreq', default=DictionaryAgent.default_minfreq, type=int, help='minimum frequency of words to include them in sorted dict') dictionary.add_argument( '--dict-nulltoken', default=DictionaryAgent.default_null, help='empty token, can be used for padding or just empty values') dictionary.add_argument( '--dict-starttoken', default=DictionaryAgent.default_start, help='token for starting sentence generation, if needed') dictionary.add_argument( '--dict-endtoken', default=DictionaryAgent.default_end, help='token for end of sentence markers, if needed') dictionary.add_argument( '--dict-unktoken', default=DictionaryAgent.default_unk, help='token to return for unavailable words') dictionary.add_argument( '--dict-maxexs', default=100000, type=int, help='max number of examples to build dict on') return dictionary def __init__(self, opt, shared=None): # initialize fields self.opt = copy.deepcopy(opt) self.minfreq = opt['dict_minfreq'] self.null_token = opt['dict_nulltoken'] self.end_token = opt['dict_endtoken'] self.unk_token = opt['dict_unktoken'] self.start_token = opt['dict_starttoken'] self.max_ngram_size = opt['dict_max_ngram_size'] if shared: self.freq = shared.get('freq', {}) self.tok2ind = shared.get('tok2ind', {}) self.ind2tok = shared.get('ind2tok', {}) else: self.freq = defaultdict(int) self.tok2ind = {} self.ind2tok = {} if self.null_token: self.tok2ind[self.null_token] = 0 self.ind2tok[0] = self.null_token if self.start_token: # set special start of sentence word token index = len(self.tok2ind) self.tok2ind[self.start_token] = index self.ind2tok[index] = self.start_token if self.end_token: # set special end of sentence word token index = len(self.tok2ind) self.tok2ind[self.end_token] = index self.ind2tok[index] = self.end_token if self.unk_token: # set special unknown word token index = len(self.tok2ind) self.tok2ind[self.unk_token] = index self.ind2tok[index] = self.unk_token if opt.get('dict_file') and os.path.isfile(opt['dict_file']): # load pre-existing dictionary self.load(opt['dict_file']) elif opt.get('dict_initpath'): # load seed dictionary self.load(opt['dict_initpath']) # initialize tokenizers st_path = 'tokenizers/punkt/{0}.pickle'.format(opt['dict_language']) try: self.sent_tok = nltk.data.load(st_path) except LookupError: nltk.download('punkt') self.sent_tok = nltk.data.load(st_path) self.word_tok = nltk.tokenize.treebank.TreebankWordTokenizer() if not shared: if self.null_token: # fix count for null token to one billion and three self.freq[self.null_token] = 1000000003 if self.start_token: # fix count for start of sentence token to one billion and two self.freq[self.start_token] = 1000000002 if self.end_token: # fix count for end of sentence token to one billion and one self.freq[self.end_token] = 1000000001 if self.unk_token: # fix count for unknown token to one billion self.freq[self.unk_token] = 1000000000 if opt.get('dict_file'): self.save_path = opt['dict_file'] def __contains__(self, key): """If key is an int, returns whether the key is in the indices. If key is a str, return if the token is in the dict of tokens. """ if type(key) == int: return key in self.ind2tok elif type(key) == str: return key in self.tok2ind def __getitem__(self, key): """If key is an int, returns the corresponding token. If it does not exist, return the unknown token. If key is a str, return the token's index. If the token is not in the dictionary, return the index of the unknown token. If there is no unknown token, return ``None``. """ if type(key) == int: # return token from index, or unk_token return self.ind2tok.get(key, self.unk_token) elif type(key) == str: # return index from token, or unk_token's index, or None return self.tok2ind.get(key, self.tok2ind.get(self.unk_token, None)) def __len__(self): return len(self.tok2ind) def __setitem__(self, key, value): """If the key is not in the dictionary, add it to the dictionary and set its frequency to value. """ key = str(key) self.freq[key] = int(value) if key not in self.tok2ind: index = len(self.tok2ind) self.tok2ind[key] = index self.ind2tok[index] = key def freqs(self): return self.freq def nltk_tokenize(self, text, building=False): """Uses nltk-trained PunktTokenizer for sentence tokenization and Treebank Word Tokenizer for tokenizing words within sentences. """ return (token for sent in self.sent_tok.tokenize(text) for token in self.word_tok.tokenize(sent)) def split_tokenize(self, text): """Splits tokens based on whitespace after adding whitespace around punctuation. """ return (text.replace('.', ' . ').replace(',', ' , ') .replace('!', ' ! ').replace('?', ' ? ') .replace('. . .', '...').split()) def tokenize(self, text, tokenizer='split', building=False): """Returns a sequence of tokens from the iterable.""" if tokenizer == 'split': word_tokens = self.split_tokenize(text) elif tokenizer == 'nltk': word_tokens = self.nltk_tokenize(text) else: raise RuntimeError( 'tokenizer type {} not yet supported'.format(tokenizer)) if not building and self.max_ngram_size > 1: # search for ngrams during parse-time # TODO(ahm): support build-time ngrams using word2vec heuristic? word_tokens = find_ngrams(self.tok2ind, word_tokens, self.max_ngram_size) return word_tokens def add_to_dict(self, tokens): """ Builds dictionary from the list of provided tokens.""" for token in tokens: self.freq[token] += 1 if token not in self.tok2ind: index = len(self.tok2ind) self.tok2ind[token] = index self.ind2tok[index] = token def remove_tail(self, min_freq): to_remove = [] for token, freq in self.freq.items(): if freq < min_freq: # queue up removals since can't mutate dict during iteration to_remove.append(token) # other dicts can be modified as we go idx = self.tok2ind.pop(token) del self.ind2tok[idx] for token in to_remove: del self.freq[token] def load(self, filename): """Load pre-existing dictionary in 'token[<TAB>count]' format. Initialize counts from other dictionary, or 0 if they aren't included. """ print('Dictionary: loading dictionary from {}'.format( filename)) with open(filename) as read: for line in read: split = line.strip().split('\t') token = unescape(split[0]) cnt = int(split[1]) if len(split) > 1 else 0 self.freq[token] = cnt if token not in self.tok2ind: index = len(self.tok2ind) self.tok2ind[token] = index self.ind2tok[index] = token print('[ num words = %d ]' % len(self)) def save(self, filename=None, append=False, sort=True): """Save dictionary to file. Format is 'token<TAB>count' for every token in the dictionary, sorted by count with the most frequent words first. If ``append`` (default ``False``) is set to ``True``, appends instead of overwriting. If ``sort`` (default ``True``), then first sort the dictionary before saving. """ filename = self.opt['dict_file'] if filename is None else filename print('Dictionary: saving dictionary to {}'.format(filename)) if sort: self.sort() with open(filename, 'a' if append else 'w') as write: for i in range(len(self.ind2tok)): tok = self.ind2tok[i] cnt = self.freq[tok] write.write('{tok}\t{cnt}\n'.format(tok=escape(tok), cnt=cnt)) def sort(self): """Sorts the dictionary, so that the elements with the lowest index have the highest counts. This reindexes the dictionary according to the sorted frequencies, breaking ties alphabetically by token. """ # sort first by count, then alphabetically self.remove_tail(self.minfreq) sorted_pairs = sorted(self.freq.items(), key=lambda x: (-x[1], x[0])) new_tok2ind = {} new_ind2tok = {} for i, (tok, _) in enumerate(sorted_pairs): new_tok2ind[tok] = i new_ind2tok[i] = tok self.tok2ind = new_tok2ind self.ind2tok = new_ind2tok return sorted_pairs def parse(self, txt_or_vec, vec_type=list): """Convenience function for parsing either text or vectors of indices. ``vec_type`` is the type of the returned vector if the input is a string. """ if type(txt_or_vec) == str: res = self.txt2vec(txt_or_vec, vec_type) assert type(res) == vec_type return res else: return self.vec2txt(txt_or_vec) def txt2vec(self, text, vec_type=list): """Converts a string to a vector (list of ints). First runs a sentence tokenizer, then a word tokenizer. ``vec_type`` is the type of the returned vector if the input is a string. """ if vec_type == np.ndarray: res = np.fromiter( (self[token] for token in self.tokenize(str(text))), np.int ) elif vec_type == list or vec_type == tuple or vec_type == set: res = vec_type((self[token] for token in self.tokenize(str(text)))) else: raise RuntimeError('Type {} not supported by dict'.format(vec_type)) assert type(res) == vec_type return res def vec2txt(self, vector, delimiter=' '): """Converts a vector (iterable of ints) into a string, with each token separated by the delimiter (default ``' '``). """ return delimiter.join(self[int(idx)] for idx in vector) def act(self): """Add any words passed in the 'text' field of the observation to this dictionary. """ for source in ([self.observation.get('text')], self.observation.get('labels')): if source: for text in source: if text: self.add_to_dict(self.tokenize(text)) return {'id': 'Dictionary'} def share(self): shared = {} shared['freq'] = self.freq shared['tok2ind'] = self.tok2ind shared['ind2tok'] = self.ind2tok shared['opt'] = self.opt shared['class'] = type(self) return shared def shutdown(self): """Save on shutdown if ``save_path`` is set.""" if hasattr(self, 'save_path'): self.save(self.save_path) def __str__(self): return str(self.freq)
38.754258
85
0.587456
712d3e7be4eb892f2ffa469267a9373b98904d8d
7,734
py
Python
viadot/tasks/sharepoint.py
angelika233/viadot
99a4c5b622ad099a44ab014a47ba932a747c0ae6
[ "MIT" ]
null
null
null
viadot/tasks/sharepoint.py
angelika233/viadot
99a4c5b622ad099a44ab014a47ba932a747c0ae6
[ "MIT" ]
null
null
null
viadot/tasks/sharepoint.py
angelika233/viadot
99a4c5b622ad099a44ab014a47ba932a747c0ae6
[ "MIT" ]
null
null
null
from typing import List import os import copy import json import pandas as pd from prefect import Task from prefect.utilities.tasks import defaults_from_attrs from prefect.utilities import logging from prefect.tasks.secrets import PrefectSecret from ..exceptions import ValidationError from ..sources import Sharepoint from .azure_key_vault import AzureKeyVaultSecret logger = logging.get_logger() class SharepointToDF(Task): """ Task for converting data from Sharepoint excel file to a pandas DataFrame. Args: path_to_file (str): Path to Excel file. url_to_file (str): Link to a file on Sharepoint. (e.g : https://{tenant_name}.sharepoint.com/sites/{folder}/Shared%20Documents/Dashboard/file). Defaults to None. nrows (int, optional): Number of rows to read at a time. Defaults to 50000. sheet_number (int): Sheet number to be extracted from file. Counting from 0, if None all sheets are axtracted. Defaults to None. validate_excel_file (bool, optional): Check if columns in separate sheets are the same. Defaults to False. if_empty (str, optional): What to do if query returns no data. Defaults to "warn". Returns: pd.DataFrame: Pandas data frame """ def __init__( self, path_to_file: str = None, url_to_file: str = None, nrows: int = 50000, sheet_number: int = None, validate_excel_file: bool = False, if_empty: str = "warn", *args, **kwargs, ): self.if_empty = if_empty self.path_to_file = path_to_file self.url_to_file = url_to_file self.nrows = nrows self.sheet_number = sheet_number self.validate_excel_file = validate_excel_file super().__init__( name="sharepoint_to_df", *args, **kwargs, ) def __call__(self): """Download Sharepoint data to a DF""" super().__call__(self) def check_column_names( self, df_header: List[str] = None, header_to_compare: List[str] = None ) -> List[str]: """ Check if column names in sheets are the same. Args: df_header (List[str]): Header of df from excel sheet. header_to_compare (List[str]): Header of df from previous excel sheet. Returns: list: list of columns """ df_header_list = df_header.columns.tolist() if header_to_compare is not None: if df_header_list != header_to_compare: raise ValidationError("Columns in sheets are different") return df_header_list def df_replace_special_chars(self, df: pd.DataFrame): """ Replace "\n" and "\t" with "". Args: df (pd.DataFrame): Pandas data frame to replace characters. Returns: df (pd.DataFrame): Pandas data frame """ return df.replace(r"\n|\t", "", regex=True) def split_sheet( self, sheetname: str = None, nrows: int = None, chunks: List[pd.DataFrame] = None, **kwargs, ) -> List[pd.DataFrame]: """ Split sheet by chunks. Args: sheetname (str): The sheet on which we iterate. nrows (int): Number of rows to read at a time. chunks(List[pd.DataFrame]): List of data in chunks. Returns: List[pd.DataFrame]: List of data frames """ skiprows = 1 logger.info(f"Worksheet: {sheetname}") temp_chunks = copy.deepcopy(chunks) i_chunk = 0 while True: df_chunk = pd.read_excel( self.path_to_file, sheet_name=sheetname, nrows=nrows, skiprows=skiprows, header=None, **kwargs, ) skiprows += nrows # When there is no data, we know we can break out of the loop. if df_chunk.empty: break else: logger.debug(f" - chunk {i_chunk+1} ({df_chunk.shape[0]} rows)") df_chunk["sheet_name"] = sheetname temp_chunks.append(df_chunk) i_chunk += 1 return temp_chunks @defaults_from_attrs( "path_to_file", "url_to_file", "nrows", "sheet_number", "validate_excel_file", ) def run( self, path_to_file: str = None, url_to_file: str = None, nrows: int = 50000, validate_excel_file: bool = False, sheet_number: int = None, credentials_secret: str = None, vault_name: str = None, **kwargs, ) -> None: """ Run Task ExcelToDF. Args: path_to_file (str): Path to Excel file. Defaults to None. url_to_file (str): Link to a file on Sharepoint. Defaults to None. nrows (int, optional): Number of rows to read at a time. Defaults to 50000. sheet_number (int): Sheet number to be extracted from file. Counting from 0, if None all sheets are axtracted. Defaults to None. validate_excel_file (bool, optional): Check if columns in separate sheets are the same. Defaults to False. credentials_secret (str, optional): The name of the Azure Key Vault secret containing a dictionary with ACCOUNT_NAME and Service Principal credentials (TENANT_ID, CLIENT_ID, CLIENT_SECRET). Defaults to None. vault_name (str, optional): The name of the vault from which to obtain the secret. Defaults to None. Returns: pd.DataFrame: Pandas data frame """ if not credentials_secret: # attempt to read a default for the service principal secret name try: credentials_secret = PrefectSecret("SHAREPOINT_KV").run() except ValueError: pass if credentials_secret: credentials_str = AzureKeyVaultSecret( credentials_secret, vault_name=vault_name ).run() credentials = json.loads(credentials_str) self.path_to_file = path_to_file self.url_to_file = url_to_file path_to_file = os.path.basename(self.path_to_file) self.sheet_number = sheet_number s = Sharepoint(download_from_path=self.url_to_file, credentials=credentials) s.download_file(download_to_path=path_to_file) self.nrows = nrows excel = pd.ExcelFile(self.path_to_file) if self.sheet_number is not None: sheet_names_list = [excel.sheet_names[self.sheet_number]] else: sheet_names_list = excel.sheet_names header_to_compare = None chunks = [] for sheetname in sheet_names_list: df_header = pd.read_excel(self.path_to_file, sheet_name=sheetname, nrows=0) if validate_excel_file: header_to_compare = self.check_column_names( df_header, header_to_compare ) chunks = self.split_sheet(sheetname, self.nrows, chunks) df_chunks = pd.concat(chunks) # Rename the columns to concatenate the chunks with the header. columns = {i: col for i, col in enumerate(df_header.columns.tolist())} last_column = len(columns) columns[last_column] = "sheet_name" df_chunks.rename(columns=columns, inplace=True) df = pd.concat([df_header, df_chunks]) df = self.df_replace_special_chars(df) self.logger.info(f"Successfully converted data to a DataFrame.") return df
34.070485
140
0.602793
34f6c243d7a9fc4e7afb333e59e2514c4e920527
839
py
Python
test_news.py
dagolde1/Ella
1c5e33dadf6c053412ffbf56a44b6bcb987c7e2f
[ "MIT" ]
null
null
null
test_news.py
dagolde1/Ella
1c5e33dadf6c053412ffbf56a44b6bcb987c7e2f
[ "MIT" ]
null
null
null
test_news.py
dagolde1/Ella
1c5e33dadf6c053412ffbf56a44b6bcb987c7e2f
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import unittest from maria import testutils, diagnose from . import news class TestGmailPlugin(unittest.TestCase): def setUp(self): self.plugin = testutils.get_plugin_instance( news.NewsPlugin) def test_is_valid_method(self): self.assertTrue(self.plugin.is_valid( "Find me some of the top news stories.")) self.assertFalse(self.plugin.is_valid("What time is it?")) @unittest.skipIf(not diagnose.check_network_connection(), "No internet connection") def test_handle_method(self): mic = testutils.TestMic(inputs=["No."]) self.plugin.handle("Find me some of the top news stories.", mic) self.assertGreater(len(mic.outputs), 1) self.assertIn("top headlines", mic.outputs[1])
34.958333
73
0.64124
5d3fdbd1fd563cefa7d8e2dcee36e1f921876eff
1,714
py
Python
setup.py
wrensuess/prospector
08173f84ddfc2b031c78822344fc821778d35bae
[ "MIT" ]
94
2016-10-12T19:29:58.000Z
2022-03-24T13:25:39.000Z
setup.py
wrensuess/prospector
08173f84ddfc2b031c78822344fc821778d35bae
[ "MIT" ]
168
2016-04-15T20:01:34.000Z
2022-03-31T21:03:07.000Z
setup.py
wrensuess/prospector
08173f84ddfc2b031c78822344fc821778d35bae
[ "MIT" ]
53
2016-07-14T07:19:11.000Z
2022-03-21T03:10:28.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import re import glob #import subprocess try: from setuptools import setup setup except ImportError: from distutils.core import setup setup #githash = subprocess.check_output(["git", "log", "--format=%h"], universal_newlines=True).split('\n')[0] vers = "1.0.0" githash = "" with open('prospect/_version.py', "w") as f: f.write('__version__ = "{}"\n'.format(vers)) f.write('__githash__ = "{}"\n'.format(githash)) setup( name="astro-prospector", version=vers, project_urls={"Source repo": "https://github.com/bd-j/prospector", "Documentation": "https://prospect.readthedocs.io"}, author="Ben Johnson", author_email="benjamin.johnson@cfa.harvard.edu", classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Science/Research", "Programming Language :: Python", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Topic :: Scientific/Engineering :: Astronomy"], packages=["prospect", "prospect.models", "prospect.likelihood", "prospect.fitting", "prospect.sources", "prospect.io", "prospect.plotting", "prospect.utils"], license="MIT", description="Stellar Population Inference", long_description=open("README.md").read(), long_description_content_type="text/markdown", package_data={"": ["README.md", "LICENSE"]}, scripts=glob.glob("scripts/*.py"), include_package_data=True, install_requires=["numpy", "h5py"], )
32.339623
105
0.603851
0841fb3303a6e4f23a006fdcaac99cfb873f00ea
1,743
py
Python
petra_viewer/widgets/tests_browser.py
yamedvedya/data_viewer
c6238b71edcf0178ebe8ab8f9bf6e56e41cd4916
[ "MIT" ]
null
null
null
petra_viewer/widgets/tests_browser.py
yamedvedya/data_viewer
c6238b71edcf0178ebe8ab8f9bf6e56e41cd4916
[ "MIT" ]
null
null
null
petra_viewer/widgets/tests_browser.py
yamedvedya/data_viewer
c6238b71edcf0178ebe8ab8f9bf6e56e41cd4916
[ "MIT" ]
null
null
null
# Created by matveyev at 09.11.2021 from PyQt5 import QtWidgets, QtCore from petra_viewer.widgets.abstract_widget import AbstractWidget from petra_viewer.data_sources.test_datasets.test_datasets import SardanaPeak1, SardanaPeak2, HeavySardana, \ ASAPO2DPeak, ASAPO3DPeak, ASAPO4DPeak, BeamView from petra_viewer.gui.tests_browser_ui import Ui_TestsBrowser WIDGET_NAME = 'TestsBrowser' # ---------------------------------------------------------------------- class TestsBrowser(AbstractWidget): test_selected = QtCore.pyqtSignal(str) def __init__(self, parent): """ """ super(TestsBrowser, self).__init__(parent) self._ui = Ui_TestsBrowser() self._ui.setupUi(self) self._ui.tb_sets.setHorizontalHeaderLabels(['Name', 'Dim', 'Size']) self._ui.tb_sets.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) self._ui.tb_sets.setColumnWidth(1, 50) self.test_classes = [SardanaPeak1, SardanaPeak2, HeavySardana, ASAPO2DPeak, ASAPO3DPeak, ASAPO4DPeak, BeamView] self._ui.tb_sets.setRowCount(len(self.test_classes)) for ind, test_class in enumerate(self.test_classes): name, dims, size = test_class.get_info(test_class) self._ui.tb_sets.setItem(ind, 0, QtWidgets.QTableWidgetItem(f'{name}')) self._ui.tb_sets.setItem(ind, 1, QtWidgets.QTableWidgetItem(f'{dims}')) self._ui.tb_sets.setItem(ind, 2, QtWidgets.QTableWidgetItem(f'{size}')) self._ui.tb_sets.itemDoubleClicked.connect(self._add_test) # ---------------------------------------------------------------------- def _add_test(self, item): self.test_selected.emit(self.test_classes[item.row()].my_name)
37.891304
119
0.658635
25750ef68e1bfdee76890b4da5a4b1c328a84783
651
py
Python
pandas_ta/overlap/__init__.py
cloudlakecho/pandas-ta
f361621d614cd4ca67800c99be27cc908c0fce96
[ "MIT" ]
1
2020-06-18T10:19:12.000Z
2020-06-18T10:19:12.000Z
pandas_ta/overlap/__init__.py
ajmal017/pandas-ta
98099f71de7c4a8b293b8de4dd62fa2399e5a12a
[ "MIT" ]
null
null
null
pandas_ta/overlap/__init__.py
ajmal017/pandas-ta
98099f71de7c4a8b293b8de4dd62fa2399e5a12a
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from .dema import dema from .ema import ema from .fwma import fwma from .hl2 import hl2 from .hlc3 import hlc3 from .hma import hma from .kama import kama from .ichimoku import ichimoku from .linreg import linreg from .midpoint import midpoint from .midprice import midprice from .ohlc4 import ohlc4 from .pwma import pwma from .rma import rma from .sinwma import sinwma from .sma import sma from .supertrend import supertrend from .swma import swma from .t3 import t3 from .tema import tema from .trima import trima from .vwap import vwap from .vwma import vwma from .wcp import wcp from .wma import wma from .zlma import zlma
24.111111
34
0.780338
49d98cd20907d160bb3e593d76a81b51eb9c19e9
923
py
Python
spira/param/field/typed_bool.py
cloudcalvin/spira
2dcaef188f2bc8c3839e1b5ff0be027e0cd4908c
[ "MIT" ]
null
null
null
spira/param/field/typed_bool.py
cloudcalvin/spira
2dcaef188f2bc8c3839e1b5ff0be027e0cd4908c
[ "MIT" ]
1
2021-10-17T10:18:04.000Z
2021-10-17T10:18:04.000Z
spira/param/field/typed_bool.py
cloudcalvin/spira
2dcaef188f2bc8c3839e1b5ff0be027e0cd4908c
[ "MIT" ]
null
null
null
from spira.core.descriptor import DataFieldDescriptor class BoolField(DataFieldDescriptor): def __init__(self, default=False, **kwargs): if default is None: kwargs['default'] = None else: kwargs['default'] = bool(default) super().__init__(**kwargs) def __set__(self, obj, value): if isinstance(value, bool): obj.__store__[self.__name__] = value else: raise TypeError("Invalid type in setting value " + "of {} (expected {}): {}" .format(self.__class_, type(value))) def get_stored_value(self, obj): value = obj.__store__[self.__name__] return value # def __repr__(self): # value = obj.__store__[self.__name__] # return ("[SPiRA: Bool] (value {})").format(value) # def __str__(self): # return self.__repr__()
27.147059
64
0.561213
be062af74b88f1748abb23e09b1cfd3eb91089ed
3,208
py
Python
zeppelin_viz/nvd3/charts/multiBarChart.py
bernhard-42/Zeppelin-Visualizations
f95eb8b948e71dd0266aacac6ac5be480a6dc656
[ "Apache-2.0" ]
2
2017-04-06T10:53:22.000Z
2017-07-12T09:32:50.000Z
zeppelin_viz/nvd3/charts/multiBarChart.py
bernhard-42/Zeppelin-Visualizations
f95eb8b948e71dd0266aacac6ac5be480a6dc656
[ "Apache-2.0" ]
1
2019-01-23T13:48:36.000Z
2019-01-23T13:48:36.000Z
zeppelin_viz/nvd3/charts/multiBarChart.py
bernhard-42/Zeppelin-Visualizations
f95eb8b948e71dd0266aacac6ac5be480a6dc656
[ "Apache-2.0" ]
2
2017-03-18T13:16:17.000Z
2018-07-03T12:06:37.000Z
# Copyright 2017 Bernhard Walter # # 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 ..nvd3_chart import Nvd3Chart import pandas as pd class MultiBarChart(Nvd3Chart): funcName = "multiBarChart" funcBody = """ function(session, object) { chart = nv.models.multiBarChart() .margin({bottom: 50, left: 50}) .groupSpacing(0.1) .reduceXTicks(false) .staggerLabels(true); chart.xAxis.showMaxMin(false) .tickFormat(d3.format(',.1f')) chart.yAxis.showMaxMin(false) .tickFormat(d3.format(',.1f')) session.__functions.makeChart(session, object, chart); } """ def __init__(self, nvd3Functions): super(self.__class__, self).__init__(nvd3Functions) def convert(self, data, key, values): """ Convert data to MultiBarChart format Example: >>> x = np.linspace(0, 4*np.pi, 10) df = pd.DataFrame({"X":x*100, "Sin":np.sin(x), "Cos":np.cos(x), "ArcTan":np.arctan(x-2*np.pi)/3}) >>> mb = nv.multiBarChart() >>> data = mb.convert(l1_df, "X", ["Sin", "Cos", "ArcTan"], keyAttributes) >>> config={"height":400, "width": 1000, "focusEnable": False, "color":nv.c10()[::2], "yAxis": {"axisLabel":"F(X)", "tickFormat":",.1f"}, "xAxis":{"axisLabel":"X", "tickFormat":",.1f"}} >>> mb.plot({"data":data, "config":config}) Parameters ---------- data : dict of lists or Pandas DataFrame If the paramter is a dict, each keys represent the name of the dataset in the list { 'A': ( 1, 2, 3), 'B': ('C', 'T', 'D' } or a pandas DataFrame, each column representing a dataset A B 0 1 C 1 2 T 2 3 D key : string Column name or dict key for values to be used for the x axis values : list of strings Column names or dict keys for values to be used for the bars Returns ------- dict The input data converted to the specific nvd3 chart format """ df = data if isinstance(data, pd.DataFrame) else pd.DataFrame(data) nvd3Data = [] for i in range(len(values)): nvd3Data.append({"key":values[i], "values":df.loc[:,[key, values[i]]].rename(str,{key:"x", values[i]:"y"}).to_dict("records")}) return nvd3Data
34.869565
139
0.539589
18fe678159fc47222a2a81d7cc0ce2aecfb8d2bc
1,130
py
Python
tensorflow_datasets/image_classification/imagenet_v2_test.py
shashwat9kumar/datasets
99b055408025f8e934fcbb0fc054488aa087ebfb
[ "Apache-2.0" ]
3,380
2018-09-11T05:03:31.000Z
2022-03-31T20:04:57.000Z
tensorflow_datasets/image_classification/imagenet_v2_test.py
shashwat9kumar/datasets
99b055408025f8e934fcbb0fc054488aa087ebfb
[ "Apache-2.0" ]
3,142
2018-09-14T10:09:00.000Z
2022-03-31T18:25:44.000Z
tensorflow_datasets/image_classification/imagenet_v2_test.py
shashwat9kumar/datasets
99b055408025f8e934fcbb0fc054488aa087ebfb
[ "Apache-2.0" ]
1,438
2018-09-16T13:58:22.000Z
2022-03-31T11:19:54.000Z
# coding=utf-8 # Copyright 2021 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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. """Tests for ImageNet-v2 image classification dataset.""" from tensorflow_datasets.image_classification import imagenet_v2 import tensorflow_datasets.public_api as tfds class ImagenetV2Test(tfds.testing.DatasetBuilderTestCase): BUILDER_CONFIG_NAMES_TO_TEST = [ 'matched-frequency', 'threshold-0.7', 'topimages' ] DATASET_CLASS = imagenet_v2.ImagenetV2 SPLITS = { 'test': 10, # Number of fake test examples. } DL_EXTRACT_RESULT = '' if __name__ == '__main__': tfds.testing.test_main()
30.540541
74
0.754867
68926fffa271f608a7904741f11ab309f11bebf9
4,590
py
Python
calendarserver/tools/test/test_resources.py
backwardn/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
[ "Apache-2.0" ]
462
2016-08-14T17:43:24.000Z
2022-03-17T07:38:16.000Z
calendarserver/tools/test/test_resources.py
backwardn/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
[ "Apache-2.0" ]
72
2016-09-01T23:19:35.000Z
2020-02-05T02:09:26.000Z
calendarserver/tools/test/test_resources.py
backwardn/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
[ "Apache-2.0" ]
171
2016-08-16T03:50:30.000Z
2022-03-26T11:49:55.000Z
## # Copyright (c) 2005-2017 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless 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 twisted.internet.defer import inlineCallbacks from calendarserver.tools.resources import migrateResources from twistedcaldav.test.util import StoreTestCase from txdav.who.test.support import InMemoryDirectoryService from twext.who.directory import DirectoryRecord from txdav.who.idirectory import RecordType as CalRecordType from txdav.who.directory import CalendarDirectoryRecordMixin class TestRecord(DirectoryRecord, CalendarDirectoryRecordMixin): pass class MigrateResourcesTest(StoreTestCase): @inlineCallbacks def setUp(self): yield super(MigrateResourcesTest, self).setUp() self.store = self.storeUnderTest() self.sourceService = InMemoryDirectoryService(None) fieldName = self.sourceService.fieldName records = ( TestRecord( self.sourceService, { fieldName.uid: u"location1", fieldName.shortNames: (u"loc1",), fieldName.recordType: CalRecordType.location, } ), TestRecord( self.sourceService, { fieldName.uid: u"location2", fieldName.shortNames: (u"loc2",), fieldName.recordType: CalRecordType.location, } ), TestRecord( self.sourceService, { fieldName.uid: u"resource1", fieldName.shortNames: (u"res1",), fieldName.recordType: CalRecordType.resource, } ), ) yield self.sourceService.updateRecords(records, create=True) @inlineCallbacks def test_migrateResources(self): # Record location1 has not been migrated record = yield self.directory.recordWithUID(u"location1") self.assertEquals(record, None) # Migrate location1, location2, and resource1 yield migrateResources(self.sourceService, self.directory) record = yield self.directory.recordWithUID(u"location1") self.assertEquals(record.uid, u"location1") self.assertEquals(record.shortNames[0], u"loc1") record = yield self.directory.recordWithUID(u"location2") self.assertEquals(record.uid, u"location2") self.assertEquals(record.shortNames[0], u"loc2") record = yield self.directory.recordWithUID(u"resource1") self.assertEquals(record.uid, u"resource1") self.assertEquals(record.shortNames[0], u"res1") # Add a new location to the sourceService, and modify an existing # location fieldName = self.sourceService.fieldName newRecords = ( TestRecord( self.sourceService, { fieldName.uid: u"location1", fieldName.shortNames: (u"newloc1",), fieldName.recordType: CalRecordType.location, } ), TestRecord( self.sourceService, { fieldName.uid: u"location3", fieldName.shortNames: (u"loc3",), fieldName.recordType: CalRecordType.location, } ), ) yield self.sourceService.updateRecords(newRecords, create=True) yield migrateResources(self.sourceService, self.directory) # Ensure an existing record does not get migrated again; verified by # seeing if shortNames changed, which they should not: record = yield self.directory.recordWithUID(u"location1") self.assertEquals(record.uid, u"location1") self.assertEquals(record.shortNames[0], u"loc1") # Ensure new record does get migrated record = yield self.directory.recordWithUID(u"location3") self.assertEquals(record.uid, u"location3") self.assertEquals(record.shortNames[0], u"loc3")
37.622951
76
0.627669
e89af5eb1196d29385b20c41450a6b370532d786
23,609
py
Python
mmdet/demos/visualization_tools.py
yizhe-ang/MMSceneGraph
d4daec3d7930d6fe1efe75b9c0a265c8be0b70ba
[ "MIT" ]
24
2021-10-14T03:28:28.000Z
2022-03-29T09:30:04.000Z
mmdet/demos/visualization_tools.py
yizhe-ang/MMSceneGraph
d4daec3d7930d6fe1efe75b9c0a265c8be0b70ba
[ "MIT" ]
4
2021-12-14T15:04:49.000Z
2022-02-19T09:54:42.000Z
mmdet/demos/visualization_tools.py
yizhe-ang/MMSceneGraph
d4daec3d7930d6fe1efe75b9c0a265c8be0b70ba
[ "MIT" ]
4
2021-10-31T11:23:06.000Z
2021-12-17T06:38:50.000Z
# --------------------------------------------------------------- # visualization.py # Set-up time: 2020/11/4 20:57 # Copyright (c) 2020 ICT # Licensed under The MIT License [see LICENSE for details] # Written by Kenneth-Wong (Wenbin-Wang) @ VIPL.ICT # Contact: wenbin.wang@vipl.ict.ac.cn [OR] nkwangwenbin@gmail.com # --------------------------------------------------------------- import cv2 import random import numpy as np from pandas import DataFrame import pandas as pd from graphviz import Digraph import webcolors import pprint import math from scipy.stats import norm from color_histogram.core.hist_3d import Hist3D import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import torchtext # 0. install torchtext==0.2.3 (pip install torchtext==0.2.3) from torch.nn.functional import cosine_similarity from collections import Counter import pcl # cd python-pcl -> python setup.py build-ext -i -> python setup.py install import os.path as osp import os fasttext = torchtext.vocab.FastText() _GRAY = (218, 227, 218) _GREEN = (18, 127, 15) _WHITE = (255, 255, 255) colorlist = [(random.randint(0, 230), random.randint(0, 230), random.randint(0, 230)) for i in range(10000)] class SameNodeDetection(object): def __init__(self): self.compare_all = False self.class_weight = 10.0 / 20.0 self.pose_weight = 8.0 / 20.0 self.color_weight = 2.0 / 20.0 def compare_class(self, curr_cls, prev_cls, cls_score): score = 0. score = cosine_similarity(fasttext.vectors[fasttext.stoi[curr_cls]].cuda(), fasttext.vectors[fasttext.stoi[prev_cls]].cuda(), dim=0).cpu().item() score = (score + 1) / 2. return score def compare_position(self, curr_mean, curr_var, prev_mean, prev_var, prev_pt_num, new_pt_num): I_x, I_y, I_z = TFCO.check_distance(curr_mean, curr_var, prev_mean, prev_var) # score = (I_x * I_y * I_z) score = (I_x / 3.0) + (I_y / 3.0) + (I_z / 3.0) score = float(score) return score def compare_color(self, curr_hist, prev_hist): curr_rgb = webcolors.name_to_rgb(curr_hist[0][1]) prev_rgb = webcolors.name_to_rgb(prev_hist[0][1]) dist = np.sqrt(np.sum(np.power(np.subtract(curr_rgb, prev_rgb), 2))) / (255 * np.sqrt(3)) score = 1 - dist return score def node_update(self, window_3d_pts, global_node, curr_mean, curr_var, curr_cls, cls_score, object_classes): # temporary do not use the curr_color_hist try: new_pt_num = len(window_3d_pts) global_node_num = len(global_node) #print(global_node_num) score = [] score_pose = [] w1, w2, w3 = self.class_weight, self.pose_weight, self.color_weight # print("current object : {cls:3}".format(cls=curr_cls[0])) for i in range(global_node_num): #import pdb #pdb.set_trace() prev_cls = object_classes[global_node.iloc[i]["class"]] prev_mean, prev_var, prev_pt_num = global_node.iloc[i]["mean"], global_node.iloc[i]["var"], \ global_node.iloc[i]["pt_num"] prev_color_hist = global_node.iloc[i]["color_hist"] cls_sc = self.compare_class(curr_cls, prev_cls, cls_score) pos_sc = self.compare_position(curr_mean, curr_var, prev_mean, prev_var, prev_pt_num, new_pt_num) # col_sc = self.compare_color(curr_color_hist, prev_color_hist) # print("class_score {cls_score:3.2f}".format(cls_score=cls_sc)) # print("pose_score {pos_score:3.2f}".format(pos_score=pos_sc)) # print("color_score {col_score:3.2f}".format(col_score=col_sc)) tot_sc = (w1 * cls_sc) + (w2 * pos_sc) + w3 # (w3 * col_sc) # print("total_score {tot_score:3.2f}".format(tot_score=tot_sc)) score.append(tot_sc) # score_pose.append(pos_sc) node_score = max(score) print("node_score {score:3.4f}".format(score=node_score)) max_score_index = score.index(max(score)) # node_score_pose = score_pose[max_score_index] # print("node_score_pose {score_pose:3.2f}".format(score_pose=node_score_pose)) return node_score, max_score_index except: return 0, 0 class FindObjectClassColor(object): def __init__(self): self.power = 2 def get_class_string(self, class_index, score, dataset): class_text = dataset[class_index] if dataset is not None else \ 'id{:d}'.format(class_index) return class_text + ' {:0.2f}'.format(score).lstrip('0') def closest_colour(self, requested_colour): min_colours = {} for key, name in webcolors.CSS3_HEX_TO_NAMES.items(): r_c, g_c, b_c = webcolors.hex_to_rgb(key) rd = (r_c - requested_colour[0]) ** self.power gd = (g_c - requested_colour[1]) ** self.power bd = (b_c - requested_colour[2]) ** self.power min_colours[(rd + gd + bd)] = name return min_colours[min(min_colours.keys())] def get_colour_name(self, requested_colour): try: closest_name = actual_name = webcolors.rgb_to_name(requested_colour) except ValueError: closest_name = self.closest_colour(requested_colour) actual_name = None return actual_name, closest_name class CompareObjects(object): def __init__(self): self.meter = 5000. self.th_x = 0.112 self.th_y = 0.112 self.th_z = 0.112 def check_distance(self, x, curr_var, mean, var): Z_x = (x[0] - mean[0]) / self.meter Z_y = (x[1] - mean[1]) / self.meter Z_z = (x[2] - mean[2]) / self.meter # Z_x = (x[0]-mean[0])/np.sqrt(curr_var[0]) # Z_y = (x[1]-mean[1])/np.sqrt(curr_var[1]) # Z_z = (x[2]-mean[2])/np.sqrt(curr_var[2]) # In Standardized normal gaussian distribution # Threshold : 0.9 --> -1.65 < Z < 1.65 # : 0.8 --> -1.29 < Z < 1.29 # : 0.7 --> -1.04 < Z < 1.04 # : 0.6 --> -0.845 < Z < 0.845 # : 0.5 --> -0.675 < Z < 0.675 # : 0.4 --> -0.53 < Z < 0.53 # print(" pos {pos_x:3.2f} {pose_y:3.2f} {pose_z:3.2f}".format(pos_x=Z_x, pose_y=Z_y, pose_z=Z_z)) # print("pos_y {pos_y:3.2f}".format(pos_y=Z_y)) # print("pos_z {pos_z:3.2f}".format(pos_z=Z_z)) # th_x = np.sqrt(np.abs(var[0])) *beta # th_y = np.sqrt(np.abs(var[1])) *beta # th_z = np.sqrt(np.abs(var[2])) *beta x_check = -self.th_x < Z_x < self.th_x y_check = -self.th_y < Z_y < self.th_y z_check = -self.th_z < Z_z < self.th_z if (x_check): I_x = 1.0 else: # I_x = norm.cdf(-np.abs(Z_x)) / norm.cdf(-self.th_x) # I_x = (norm.cdf(self.th_x) - norm.cdf(-self.th_x)) / (norm.cdf(np.abs(Z_x)) - norm.cdf(-np.abs(Z_x))) I_x = self.th_x / np.abs(Z_x) # if (np.abs(self.th_x - Z_x)<1): # I_x = np.abs(self.th_x - Z_x) # else: # I_x = 1/np.abs(self.th_x-Z_x) if (y_check): I_y = 1.0 else: # I_y = norm.cdf(-np.abs(Z_y)) / norm.cdf(-self.th_y) # I_y = (norm.cdf(self.th_y) - norm.cdf(-self.th_y)) / (norm.cdf(np.abs(Z_y)) - norm.cdf(-np.abs(Z_y))) I_y = self.th_y / np.abs(Z_y) # if (np.abs(self.th_y - Z_y)<1): # I_y = np.abs(self.th_y - Z_y) # else: # I_y = 1/np.abs(self.th_y-Z_y) if (z_check): I_z = 1.0 else: # I_z = norm.cdf(-np.abs(Z_z)) / norm.cdf(-self.th_z) # I_z = (norm.cdf(self.th_z) - norm.cdf(-self.th_z)) / (norm.cdf(np.abs(Z_z)) - norm.cdf(-np.abs(Z_z))) I_z = self.th_z / np.abs(Z_z) # if (np.abs(self.th_z - Z_z)<1): # I_z = np.abs(self.th_z - Z_z) # else: # I_z = 1/np.abs(self.th_x-Z_z) # print(" score {score_x:3.2f} {score_y:3.2f} {score_z:3.2f}".format(score_x=I_x, score_y=I_y, score_z=I_z)) # print(" tot_score {score:3.2f} ".format(score=(I_x+I_y+I_z)/3.)) # print("pose_score_y {pos_score_y:3.2f}".format(pos_score_y=I_y)) # print("pose_score_z {pos_score_z:3.2f}".format(pos_score_z=I_z)) return I_x, I_y, I_z def Measure_new_Gaussian_distribution(self, new_pts): try: pt_num = len(new_pts) mu = np.sum(new_pts, axis=0) / pt_num mean = [int(mu[0]), int(mu[1]), int(mu[2])] var = np.sum(np.power(new_pts, 2), axis=0) / pt_num - np.power(mu, 2) var = [int(var[0]), int(var[1]), int(var[2])] return pt_num, mean, var, True except: return 1, [0, 0, 0], [1, 1, 1], False def Measure_added_Gaussian_distribution(self, new_pts, prev_mean, prev_var, prev_pt_num, new_pt_num): # update mean and variance pt_num = prev_pt_num + new_pt_num mu = np.sum(new_pts, axis=0) mean = np.divide((np.multiply(prev_mean, prev_pt_num) + mu), pt_num) mean = [int(mean[0]), int(mean[1]), int(mean[2])] var = np.subtract(np.divide( (np.multiply((prev_var + np.power(prev_mean, 2)), prev_pt_num) + np.sum(np.power(new_pts, 2), axis=0)), pt_num), np.power(mean, 2)) var = [int(var[0]), int(var[1]), int(var[2])] return pt_num, mean, var def get_color_hist(self, img): ''' # return color_hist # format: [[num_pixels1,color1],[num_pixels2,color2],...,[num_pixelsN,colorN]] # ex: [[362 ,'red' ],[2 ,'blue'],...,[3 ,'gray']] ''' img = img[..., ::-1] # BGR to RGB img = img.flatten().reshape(-1, 3).tolist() # shape: ((640x480)*3) color_hist = [] start = 0 new_color = False actual_name, closest_name = FOCC.get_colour_name(img[0]) if (actual_name == None): color_hist.append([0, closest_name]) else: color_hist.append([0, actual_name]) for i in range(len(img)): actual_name, closest_name = FOCC.get_colour_name(img[i]) for k in range(len(color_hist)): if (color_hist[k][1] == actual_name or color_hist[k][1] == closest_name): color_hist[k][0] += 1 new_color = False break else: new_color = True if (new_color == True): if (actual_name == None): color_hist.append([1, closest_name]) new_color = False else: color_hist.append([1, actual_name]) new_color = False color_hist = sorted(color_hist, reverse=True) return color_hist def get_color_hist2(self, img): ''' # return color_hist # format: [[density1,color1],[density2,color2],[density3,color3]] # ex: [[362 ,'red' ],[2 ,'blue'],[3 ,'gray']] ''' try: hist3D = Hist3D(img[..., ::-1], num_bins=8, color_space='rgb') # BGR to RGB # print('sffsd:', img.shape) # cv2.imshow('a',img) # cv2.waitKey(1) except: return TFCO.get_color_hist(img) else: densities = hist3D.colorDensities() order = densities.argsort()[::-1] densities = densities[order] colors = (255 * hist3D.rgbColors()[order]).astype(int) color_hist = [] for density, color in zip(densities, colors)[:4]: actual_name, closest_name = FOCC.get_colour_name(color.tolist()) if (actual_name == None): color_hist.append([density, closest_name]) else: color_hist.append([density, actual_name]) return color_hist class BboxSizeResample(object): def __init__(self): self.range = 10.0 self.mean_k = 10 self.thres = 1.0 def isNoisyPoint(self, point): return -self.range < point[0] < self.range and -self.range < point[1] < self.range and -self.range < point[ 2] < self.range def outlier_filter(self, points): try: points_ = np.array(points, dtype=np.float32) cloud = pcl.PointCloud() cloud.from_array(points_) filtering = cloud.make_statistical_outlier_filter() filtering.set_mean_k(min(len(points_), self.mean_k)) filtering.set_std_dev_mul_thresh(self.thres) cloud_filtered = filtering.filter() return cloud_filtered.to_array().tolist() except: return points def make_window_size(self, width, height, obj_boxes): if (width < 30): range_x_min = int(obj_boxes[0]) + int(width * 3. / 10.) range_x_max = int(obj_boxes[0]) + int(width * 7. / 10.) elif (width < 60): range_x_min = int(obj_boxes[0]) + int(width * 8. / 20.) range_x_max = int(obj_boxes[0]) + int(width * 12. / 20.) else: range_x_min = int(obj_boxes[0]) + int(width * 12. / 30.) range_x_max = int(obj_boxes[0]) + int(width * 18. / 30.) if (height < 30): range_y_min = int(obj_boxes[1]) + int(height * 3. / 10.) range_y_max = int(obj_boxes[1]) + int(height * 7. / 10.) elif (height < 60): range_y_min = int(obj_boxes[1]) + int(height * 8. / 20.) range_y_max = int(obj_boxes[1]) + int(height * 12. / 20.) else: range_y_min = int(obj_boxes[1]) + int(height * 12. / 30.) range_y_max = int(obj_boxes[1]) + int(height * 18. / 30.) return range_x_min, range_x_max, range_y_min, range_y_max class Visualization(object): def __init(self): self.color = _GREEN self.thick = 1 def vis_bbox_opencv(self, img, bbox): """Visualizes a bounding box.""" (x0, y0, w, h) = bbox x1, y1 = int(x0 + w), int(y0 + h) x0, y0 = int(x0), int(y0) cv2.rectangle(img, (x0, y0), (x1, y1), self.color, thickness=self.thick) return img def Draw_connected_scene_graph(self, node_feature, relation, img_count, sg, idx, object_classes, predicate_classes, cnt_thres=2, view=True, save_path='./vis_result/', show=True): # load all of saved node_feature # if struct ids are same, updated to newly typed object # print('node_feature:',node_feature) tile_idx = [] handle_idx = [] # tomato_rgb = [255,99,71] tomato_rgb = [236, 93, 87] blue_rgb = [81, 167, 250] tomato_hex = webcolors.rgb_to_hex(tomato_rgb) blue_hex = webcolors.rgb_to_hex(blue_rgb) for node_num in range(len(node_feature)): if node_feature.iloc[node_num]['detection_cnt'] < cnt_thres: continue obj_cls = object_classes[int(node_feature.iloc[node_num]["class"])] node = node_feature.iloc[node_num] if (obj_cls == "tile"): tile_idx.append(str(node["idx"])) elif (obj_cls == "handle"): handle_idx.append(str(node["idx"])) else: sg.node('struct' + str(node["idx"]), shape='box', style='filled,rounded', label=obj_cls + "_" + str(node["idx"]), margin='0.11, 0.0001', width='0.11', height='0', fillcolor=tomato_hex, fontcolor='black') # sg.node('attribute_pose_' + str(node["idx"]), shape='box', style='filled, rounded', # label="(" + str(round(float(node["3d_pose"][0]) / 5000.0, 1)) + "," + # str(round(float(node["3d_pose"][1]) / 5000.0, 1)) + "," + # str(round(float(node["3d_pose"][2]) / 5000.0, 1)) + ")", # margin='0.11, 0.0001', width='0.11', height='0', # fillcolor=blue_hex, fontcolor='black') # sg.edge('struct' + str(node["idx"]), 'attribute_pose_' + str(node["idx"])) tile_idx = set(tile_idx) tile_idx = list(tile_idx) handle_idx = set(handle_idx) handle_idx = list(handle_idx) relation_list = [] for num in range(len(relation)): relation_list.append( (relation.iloc[num]["relation"][0], relation.iloc[num]["relation"][1], relation.iloc[num]["relation"][2])) #relation_list = [rel for rel in relation_list if ( # node_feature.loc[node_feature['idx'] == int(rel[0])]['detection_cnt'].item() >= min(cnt_thres, # idx))] #relation_list = [rel for rel in relation_list if ( # node_feature.loc[node_feature['idx'] == int(rel[2])]['detection_cnt'].item() >= min(cnt_thres, # idx))] relation_set = set(relation_list) # remove duplicate relations repeated_idx = [] relation_array = np.array(list(relation_set)) for i in range(len(relation_array)): for j in range(len(relation_array)): res = relation_array[i] == relation_array[j] if res[0] and res[2] and i != j: repeated_idx.append(i) repeated_idx = set(repeated_idx) repeated_idx = list(repeated_idx) if len(repeated_idx) > 0: repeated = relation_array[repeated_idx] # print repeated.shape, repeated_idx for i, (pos, x, y) in enumerate(zip(repeated_idx, repeated[:, 0], repeated[:, 2])): position = np.where((x == repeated[:, 0]) & (y == repeated[:, 2]))[0] triplets = repeated[position].astype(int).tolist() preds = [t[1] for t in triplets] counted = Counter(preds) voted_pred = counted.most_common(1) # print(i, idx, triplets, voted_pred) relation_array[pos, 1] = voted_pred[0][0] relation_set = [tuple(rel) for rel in relation_array.astype(int).tolist()] relation_set = set(relation_set) # print(len(relation_set)) # pale_rgb = [152,251,152] pale_rgb = [112, 191, 64] pale_hex = webcolors.rgb_to_hex(pale_rgb) for rel_num in range(len(relation_set)): rel = relation_set.pop() tile = False handle = False for t_i in tile_idx: if (str(rel[0]) == t_i or str(rel[2]) == t_i): tile = True for h_i in handle_idx: if (str(rel[0]) == h_i or str(rel[2]) == h_i): handle = True if ((not tile) and (not handle)): sg.node('rel' + str(rel_num), shape='box', style='filled, rounded', fillcolor=pale_hex, fontcolor='black', margin='0.11, 0.0001', width='0.11', height='0', label=str(predicate_classes[rel[1]])) sg.edge('struct' + str(rel[0]), 'rel' + str(rel_num)) sg.edge('rel' + str(rel_num), 'struct' + str(rel[2])) if view and sg.format == 'pdf': sg.render(osp.join(save_path, 'scene_graph' + str(idx)), view=view) elif view and sg.format == 'png': sg.render(osp.join(save_path, 'scene_graph' + str(idx)), view=False) if show: img = cv2.imread(osp.join(save_path, 'scene_graph' + str(idx) + '.png'), cv2.IMREAD_COLOR) resize_x = 0.65 resize_y = 0.9 if img.shape[1] < int(1920 * resize_x) and img.shape[0] < int(1080 * resize_y): pad = cv2.resize(img.copy(), (int(1920 * resize_x), int(1080 * resize_y))) pad.fill(255) pad[:img.shape[0], :img.shape[1], :] = img resized = pad elif img.shape[1] < int(1920 * resize_x): pad = cv2.resize(img.copy(), (int(1920 * resize_x), int(1080 * resize_y))) pad.fill(255) img = cv2.resize(img, (img.shape[1], int(1080 * resize_y))) pad[:img.shape[0], :img.shape[1], :] = img resized = pad elif img.shape[0] < int(1080 * resize_y): pad = cv2.resize(img.copy(), (int(1920 * resize_x), int(1080 * resize_y))) pad.fill(255) img = cv2.resize(img, (int(1920 * resize_x), img.shape[0])) pad[:img.shape[0], :img.shape[1], :] = img resized = pad else: resized = cv2.resize(img, (int(1920 * resize_x), int(1080 * resize_y))) cv2.imshow('3D Scene Graph', resized) # cv2.moveWindow('3D Scene Graph',1920,0) cv2.moveWindow('3D Scene Graph', 650, 0) cv2.waitKey(1) # node_feature.to_json(osp.join(save_path, 'json', 'scene_graph_node' + str(idx) + '.json'), orient='index') # relation.to_json(osp.join(save_path, 'json', 'scene_graph_relation' + str(idx) + '.json'), orient='index') # sg.clear() def vis_object_detection(self, image_scene, object_classes, obj_inds, obj_boxes, obj_scores): for i, obj_ind in enumerate(obj_inds): cv2.rectangle(image_scene, (int(obj_boxes[i][0]), int(obj_boxes[i][1])), (int(obj_boxes[i][2]), int(obj_boxes[i][3])), colorlist[int(obj_boxes[i][4])], 2) font_scale = 0.5 txt = FOCC.get_class_string(obj_ind, obj_scores[i], object_classes) ((txt_w, txt_h), _) = cv2.getTextSize(txt, cv2.FONT_HERSHEY_SIMPLEX, font_scale, 1) # Place text background. x0, y0 = int(obj_boxes[i][0]), int(obj_boxes[i][3]) back_tl = x0, y0 - int(1.3 * txt_h) back_br = x0 + txt_w, y0 cv2.rectangle(image_scene, back_tl, back_br, colorlist[int(obj_boxes[i][4])], -1) cv2.putText(image_scene, txt, (x0, y0 - 2), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), 1) return image_scene FOCC = FindObjectClassColor() TFCO = CompareObjects()
45.931907
120
0.520945
5194364f6e5ac4848362a414df28dd1eee160653
3,784
py
Python
idcharger.py
perolse/idcharger
2e501cc459ea08146066deff83ee6650d7786dc8
[ "Apache-2.0" ]
null
null
null
idcharger.py
perolse/idcharger
2e501cc459ea08146066deff83ee6650d7786dc8
[ "Apache-2.0" ]
null
null
null
idcharger.py
perolse/idcharger
2e501cc459ea08146066deff83ee6650d7786dc8
[ "Apache-2.0" ]
1
2021-12-27T14:41:07.000Z
2021-12-27T14:41:07.000Z
import requests from settings import Settings import logging import threading import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) class IdCharger: def __init__(self, settings): self.settings = settings self.loginUrl = '/api/v1/auth/login' self.refreshUrl = '/api/v1/auth/refresh' self.ctCoilUrl = '/api/v1/evse-settings/ct-coil-measured-current' self.access_token = None self.refresh_token = None self.ct1 = 0.0 self.ct2 = 0.0 self.ct3 = 0.0 self.update_access_token() def login(self): try: logging.info("Try to login on Id Charger") login_response = requests.post( url=self.settings.host+self.loginUrl, json={"password": self.settings.password}, verify=False, timeout=30) if login_response.status_code != requests.codes.ok: logging.error("Login failed, status: %s", login_response.status_code) self.access_token = None self.refresh_token = None return self.access_token = login_response.json().get('access_token') self.refresh_token = login_response.json().get('refresh') except Exception as e: logging.error("Login Id Charger failed: %s", str(e)) self.access_token = None def refresh(self): try: logging.info("Try to refresh token on Id Charger") refresh_response = requests.post( url=self.settings.host+self.refreshUrl, json={"refresh_token": self.refresh_token}, verify=False, timeout=30) if refresh_response.status_code != requests.codes.ok: logging.error("Refresh failed, status: %s", refresh_response.status_code) self.access_token = None return False self.access_token = refresh_response.json().get('access_token') except Exception as e: logging.error("Refresh access token for Id Charger failed: %s", str(e)) self.access_token = None def update_access_token(self): try: if self.refresh_token == None: if self.login(): raise Exception("Login failed") else: if not refresh(): if self.login(): raise Exception("Login failed") self.token_refresh_timer = threading.Timer(120, self.update_access_token) self.token_refresh_timer.start() except Exception as e: logging.error("Update access token for Id Charger failed: %s", str(e)) self.access_token = None self.refresh_token = None def stop(self): self.token_refresh_timer.cancel() def fetch_values(self): try: headers = { 'Authorization': 'Bearer ' + self.access_token } logging.info("Try to fetch values") ct_coil_response = requests.get( url=self.settings.host+self.ctCoilUrl, headers=headers, verify=False, timeout=10) if ct_coil_response.status_code != requests.codes.ok: logging.error("Fetch failed, status: %s", ct_coil_response.status_code) return False logging.info("Values fetched") self.ct1 = float(ct_coil_response.json().get('CT1')) self.ct2 = float(ct_coil_response.json().get('CT2')) self.ct3 = float(ct_coil_response.json().get('CT3')) return True except Exception as e: logging.info("Fetch values failed: %s", str(e)) return False
39.010309
89
0.581924
894c290a08c1d11649b0cbeac40974bed420f61c
4,451
py
Python
tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_statistics.py
fefi95/twilio-python
b9bfea293b6133fe84d4d8d3ac4e2a75381c3881
[ "MIT" ]
1
2019-12-30T21:46:55.000Z
2019-12-30T21:46:55.000Z
tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_statistics.py
fefi95/twilio-python
b9bfea293b6133fe84d4d8d3ac4e2a75381c3881
[ "MIT" ]
null
null
null
tests/integration/taskrouter/v1/workspace/task_queue/test_task_queue_statistics.py
fefi95/twilio-python
b9bfea293b6133fe84d4d8d3ac4e2a75381c3881
[ "MIT" ]
null
null
null
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from tests import IntegrationTestCase from tests.holodeck import Request from twilio.base.exceptions import TwilioException from twilio.http.response import Response class TaskQueueStatisticsTestCase(IntegrationTestCase): def test_fetch_request(self): self.holodeck.mock(Response(500, '')) with self.assertRaises(TwilioException): self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .task_queues(sid="WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .statistics().fetch() self.holodeck.assert_has_request(Request( 'get', 'https://taskrouter.twilio.com/v1/Workspaces/WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/TaskQueues/WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Statistics', )) def test_fetch_response(self): self.holodeck.mock(Response( 200, ''' { "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "url": "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/TaskQueues/WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Statistics", "cumulative": { "avg_task_acceptance_time": 0.0, "end_time": "2015-08-18T08:42:34Z", "reservations_accepted": 0, "reservations_canceled": 0, "reservations_created": 0, "reservations_rejected": 0, "reservations_rescinded": 0, "reservations_timed_out": 0, "start_time": "2015-08-18T08:27:34Z", "tasks_canceled": 0, "tasks_deleted": 0, "tasks_entered": 0, "tasks_moved": 0 }, "realtime": { "activity_statistics": [ { "friendly_name": "Offline", "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "workers": 0 }, { "friendly_name": "Idle", "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "workers": 0 }, { "friendly_name": "80fa2beb-3a05-11e5-8fc8-98e0d9a1eb73", "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "workers": 0 }, { "friendly_name": "Reserved", "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "workers": 0 }, { "friendly_name": "Busy", "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "workers": 0 }, { "friendly_name": "817ca1c5-3a05-11e5-9292-98e0d9a1eb73", "sid": "WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "workers": 0 } ], "longest_task_waiting_age": 0, "longest_task_waiting_sid": "WTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "tasks_by_status": { "assigned": 0, "pending": 0, "reserved": 0, "wrapping": 0 }, "total_available_workers": 0, "total_eligible_workers": 0, "total_tasks": 0 }, "task_queue_sid": "WQaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "workspace_sid": "WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } ''' )) actual = self.client.taskrouter.v1.workspaces(sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .task_queues(sid="WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .statistics().fetch() self.assertIsNotNone(actual)
41.212963
161
0.457425
561fdb9e6a8fdda68e47a3447768b3e8fbf21e75
14,126
py
Python
Roles/avl-settings/main.py
andycavatorta/oratio
f407797e3ea6d2956e577ec98c64486b04d90946
[ "MIT" ]
1
2017-12-04T17:29:37.000Z
2017-12-04T17:29:37.000Z
Roles/avl-settings/main.py
andycavatorta/oratio
f407797e3ea6d2956e577ec98c64486b04d90946
[ "MIT" ]
null
null
null
Roles/avl-settings/main.py
andycavatorta/oratio
f407797e3ea6d2956e577ec98c64486b04d90946
[ "MIT" ]
null
null
null
""" pin info: analog potentiometers are read via MCP3008 chip connected via SPI MCP3008 ADC chip #1 pin 21: SPI MISO pin 19: SPI MOSI pin 23: SPI Serial Clock pin 38: Chip Select MCP3008 ADC chip #2 pin 21: SPI MISO pin 19: SPI MOSI pin 23: SPI Serial Clock pin 40: Chip Select MCP3008 ADC chip #3 pin 21: SPI MISO pin 19: SPI MOSI pin 23: SPI Serial Clock pin 32: Chip Select MCP3008 ADC chip #4 pin 21: SPI MISO pin 19: SPI MOSI pin 23: SPI Serial Clock pin 36: Chip Select MCP3008 ADC chip #5 pin 21: SPI MISO pin 19: SPI MOSI pin 23: SPI Serial Clock pin 24: Chip Select MCP3008 ADC chip #6 pin 21: SPI MISO pin 19: SPI MOSI pin 23: SPI Serial Clock pin 26: Chip Select """ import Adafruit_GPIO as GPIO import adafruit_spi_modified as SPI import commands import os import Queue import settings import time import threading import traceback import sys BASE_PATH = os.path.dirname(os.path.realpath(__file__)) UPPER_PATH = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0] DEVICES_PATH = "%s/Hosts/" % (BASE_PATH ) THIRTYBIRDS_PATH = "%s/thirtybirds_2_0" % (UPPER_PATH ) sys.path.append(BASE_PATH) sys.path.append(UPPER_PATH) from thirtybirds_2_0.Network.manager import init as network_init from thirtybirds_2_0.Updates.manager import init as updates_init ######################## ## UTILS ######################## class Utils(object): def __init__(self, hostname): self.hostname = hostname def reboot(self): os.system("sudo reboot now") def get_shelf_id(self): return self.hostname[11:][:1] def get_camera_id(self): return self.hostname[12:] def create_image_file_name(self, timestamp, light_level, process_type): return "{}_{}_{}_{}_{}.png".format(timestamp, self.get_shelf_id() , self.get_camera_id(), light_level, process_type) def remote_update_git(self, oratio, thirtybirds, update, upgrade): if oratio: subprocess.call(['sudo', 'git', 'pull'], cwd='/home/pi/oratio') if thirtybirds: subprocess.call(['sudo', 'git', 'pull'], cwd='/home/pi/thirtybirds_2_0') return def remote_update_scripts(self): updates_init("/home/pi/oratio", False, True) return def get_update_script_version(self): (updates, ghStatus, bsStatus) = updates_init("/home/pi/oratio", False, False) return updates.read_version_pickle() def get_git_timestamp(self): return commands.getstatusoutput("cd /home/pi/oratio/; git log -1 --format=%cd")[1] def get_temp(self): return commands.getstatusoutput("/opt/vc/bin/vcgencmd measure_temp")[1] def get_cpu(self): bash_output = commands.getstatusoutput("uptime")[1] split_output = bash_output.split(" ") return split_output[12] def get_uptime(self): bash_output = commands.getstatusoutput("uptime")[1] split_output = bash_output.split(" ") return split_output[4] def get_disk(self): # stub for now return "0" def get_client_status(self): return (self.hostname, self.get_update_script_version(), self.get_git_timestamp(), self.get_temp(), self.get_cpu(), self.get_uptime(), self.get_disk()) class MCP3008s(object): def __init__(self, spi_clock_pin, miso_pin, mosi_pin, chip_select_pins, list_of_noise_thresholds): self.gpio = GPIO.get_platform_gpio() self.chip_select_pins = chip_select_pins self.list_of_noise_thresholds = list_of_noise_thresholds self._spi = SPI.BitBang(self.gpio, spi_clock_pin, mosi_pin, miso_pin) self._spi.set_clock_hz(1000000) self._spi.set_mode(0) self._spi.set_bit_order(SPI.MSBFIRST) for chip_select_pin in chip_select_pins: self.gpio.setup(chip_select_pin, GPIO.OUT) self.gpio.set_high(chip_select_pin) def read(self, chip_select_pin, adc_number): assert 0 <= adc_number <= 7, 'ADC number must be a value of 0-7!' # Build a single channel read command. # For example channel zero = 0b11000000 command = 0b11 << 6 # Start bit, single channel read command |= (adc_number & 0x07) << 3 # Channel number (in 3 bits) # Note the bottom 3 bits of command are 0, this is to account for the # extra clock to do the conversion, and the low null bit returned at # the start of the response. resp = self._spi.transfer(chip_select_pin,[command, 0x0, 0x0]) # Parse out the 10 bits of response data and return it. result = (resp[0] & 0x01) << 9 result |= (resp[1] & 0xFF) << 1 result |= (resp[2] & 0x80) >> 7 return result & 0x3FF def scan_all(self): adcs = [] for chip_number, chip_select_pin in enumerate(self.chip_select_pins): channels = [] for adc_number in range(8): if self.list_of_noise_thresholds[chip_number][adc_number] > -1: channels.append(self.read(chip_select_pin, adc_number)) else: channels.append(0) adcs.append(channels) return adcs class Potentiometers(threading.Thread): def __init__(self, network_send_ref): threading.Thread.__init__(self) self.queue = Queue.Queue() self.network_send_ref = network_send_ref self.noise_threshold = 20 self.spi_clock_pin = 11 self.miso_pin = 9 self.mosi_pin = 10 self.chip_select_pins = [20,21,12,16,8,7] self.potentiometers_layout = [ [ "voice_1_overtone_1_volume", "voice_1_overtone_2_harmonic", "voice_1_overtone_2_fine", "voice_1_overtone_2_volume", "voice_1_emergence", "", "", "", ], [ "voice_1_root_half_steps", "voice_1_root_fine", "voice_1_overtone_1_harmonic", "voice_1_overtone_1_fine", "", "", "", "", ], [ "voice_2_overtone_1_volume", "voice_2_overtone_2_harmonic", "voice_2_overtone_2_fine", "voice_2_overtone_2_volume", "voice_2_emergence", "", "", "", ], [ "voice_2_root_half_steps", "voice_2_root_fine", "voice_2_overtone_1_harmonic", "voice_2_overtone_1_fine", "", "", "", "", ], [ "voice_3_overtone_1_volume", "voice_3_overtone_2_harmonic", "voice_3_overtone_2_fine", "voice_3_overtone_2_volume", "voice_3_emergence", "layer_speed", "", "", ], [ "voice_3_root_half_steps", "voice_3_root_fine", "voice_3_overtone_1_harmonic", "voice_3_overtone_1_fine", "", "", "", "", ] ] self.potentiometer_last_value = [ [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0] ] self.list_of_noise_thresholds = [ [ 10, 10, 10, 10, 10, 10, 10, 10, ], [ 10, 10, 10, 10, 10, 10, 10, 10, ], [ 10, 10, 10, 10, 10, 10, 10, 10, ], [ 10, 10, 10, 10, 10, 10, 10, 10, ], [ 10, 10, 10, 10, 10, 10, 10, 10, ], [ 10, 10, 10, 10, 10, 10, 10, 10, ] ] self.mcp3008s = MCP3008s(self.spi_clock_pin, self.miso_pin, self.mosi_pin, self.chip_select_pins, self.list_of_noise_thresholds) def run(self): last_summary_timestamp = time.time() while True: all_adc_values = self.mcp3008s.scan_all() #print all_adc_values for adc in range(len(all_adc_values)): for channel in range(8): adc_value = all_adc_values[adc][channel] potentiometer_name = self.potentiometers_layout[adc][channel] if potentiometer_name != "": #print adc_value, self.potentiometer_last_value[adc][channel], self.list_of_noise_thresholds[adc][channel] if abs(adc_value - self.potentiometer_last_value[adc][channel] ) > self.list_of_noise_thresholds[adc][channel]: self.network_send_ref(potentiometer_name, adc_value/1023.0) print adc, channel, self.potentiometers_layout[adc][channel], adc_value self.potentiometer_last_value[adc][channel] = adc_value time.sleep(0.05) if time.time() - 30 > last_summary_timestamp: for adc in range(len(self.potentiometers_layout)): for channel in range(8): potentiometer_name = self.potentiometers_layout[adc][channel] if potentiometer_name != "": self.network_send_ref(potentiometer_name, self.potentiometer_last_value[adc][channel]/1023.0) last_summary_timestamp = time.time() class Network(object): def __init__(self, hostname, network_message_handler, network_status_handler): self.hostname = hostname self.thirtybirds = network_init( hostname=hostname, role="client", discovery_multicastGroup=settings.discovery_multicastGroup, discovery_multicastPort=settings.discovery_multicastPort, discovery_responsePort=settings.discovery_responsePort, pubsub_pubPort=settings.pubsub_pubPort, message_callback=network_message_handler, status_callback=network_status_handler ) # Main handles network send/recv and can see all other classes directly class Main(threading.Thread): def __init__(self, hostname): threading.Thread.__init__(self) self.network = Network(hostname, self.network_message_handler, self.network_status_handler) self.queue = Queue.Queue() self.network.thirtybirds.subscribe_to_topic("door_closed") self.potentiometers = Potentiometers(self.network.thirtybirds.send) # self.network.thirtybirds.send self.potentiometers.daemon = True self.potentiometers.start() self.utils = Utils(hostname) self.status = { "avl-settings":"pass", "avl-settings-adcs":"pass", } self.network.thirtybirds.subscribe_to_topic("client_monitor_request") self.network.thirtybirds.subscribe_to_topic("settings_state_request") self.network.thirtybirds.subscribe_to_topic("mandala_device_request") self.network.thirtybirds.subscribe_to_topic("mandala_device_status") def update_device_status(self, devicename, status): print "update_device_status 1",devicename, status if self.status[devicename] != status: self.status[devicename] = status msg = [devicename, status] print "update_device_status 2",devicename, status self.network.thirtybirds.send("mandala_device_status", msg) def get_device_status(self): for devicename in self.status: msg = [devicename, self.status[devicename]] self.network.thirtybirds.send("mandala_device_status", msg) def network_message_handler(self, topic_msg): # this method runs in the thread of the caller, not the tread of Main topic, msg = topic_msg # separating just to eval msg. best to do it early. it should be done in TB. if len(msg) > 0: msg = eval(msg) self.add_to_queue(topic, msg) def network_status_handler(self, topic_msg): # this method runs in the thread of the caller, not the tread of Main print "Main.network_status_handler", topic_msg def add_to_queue(self, topic, msg): self.queue.put((topic, msg)) def run(self): while True: try: topic, msg = self.queue.get(True) if topic == "client_monitor_request": self.network.thirtybirds.send("client_monitor_response", self.utils.get_client_status()) if topic == "settings_state_request": pass if topic == "mandala_device_request": self.get_device_status() except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() print e, repr(traceback.format_exception(exc_type, exc_value,exc_traceback)) def init(hostname): main = Main(hostname) main.daemon = True main.start() return main
34.20339
159
0.555854
07727ba5bfc4bf508a8dfcde7cfee0a7b6e70c4e
9,587
py
Python
nzme_skynet/core/proxy/browserproxy.py
MilindThakur/nzme-skynet
7175edbf625e46ce1489c97f171a8717eaf0be7e
[ "BSD-3-Clause" ]
2
2019-09-27T22:06:35.000Z
2019-12-04T15:48:58.000Z
nzme_skynet/core/proxy/browserproxy.py
MilindThakur/nzme-skynet
7175edbf625e46ce1489c97f171a8717eaf0be7e
[ "BSD-3-Clause" ]
4
2020-03-24T18:29:48.000Z
2021-03-29T22:15:24.000Z
nzme_skynet/core/proxy/browserproxy.py
MilindThakur/nzme-skynet
7175edbf625e46ce1489c97f171a8717eaf0be7e
[ "BSD-3-Clause" ]
1
2020-10-21T20:03:59.000Z
2020-10-21T20:03:59.000Z
# coding=utf-8 import json import time import os from browsermobproxy import Server from browsermobproxy import Client from haralyzer import HarParser from nzme_skynet.core.driver.driverregistry import DriverRegistry from nzme_skynet.core.driver.enums.drivertypes import DriverTypes from nzme_skynet.core.driver.basedriver import BaseDriver class BrowserProxy(object): """ Base class to for Browser Proxy setup """ def __init__(self): self._driver = self._server = self._client = None @property def driver(self): # type: () -> BaseDriver """ Exposes the framework driver wrapper for browser/device interactions :return: Framework Driver """ return self._driver @property def client(self): # type: () -> Client """ Exposes Browsermobproxy client :return: """ return self._client @property def harparser(self): """ Captures the har and converts to a HarParser object :return: HarParser object, a page from har capture """ result_har = json.dumps(self._client.har, ensure_ascii=False) har_parser = HarParser(json.loads(result_har)) return har_parser.pages[0] def start(self): """ Start the proxy and browser """ self.start_proxy() self.start_browser() def start_proxy(self): """ Start the browsermob-proxy """ raise NotImplementedError def start_browser(self, headless=False, resolution="maximum", mobileEmulation=""): """ Start the chrome browser instance :param bool headless: run browser in headless mode :param str resolution: maximum or width * height :param str mobileEmulation: chrome emulation mode e.g. iPhone X, Samsung Galaxy S5 etc :return: Framework driver wrapper """ raise NotImplementedError def stop(self): """ Stop the proxy and browser instance """ raise NotImplementedError def stop_browser(self): """ Stop the browser instance """ if DriverRegistry.get_driver(): DriverRegistry.deregister_driver() self._driver = None def stop_proxy(self): """ Stop the proxy """ if self._client: self._client.close() self._client = None if self._server: self._server.stop() self._server = None def capture_url_traffic(self, url, wait_time=0): """ Capture the har for a given url :param str url: url to capture traffic for :param int wait_time: time to wait after the page load :return: HarParser object, a page from har capture """ self._client.new_har(options={'captureHeaders': True}) self._driver.goto_url(url, absolute=True) time.sleep(wait_time) result_har = json.dumps(self._client.har, ensure_ascii=False) har_parser = HarParser(json.loads(result_har)) return har_parser.pages[0] @staticmethod def filter_entry_by_matching_url(har_page, url_matcher): """ Static method to match request url, an absolute string match is made e.g. bproxy.filter_entry_by_matching_url(har_page, "gstatic.com") :param HarParser.page har_page: HarParser page instance :param str url_matcher: matching url :return: list of matching page entry """ matching_list = [] for entry in har_page.entries: if url_matcher in entry['request']['url']: matching_list.append(entry) return matching_list class BrowserProxyLocal(BrowserProxy): """ Starts local browsermob-proxy server and chrome browser to capture the traffic. Example: bproxy = BrowserProxyLocal(path_to_binary=BROWSER_PROXY_BIN) bproxy.start() """ def __init__(self, path_to_binary='browsermob-proxy'): """ Initialises a new Local Browsermobproxy and browser instance :param str path_to_binary: Path to the browsermob proxy bin file """ super(BrowserProxyLocal, self).__init__() self._bin_path = path_to_binary def start_proxy(self): """ Starts the browsermob-proxy locally :return: client instance on browsermob-proxy """ try: self._server = Server(path=self._bin_path) except Exception: raise self._server.start() self._client = self._server.create_proxy({'captureHeaders': True, 'captureContent': True, 'captureBinaryContent': True}) def start_browser(self, headless=False, resolution="maximum", mobileEmulation=""): """ Starts local chrome browser with proxy configured :param bool headless: run browser in headless mode :param str resolution: maximum or width * height :param str mobileEmulation: chrome emulation mode e.g. iPhone X, Samsung Galaxy S5 etc :return: Framework driver wrapper """ proxy_server_arg = "--proxy-server={0}".format(self._client.proxy) capabilities = { "browserName": "chrome", "version": "ANY", "platform": "ANY", "goog:chromeOptions": { "args": [proxy_server_arg, '--ignore-certificate-errors', '--test-type'], "extensions": [], "prefs": {} } } options = { "highlight": False, "headless": headless, "resolution": resolution, "mobileEmulation": mobileEmulation } DriverRegistry.register_driver(DriverTypes.CHROME, capabilities=capabilities, options=options, local=True) self._driver = DriverRegistry.get_driver() def stop(self): """ Stop local browsermob-proxy and browser instance :return: """ self.stop_browser() self.start_proxy() class BrowserProxyGrid(BrowserProxy): """ Run browsermob-proxy and browser instance in docker mode first. Use to capture and analyse traffic. Useful for a CI setup Please refer to https://hub.docker.com/r/qautomatron/docker-browsermob-proxy/ Example: capabilities = { "browserName": "chrome", "platform": 'LINUX', "version": '', "javascriptEnabled": True } bproxy = BrowserProxyGrid(capabilities=capabilities) bproxy.start() """ def __init__(self, capabilities, grid_url="http://localhost:4444/wd/hub"): """ Initialises Browsermob-proxy grid instance :param dict capabilities: Browser/Device capabilities :param str grid_url: Selenium grid url """ super(BrowserProxyGrid, self).__init__() self._capabilities = capabilities self._grid_url = grid_url def start_proxy(self): """ Assumes browsermob-proxy is running in a docker container and initiates a client :return: browsermob-proxy client instance """ proxy_ip = self._get_browsermobproxy_docker_ip() proxy_port = "9090" self._client = Client("{0}:{1}".format(proxy_ip, proxy_port)) @staticmethod def _get_browsermobproxy_docker_ip(): """ Get the docker IP address of the browsermob-proxy container :return: str docker container IP address """ proxy_container = os.popen( "docker ps --format {{.Names}} | grep 'proxy'").read().rstrip() if not proxy_container: raise Exception("Error: Ensure browsermobproxy is running in a docker container") network = os.popen( "docker inspect --format {{.HostConfig.NetworkMode}} %s" % proxy_container).read().rstrip() return os.popen("docker inspect --format {{.NetworkSettings.Networks.%s.IPAddress}} %s" % (network, proxy_container)).read().rstrip() def start_browser(self, headless=False, resolution="maximum", mobileEmulation=""): """ Start the browser in a grid with proxy setup :param bool headless: run browser in headless mode :param str resolution: maximum or width * height :param str mobileEmulation: chrome emulation mode e.g. iPhone X, Samsung Galaxy S5 etc :return: Framework driver wrapper """ proxy_server_arg = "--proxy-server={0}".format(self._client.proxy) options = { "highlight": False, "headless": headless, "resolution": resolution, "mobileEmulation": mobileEmulation } self._capabilities["goog:chromeOptions"] = { "args": [proxy_server_arg, '--ignore-certificate-errors', '--test-type']} DriverRegistry.register_driver(DriverTypes.CHROME, capabilities=self._capabilities, local=False, options=options, grid_url=self._grid_url) self._driver = DriverRegistry.get_driver() def stop(self): """ Stop the browsermob-proxy and browser instance """ self.stop_browser() # TODO: Adding a sleep, otherwise getting a "Unable to close channel." error from Browsermobproxy container. time.sleep(5) self.stop_proxy()
34.861818
116
0.607594
bf2be8f0b1abe6d134723319ea2ade871df5041f
8,229
py
Python
scripts/lib/tools.py
thorunna/UD
ac27262e49691daecf3016fa9386e603252a45a6
[ "Apache-2.0" ]
1
2020-10-05T12:40:39.000Z
2020-10-05T12:40:39.000Z
scripts/lib/tools.py
thorunna/UD
ac27262e49691daecf3016fa9386e603252a45a6
[ "Apache-2.0" ]
null
null
null
scripts/lib/tools.py
thorunna/UD
ac27262e49691daecf3016fa9386e603252a45a6
[ "Apache-2.0" ]
null
null
null
import string import re import requests import json from lib.rules import relation_NP, relation_IP, relation_CP, abbr_map from lib.reader import IndexedCorpusTree def determine_relations(mod_tag, mod_func, head_tag, head_func): if mod_tag in ["NP", "NX", "WNX"]: # -ADV, -CMP, -PRN, -SBJ, -OB1, -OB2, -OB3, -PRD, -POS, -COM, -ADT, -TMP, -MSR return relation_NP.get(mod_func, "dep") elif mod_tag == "WNP": return "obj" elif mod_tag in ["NS", "N", "NPRS"] and head_tag in [ "NP", "NX", "QTP", "ADJP", "CONJP", "NPR", ]: # seinna no. í nafnlið fær 'conj' og er háð fyrra no. return "conj" elif head_tag == "ADJP": return "amod" elif mod_tag == "NPR" and head_tag == "CONJP": return "conj" elif mod_tag == "ES": return "expl" # expletive elif mod_tag in ["PRO", "WPRO"]: return "nmod" elif mod_tag in ["D", "WD", "ONE", "ONES", "OTHER", "OTHERS", "SUCH"]: return "det" elif ( mod_tag[:3] == "ADJ" or mod_tag[:4] == "WADJ" or mod_tag in ["Q", "QR", "QS", "WQP"] ): # -SPR (secondary predicate) return "amod" elif mod_tag in ["PP", "WPP", "PX"]: # -BY, -PRN return "obl" # NP sem er haus PP fær obl nominal #TODO: haus CP-ADV (sem er PP) á að vera merktur advcl elif mod_tag == "P": return "case" elif mod_tag[:3] == "ADV" or mod_tag in [ "NEG", "FP", "QP", "ALSO", "WADV", "WADVP", ]: # FP = focus particles #QP = quantifier phrase - ATH. """ if head_func == 'QUE' or head_tag == 'WNP': # Ætti að grípa spurnarorð í spurnarsetningum, sem eru mark skv. greiningu HJ - TODO er þetta rétt? return 'mark' else: # -DIR, -LOC, -TP return 'advmod' """ return "advmod" elif ( mod_tag == "NS" and head_tag == "ADVP" and head_func == "TMP" ): # ath. virkar fyrir eitt dæmi, of greedy? return "conj" elif mod_tag in ["RP", "RPX"]: return "compound:prt" elif ( mod_tag == "IP" and mod_func == "SUB" and head_tag == "CP" and head_func == "FRL" ): return "acl:relcl" elif mod_tag in ["IP", "VP"]: return relation_IP.get(mod_func, "dep") elif mod_tag[:2] == "VB" and head_tag == "CP": return "ccomp" elif head_tag == "IP" and head_func == "INF-PRP": return "advcl" elif head_tag == "NP" and mod_tag == "VAN": return "amod" elif mod_tag in ["VAN", "DAN"] or mod_tag[:2] == "DO": return "ccomp/xcomp" elif mod_tag in ["VAN", "DAN", "HAN", "BAN", "RAN"]: # RAN vantaði? return "aux" elif mod_tag in ["VBN", "DON", "HVN", "RDN"]: # ath. VBN getur verið rót if head_func and "=" in head_func: return "conj" else: return "dep" # elif mod_tag[:2] in ['VB', 'DO', 'HV', 'RD', 'MD']: #todo elif mod_tag[:2] in ["DO", "HV", "RD", "MD"]: # todo return "aux" # return 'verb' # testing dropping aux in output elif mod_tag[:2] == "BE" or mod_tag == "BAN": return "cop" elif mod_tag == "VAG": return "amod" elif mod_tag == "RRC": return "acl:relcl" elif mod_tag == "CONJ": return "cc" elif mod_tag in ["CONJP", "N"] and head_tag in [ "NP", "N", "PP", ]: # N: tvö N í einum NP tengd með CONJ return "conj" elif mod_tag == "CONJP" and head_tag == "IP": return relation_IP.get(head_func, "dep") elif mod_tag == "CONJP": return "conj" elif mod_tag == "CP" and mod_func == "REL" and head_tag == "ADVP": return "advcl" elif mod_tag == "CP": return relation_CP.get(mod_func, "dep") elif mod_tag in ["C", "CP", "TO", "WQ"]: # infinitival marker with marker relation return "mark" elif mod_tag in ["NUM", "NUMP"]: return "nummod" elif mod_tag == "FRAG": return "xcomp" elif mod_tag in string.punctuation or mod_tag == "LB": return "punct" elif mod_tag in ["INTJ", "INTJP"] or head_tag == "INTJP": return "discourse" elif mod_tag in ["FOREIGN", "FW", "ENGLISH", "LATIN"] or head_tag in [ "FOREIGN", "FW", "ENGLISH", "LATIN", ]: return "flat:foreign" elif mod_tag in [ "XXX", "XP", "X", "QTP", "REP", "FS", "LS", "META", "REF", ]: # XXX = annotator unsure of parse, LS = list marker return "dep" # unspecified dependency elif head_tag in ["META", "CODE", "REF", "FRAG"]: return "dep" elif mod_tag in ["N", "NS", "NPR", "NPRS"]: # return 'rel' return "dep" elif head_tag == "IP" and head_func == "SMC": return "dep" return "dep" def decode_escaped(string, lemma=False): """ Fixes various punctuations (-, /, ') that are escaped in corpus data Also fixes most abbrevations in corpus data using abbrevations rules dictionar """ if re.search(r"[<>]", string): """Tokens processed""" if re.search(r"</?dash/?>", string): string = re.sub(r"</?dash/?>", "-", string) if re.search(r"</?slash/?>", string): string = re.sub(r"</?slash/?>", "/", string) if re.search(r"</?apostrophe/?>", string): string = re.sub(r"</?apostrophe/?>", "'", string) return string if string in abbr_map.keys(): string = re.sub(abbr_map[string][0], abbr_map[string][1], string) return string else: return string def fix_IcePaHC_tree_errors(tree): """ Fixes specific punctuation errors in IcePaHC trees """ if not tree.corpus_id: return tree fileid = tree.corpus_id.split(",")[0] if fileid == "1150.HOMILIUBOK.REL-SER": if tree.corpus_id_num in {".691", ".697", ".1040", ".1044", ".1572"}: tree.append(IndexedCorpusTree.fromstring("(. ?-?)")) elif tree.corpus_id_num == ".1486": tree.append(IndexedCorpusTree.fromstring("(. .-.)")) elif fileid == "1275.MORKIN.NAR-HIS": if tree.corpus_id_num == ".451": tree.append(IndexedCorpusTree.fromstring("(. .-.)")) tree.append(IndexedCorpusTree.fromstring('(" "-")')) elif tree.corpus_id_num == ".1680": tree.append(IndexedCorpusTree.fromstring("(. .-.)")) return tree def tagged_corpus(corpus): """ Gets tagged data for corpus """ text = "" IDs = [] counter = 0 for tree in corpus: counter += 1 text += re.sub( r" \.", ".", re.sub( r"(\$ \$|\*ICH\*|\*T\*)", "", " ".join( [ tree[i].split("-")[0] for i in tree.treepositions() if isinstance(tree[i], str) and "-" in tree[i] ] ), ) + "\n", ) if tree.corpus_id != None: IDs.append(tree.corpus_id) else: # IDs.append(IDs[0][:-1]+str(counter)) IDs.append("ID_missing_" + str(counter)) url = "http://malvinnsla.arnastofnun.is" payload = {"text": text, "lemma": "on"} headers = {} # res = requests.post(url, data=payload, headers=headers) # tagged = json.loads(res.text) tagged = None tagged_sents = [] while tagged is None: try: res = requests.post(url, data=payload, headers=headers) tagged = json.loads(res.text) except: pass for par in tagged["paragraphs"]: tagged_sent = {} for sent in par["sentences"]: for pair in sent: tagged_sent[pair["word"]] = (pair["tag"], pair["lemma"]) tagged_sents.append(tagged_sent) ID_sents = dict(zip(IDs, tagged_sents)) # for i, j in ID_sents.items(): # print(i,j) # input() # exit() return ID_sents
31.288973
113
0.510633
ee243c2f4c3ffc7c9f5ae44fa41fb33fabe5f861
228
py
Python
db/python_mongo_gfs.py
sdyz5210/python
78f9999f94d92d9ca7fde6f18acec7d3abd422ef
[ "BSD-3-Clause" ]
null
null
null
db/python_mongo_gfs.py
sdyz5210/python
78f9999f94d92d9ca7fde6f18acec7d3abd422ef
[ "BSD-3-Clause" ]
null
null
null
db/python_mongo_gfs.py
sdyz5210/python
78f9999f94d92d9ca7fde6f18acec7d3abd422ef
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # python v2.7.6 from pymongo import MongoClient import gridfs db = MongoClient().summergfs fs = gridfs.GridFS(db) fs.put("/Users/mac/Documents/workspaces/github/python/high/a.jpg")
22.8
66
0.723684
a4c99b19c3ff57c1adb51a836bf8a2844b93d2fa
6,653
py
Python
tst/rpc/full_node_rpc_client.py
TST-Group-BE/flax-blockchain
ed850df4f28ef4b6f71c175c8b6d07d27f7b3cd5
[ "Apache-2.0" ]
null
null
null
tst/rpc/full_node_rpc_client.py
TST-Group-BE/flax-blockchain
ed850df4f28ef4b6f71c175c8b6d07d27f7b3cd5
[ "Apache-2.0" ]
null
null
null
tst/rpc/full_node_rpc_client.py
TST-Group-BE/flax-blockchain
ed850df4f28ef4b6f71c175c8b6d07d27f7b3cd5
[ "Apache-2.0" ]
null
null
null
from typing import Dict, List, Optional, Tuple from tst.consensus.block_record import BlockRecord from tst.rpc.rpc_client import RpcClient from tst.types.blockchain_format.sized_bytes import bytes32 from tst.types.coin_record import CoinRecord from tst.types.full_block import FullBlock from tst.types.spend_bundle import SpendBundle from tst.types.unfinished_header_block import UnfinishedHeaderBlock from tst.util.byte_types import hexstr_to_bytes from tst.util.ints import uint32, uint64 class FullNodeRpcClient(RpcClient): """ Client to Tst RPC, connects to a local full node. Uses HTTP/JSON, and converts back from JSON into native python objects before returning. All api calls use POST requests. Note that this is not the same as the peer protocol, or wallet protocol (which run Tst's protocol on top of TCP), it's a separate protocol on top of HTTP thats provides easy access to the full node. """ async def get_blockchain_state(self) -> Dict: response = await self.fetch("get_blockchain_state", {}) if response["blockchain_state"]["peak"] is not None: response["blockchain_state"]["peak"] = BlockRecord.from_json_dict(response["blockchain_state"]["peak"]) return response["blockchain_state"] async def get_block(self, header_hash) -> Optional[FullBlock]: try: response = await self.fetch("get_block", {"header_hash": header_hash.hex()}) except Exception: return None return FullBlock.from_json_dict(response["block"]) async def get_block_record_by_height(self, height) -> Optional[BlockRecord]: try: response = await self.fetch("get_block_record_by_height", {"height": height}) except Exception: return None return BlockRecord.from_json_dict(response["block_record"]) async def get_block_record(self, header_hash) -> Optional[BlockRecord]: try: response = await self.fetch("get_block_record", {"header_hash": header_hash.hex()}) if response["block_record"] is None: return None except Exception: return None return BlockRecord.from_json_dict(response["block_record"]) async def get_unfinished_block_headers(self) -> List[UnfinishedHeaderBlock]: response = await self.fetch("get_unfinished_block_headers", {}) return [UnfinishedHeaderBlock.from_json_dict(r) for r in response["headers"]] async def get_all_block(self, start: uint32, end: uint32) -> List[FullBlock]: response = await self.fetch("get_blocks", {"start": start, "end": end, "exclude_header_hash": True}) return [FullBlock.from_json_dict(r) for r in response["blocks"]] async def get_network_space( self, newer_block_header_hash: bytes32, older_block_header_hash: bytes32 ) -> Optional[uint64]: try: network_space_bytes_estimate = await self.fetch( "get_network_space", { "newer_block_header_hash": newer_block_header_hash.hex(), "older_block_header_hash": older_block_header_hash.hex(), }, ) except Exception: return None return network_space_bytes_estimate["space"] async def get_coin_records_by_puzzle_hash( self, puzzle_hash: bytes32, include_spent_coins: bool = True, start_height: Optional[int] = None, end_height: Optional[int] = None, ) -> List: d = {"puzzle_hash": puzzle_hash.hex(), "include_spent_coins": include_spent_coins} if start_height is not None: d["start_height"] = start_height if end_height is not None: d["end_height"] = end_height return [ CoinRecord.from_json_dict(coin) for coin in ((await self.fetch("get_coin_records_by_puzzle_hash", d))["coin_records"]) ] async def get_coin_records_by_puzzle_hashes( self, puzzle_hashes: List[bytes32], include_spent_coins: bool = True, start_height: Optional[int] = None, end_height: Optional[int] = None, ) -> List: puzzle_hashes_hex = [ph.hex() for ph in puzzle_hashes] d = {"puzzle_hashes": puzzle_hashes_hex, "include_spent_coins": include_spent_coins} if start_height is not None: d["start_height"] = start_height if end_height is not None: d["end_height"] = end_height return [ CoinRecord.from_json_dict(coin) for coin in ((await self.fetch("get_coin_records_by_puzzle_hashes", d))["coin_records"]) ] async def get_additions_and_removals(self, header_hash: bytes32) -> Tuple[List[CoinRecord], List[CoinRecord]]: try: response = await self.fetch("get_additions_and_removals", {"header_hash": header_hash.hex()}) except Exception: return [], [] removals = [] additions = [] for coin_record in response["removals"]: removals.append(CoinRecord.from_json_dict(coin_record)) for coin_record in response["additions"]: additions.append(CoinRecord.from_json_dict(coin_record)) return additions, removals async def get_block_records(self, start: int, end: int) -> List: try: response = await self.fetch("get_block_records", {"start": start, "end": end}) if response["block_records"] is None: return [] except Exception: return [] # TODO: return block records return response["block_records"] async def push_tx(self, spend_bundle: SpendBundle): return await self.fetch("push_tx", {"spend_bundle": spend_bundle.to_json_dict()}) async def get_all_mempool_tx_ids(self) -> List[bytes32]: response = await self.fetch("get_all_mempool_tx_ids", {}) return [bytes32(hexstr_to_bytes(tx_id_hex)) for tx_id_hex in response["tx_ids"]] async def get_all_mempool_items(self) -> Dict[bytes32, Dict]: response: Dict = await self.fetch("get_all_mempool_items", {}) converted: Dict[bytes32, Dict] = {} for tx_id_hex, item in response["mempool_items"].items(): converted[bytes32(hexstr_to_bytes(tx_id_hex))] = item return converted async def get_mempool_item_by_tx_id(self, tx_id: bytes32) -> Optional[Dict]: try: response = await self.fetch("get_mempool_item_by_tx_id", {"tx_id": tx_id.hex()}) return response["mempool_item"] except Exception: return None
43.48366
115
0.658951
0aea17fdaae207fa49ab099ef1b725b16319069f
3,577
py
Python
mootdx/server.py
skanda-huayan/mootdx-1
73f07be7d031b2f05ce3e42330294417e614e7b0
[ "MIT" ]
null
null
null
mootdx/server.py
skanda-huayan/mootdx-1
73f07be7d031b2f05ce3e42330294417e614e7b0
[ "MIT" ]
null
null
null
mootdx/server.py
skanda-huayan/mootdx-1
73f07be7d031b2f05ce3e42330294417e614e7b0
[ "MIT" ]
1
2021-11-22T15:55:23.000Z
2021-11-22T15:55:23.000Z
import asyncio import functools import json import socket import time from functools import partial from mootdx.consts import CONFIG from mootdx.consts import EX_HOSTS from mootdx.consts import GP_HOSTS from mootdx.consts import HQ_HOSTS from mootdx.logger import log from mootdx.utils import get_config_path hosts = { 'HQ': [{'addr': hs[1], 'port': hs[2], 'time': 0, 'site': hs[0]} for hs in HQ_HOSTS], 'EX': [{'addr': hs[1], 'port': hs[2], 'time': 0, 'site': hs[0]} for hs in EX_HOSTS], 'GP': [{'addr': hs[1], 'port': hs[2], 'time': 0, 'site': hs[0]} for hs in GP_HOSTS], } results = {k: [] for k in hosts} def callback(res, key): result = res.result() if result.get('time'): results[key].append(result) log.debug('callback: {}', res.result()) def connect(proxy): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(3) start = time.perf_counter() sock.connect((proxy.get('addr'), int(proxy.get('port')))) sock.close() proxy['time'] = (time.perf_counter() - start) * 1000 log.info('{addr}:{port} 验证通过,响应时间:{time} ms.'.format(**proxy)) except socket.timeout as ex: log.info('{addr},{port} time out.'.format(**proxy)) proxy['time'] = None except ConnectionRefusedError as ex: log.info('{addr},{port} 验证失败.'.format(**proxy)) proxy['time'] = None finally: return proxy async def verify(proxy): result = await asyncio.get_event_loop().run_in_executor(None, functools.partial(connect, proxy=proxy)) return result def Server(index=None, limit=5, console=False, sync=True): _hosts = hosts[index] def async_event(): event = asyncio.get_event_loop() tasks = [] while len(_hosts) > 0: task = event.create_task(verify(_hosts.pop(0))) task.add_done_callback(partial(callback, key=index)) tasks.append(task) # event.is_closed() # event.is_running() event.run_until_complete(asyncio.wait(tasks)) global results if sync: results[index] = [connect(proxy) for proxy in _hosts] results[index] = [x for x in results[index] if x.get('time')] else: async_event() server = results[index] # 结果按响应时间从小到大排序 if console: from prettytable import PrettyTable server.sort(key=lambda item: item['time']) print('[√] 最优服务器:') t = PrettyTable(['Name', 'Addr', 'Port', 'Time']) t.align['Name'] = 'l' t.align['Addr'] = 'l' t.align['Port'] = 'l' t.align['Time'] = 'r' t.padding_width = 1 for host in server[: int(limit)]: t.add_row( [ host['site'], host['addr'], host['port'], '{:5.2f} ms'.format(host['time']), ] ) print(t) return [(item['addr'], item['port']) for item in server] def bestip(console=False, limit=5, sync=True) -> None: config_ = get_config_path('config.json') default = dict(CONFIG) for index in ['HQ', 'EX', 'GP']: try: data = Server(index=index, limit=limit, console=console, sync=sync) if data: default['BESTIP'][index] = data[0] except RuntimeError as ex: log.error('请手动运行`python -m mootdx bestip`') break json.dump(default, open(config_, 'w'), indent=2, ensure_ascii=False) if __name__ == '__main__': bestip()
26.69403
106
0.572267
c65bb08bc31597c765261bd189c458285d8152b9
12,598
py
Python
crosshair/util.py
samuelchassot/CrossHair
4eac7a23e470567cc23e6d0916ce6dd6820eacd8
[ "MIT" ]
785
2019-09-28T14:47:48.000Z
2022-03-24T15:04:03.000Z
crosshair/util.py
samuelchassot/CrossHair
4eac7a23e470567cc23e6d0916ce6dd6820eacd8
[ "MIT" ]
111
2019-10-19T14:43:03.000Z
2022-03-29T07:23:32.000Z
crosshair/util.py
samuelchassot/CrossHair
4eac7a23e470567cc23e6d0916ce6dd6820eacd8
[ "MIT" ]
36
2018-05-12T03:31:29.000Z
2022-03-02T14:07:16.000Z
import builtins import collections import contextlib import dataclasses import dis import importlib.util import inspect import functools import math import os import pathlib import re import sys import threading import time import traceback import types from types import TracebackType import typing from typing import ( Callable, Dict, Generator, Generic, Iterable, List, Mapping, Optional, Set, Tuple, Type, TypeVar, Union, cast, ) _DEBUG = False def is_iterable(o: object) -> bool: try: iter(o) # type: ignore return True except TypeError: return False def is_hashable(o: object) -> bool: return getattr(o, "__hash__", None) is not None def is_pure_python(obj: object) -> bool: if isinstance(obj, type): return True if "__dict__" in dir(obj) else hasattr(obj, "__slots__") elif callable(obj): return inspect.isfunction( obj ) # isfunction selects "user-defined" functions only else: return True def memo(f): """Decorate a function taking a single argument with a memoization decorator.""" saved = {} @functools.wraps(f) def memo_wrapper(a): if not a in saved: saved[a] = f(a) return saved[a] return memo_wrapper # Valid smtlib identifier chars: ~ ! @ $ % ^ & * _ - + = < > . ? / # See the section on "symbols" here: # https://smtlib.cs.uiowa.edu/papers/smt-lib-reference-v2.6-r2017-07-18.pdf _SMTLIB_TRANSLATION = str.maketrans("[],", "<>.", " ") def smtlib_typename(typ: Type) -> str: return name_of_type(typ).translate(_SMTLIB_TRANSLATION) def name_of_type(typ: Type) -> str: return typ.__name__ if hasattr(typ, "__name__") else str(typ).split(".")[-1] def samefile(f1: Optional[str], f2: Optional[str]) -> bool: try: return f1 is not None and f2 is not None and os.path.samefile(f1, f2) except FileNotFoundError: return False _SOURCE_CACHE: Dict[object, Tuple[str, int, Tuple[str, ...]]] = {} def sourcelines(thing: object) -> Tuple[str, int, Tuple[str, ...]]: # If it's a bound method, pull the function out: while hasattr(thing, "__func__"): thing = thing.__func__ # type: ignore # Unwrap decorators as necessary: while hasattr(thing, "__wrapped__"): thing = thing.__wrapped__ # type: ignore filename, start_line, lines = "<unknown file>", 0, () try: ret = _SOURCE_CACHE.get(thing, None) except TypeError: # some bound methods are undetectable (and not hashable) return (filename, start_line, lines) if ret is None: try: filename = inspect.getsourcefile(thing) # type: ignore (lines, start_line) = inspect.getsourcelines(thing) # type: ignore except (OSError, TypeError): pass ret = (filename, start_line, tuple(lines)) _SOURCE_CACHE[thing] = ret return ret def frame_summary_for_fn( fn: Callable, frames: traceback.StackSummary ) -> Tuple[str, int]: fn_name = fn.__name__ fn_file = cast(str, inspect.getsourcefile(fn)) for frame in reversed(frames): if frame.name == fn_name and samefile(frame.filename, fn_file): return (frame.filename, frame.lineno) return sourcelines(fn)[:2] def set_debug(debug: bool): global _DEBUG _DEBUG = debug def in_debug() -> bool: global _DEBUG return _DEBUG from crosshair.tracers import NoTracing def debug(*a): """ Print debugging information in CrossHair's nested log output. Arguments are serialized with ``str()`` and printed when running in CrossHair's verbose mode. Avoid passing symbolic values, as taking the string of a symbolic will change the path exploration that CrossHair normally takes, leading to different outcomes in verbose and non-verbose mode. """ if not _DEBUG: return with NoTracing(): stack = traceback.extract_stack() frame = stack[-2] indent = len(stack) - 3 print( "{:06.3f}|{}|{}() {}".format( time.monotonic(), " " * indent, frame.name, " ".join(map(str, a)) ), file=sys.stderr, ) TracebackLike = Union[None, TracebackType, Iterable[traceback.FrameSummary]] def test_stack(tb: TracebackLike = None) -> str: return tiny_stack(tb, ignore=re.compile("^$")) def tiny_stack(tb: TracebackLike = None, **kw) -> str: with NoTracing(): if tb is None: frames: Iterable[traceback.FrameSummary] = traceback.extract_stack()[:-1] elif isinstance(tb, TracebackType): frames = traceback.extract_tb(tb) else: frames = tb return _tiny_stack_frames(frames, **kw) def _tiny_stack_frames( frames: Iterable[traceback.FrameSummary], ignore=re.compile(r".*\b(crosshair|z3|typing_inspect|unittest)\b"), ) -> str: output: List[str] = [] ignore_ct = 0 for frame in frames: if ignore.match(frame.filename) and not frame.filename.endswith("_test.py"): ignore_ct += 1 else: if ignore_ct > 0: if output: output.append(f"(...x{ignore_ct})") ignore_ct = 0 filename = os.path.split(frame.filename)[1] output.append(f"({frame.name}@{filename}:{frame.lineno})") if ignore_ct > 0: output.append(f"(...x{ignore_ct})") return " ".join(output) @dataclasses.dataclass class CoverageResult: offsets_covered: Set[int] all_offsets: Set[int] opcode_coverage: float @contextlib.contextmanager def measure_fn_coverage(*fns: Callable): codeobjects = set(fn.__code__ for fn in fns) opcode_offsets = { code: set(i.offset for i in dis.get_instructions(code)) for code in codeobjects } offsets_seen: Dict[types.CodeType, Set[int]] = collections.defaultdict(set) previous_trace = sys.gettrace() # TODO: per-line stats would be nice too def trace(frame, event, arg): code = frame.f_code if code in codeobjects: frame.f_trace_opcodes = True if event == "opcode": assert frame.f_lasti in opcode_offsets[code] offsets_seen[code].add(frame.f_lasti) if previous_trace: previous_trace(frame, event, arg) # Discard the prior tracer's return value. # (because we want to be the top-level tracer) return trace else: if previous_trace: return previous_trace(frame, event, arg) else: return None sys.settrace(trace) def result_getter(fn: Optional[Callable] = None): if fn is None: assert len(fns) == 1 fn = fns[0] possible = opcode_offsets[fn.__code__] seen = offsets_seen[fn.__code__] return CoverageResult( offsets_covered=seen, all_offsets=possible, opcode_coverage=len(seen) / len(possible), ) try: yield result_getter finally: assert sys.gettrace() is trace sys.settrace(previous_trace) class ErrorDuringImport(Exception): pass @contextlib.contextmanager def add_to_pypath(*paths: Union[str, pathlib.Path]) -> Generator: old_path = sys.path[:] for path in paths: sys.path.insert(0, str(path)) try: yield finally: sys.path[:] = old_path class _TypingAccessDetector: accessed = False def __bool__(self): self.accessed = True return False @contextlib.contextmanager def typing_access_detector(): typing.TYPE_CHECKING = _TypingAccessDetector() try: yield typing.TYPE_CHECKING finally: typing.TYPE_CHECKING = False def import_module(module_name): with typing_access_detector() as detector: module = importlib.import_module(module_name) # It's common to avoid circular imports with TYPE_CHECKING guards. # We need those imports however, so we work around this by re-importing # modules that use such guards, with the TYPE_CHECKING flag turned on. # (see https://github.com/pschanely/CrossHair/issues/32) if detector.accessed: typing.TYPE_CHECKING = True try: importlib.reload(module) finally: typing.TYPE_CHECKING = False return module def load_file(filename: str) -> types.ModuleType: """ Load a module from a file. :raises ErrorDuringImport: if the file cannot be imported """ try: root_path, module_name = extract_module_from_file(filename) with add_to_pypath(root_path): return import_module(module_name) except Exception as e: raise ErrorDuringImport from e @contextlib.contextmanager def eval_friendly_repr(): """ Monkey-patch repr() to make some cases more ammenible to eval(). In particular: * object instances repr as "object()" rather than "<object object at ...>" * non-finite floats like inf repr as 'float("inf")' rather than just 'inf' >>> with eval_friendly_repr(): ... repr(object()) 'object()' >>> with eval_friendly_repr(): ... repr(float("nan")) 'float("nan")' >>> # returns to original behavior afterwards: >>> repr(float("nan")) 'nan' >>> repr(object())[:20] '<object object at 0x' """ _orig = builtins.repr OVERRIDES = { object: lambda o: "object()", float: lambda o: _orig(o) if math.isfinite(o) else f'float("{o}")', } @functools.wraps(_orig) def _eval_friendly_repr(obj): typ = type(obj) if typ in OVERRIDES: return OVERRIDES[typ](obj) return _orig(obj) builtins.repr = _eval_friendly_repr try: yield finally: assert builtins.repr is _eval_friendly_repr builtins.repr = _orig def extract_module_from_file(filename: str) -> Tuple[str, str]: module_name = inspect.getmodulename(filename) dirs = [] if module_name and module_name != "__init__": dirs.append(module_name) path = os.path.split(os.path.realpath(filename))[0] while os.path.exists(os.path.join(path, "__init__.py")): path, cur = os.path.split(path) dirs.append(cur) dirs.reverse() module = ".".join(dirs) return path, module _T = TypeVar("_T") class DynamicScopeVar(Generic[_T]): """ Manage a hidden value that can get passed through the callstack. This has similar downsides to threadlocals/globals; it should be used sparingly. >>> _VAR = DynamicScopeVar(int) >>> with _VAR.open(42): ... _VAR.get() 42 """ def __init__(self, typ: Type[_T], name_for_debugging: str = ""): self._local = threading.local() self._name = name_for_debugging @contextlib.contextmanager def open(self, value: _T, reentrant: bool = True): _local = self._local old_value = getattr(_local, "value", None) if not reentrant: assert old_value is None, f"Already in a {self._name} context" _local.value = value try: yield value finally: assert getattr(_local, "value", None) is value _local.value = old_value def get(self, default: Optional[_T] = None) -> _T: ret = getattr(self._local, "value", None) if ret is not None: return ret if default is not None: return default assert False, f"Not in a {self._name} context" def get_if_in_scope(self) -> Optional[_T]: return getattr(self._local, "value", None) class AttributeHolder: def __init__(self, attrs: Mapping[str, object]): for (k, v) in attrs.items(): self.__dict__[k] = v class CrosshairInternal(Exception): def __init__(self, *a): Exception.__init__(self, *a) debug("CrosshairInternal", str(self)) class UnexploredPath(Exception): pass class UnknownSatisfiability(UnexploredPath): def __init__(self, *a): Exception.__init__(self, *a) debug("UnknownSatisfiability", str(self)) class PathTimeout(UnexploredPath): pass class CrosshairUnsupported(UnexploredPath): def __init__(self, *a): debug("CrosshairUnsupported: ", str(self)) debug(" Stack trace:\n" + "".join(traceback.format_stack())) class IgnoreAttempt(Exception): def __init__(self, *a): debug("IgnoreAttempt", str(self))
26.861407
87
0.626449
7cb63687735a335a296acb58732ed51cffb7c432
58,384
py
Python
holoviews/core/dimension.py
TheoMathurin/holoviews
0defcef994d6dd6d2054f75a0e332d02d121f8b0
[ "BSD-3-Clause" ]
864
2019-11-13T08:18:27.000Z
2022-03-31T13:36:13.000Z
holoviews/core/dimension.py
chrinide/holoviews
e1234a60ae0809ac561c204b1998dff0452b2bf0
[ "BSD-3-Clause" ]
1,117
2019-11-12T16:15:59.000Z
2022-03-30T22:57:59.000Z
holoviews/core/dimension.py
chrinide/holoviews
e1234a60ae0809ac561c204b1998dff0452b2bf0
[ "BSD-3-Clause" ]
180
2019-11-19T16:44:44.000Z
2022-03-28T22:49:18.000Z
""" Provides Dimension objects for tracking the properties of a value, axis or map dimension. Also supplies the Dimensioned abstract baseclass for classes that accept Dimension values. """ import re import datetime as dt import weakref from operator import itemgetter from collections import defaultdict, Counter from itertools import chain from functools import partial import param import numpy as np from . import util from .accessors import Opts, Apply, Redim from .options import Store, Options, cleanup_custom_options from .pprint import PrettyPrinter from .tree import AttrTree from .util import OrderedDict, bytes_to_unicode # Alias parameter support for pickle loading ALIASES = {'key_dimensions': 'kdims', 'value_dimensions': 'vdims', 'constant_dimensions': 'cdims'} title_format = "{name}: {val}{unit}" redim = Redim # pickle compatibility - remove in 2.0 def param_aliases(d): """ Called from __setstate__ in LabelledData in order to load old pickles with outdated parameter names. Warning: We want to keep pickle hacking to a minimum! """ for old, new in ALIASES.items(): old_param = '_%s_param_value' % old new_param = '_%s_param_value' % new if old_param in d: d[new_param] = d.pop(old_param) return d def asdim(dimension): """Convert the input to a Dimension. Args: dimension: tuple, dict or string type to convert to Dimension Returns: A Dimension object constructed from the dimension spec. No copy is performed if the input is already a Dimension. """ if isinstance(dimension, Dimension): return dimension elif isinstance(dimension, (tuple, dict, str)): return Dimension(dimension) else: raise ValueError('%s type could not be interpreted as Dimension. ' 'Dimensions must be declared as a string, tuple, ' 'dictionary or Dimension type.') def dimension_name(dimension): """Return the Dimension.name for a dimension-like object. Args: dimension: Dimension or dimension string, tuple or dict Returns: The name of the Dimension or what would be the name if the input as converted to a Dimension. """ if isinstance(dimension, Dimension): return dimension.name elif isinstance(dimension, str): return dimension elif isinstance(dimension, tuple): return dimension[0] elif isinstance(dimension, dict): return dimension['name'] elif dimension is None: return None else: raise ValueError('%s type could not be interpreted as Dimension. ' 'Dimensions must be declared as a string, tuple, ' 'dictionary or Dimension type.' % type(dimension).__name__) def process_dimensions(kdims, vdims): """Converts kdims and vdims to Dimension objects. Args: kdims: List or single key dimension(s) specified as strings, tuples dicts or Dimension objects. vdims: List or single value dimension(s) specified as strings, tuples dicts or Dimension objects. Returns: Dictionary containing kdims and vdims converted to Dimension objects: {'kdims': [Dimension('x')], 'vdims': [Dimension('y')] """ dimensions = {} for group, dims in [('kdims', kdims), ('vdims', vdims)]: if dims is None: continue elif isinstance(dims, (tuple, str, Dimension, dict)): dims = [dims] elif not isinstance(dims, list): raise ValueError("%s argument expects a Dimension or list of dimensions, " "specified as tuples, strings, dictionaries or Dimension " "instances, not a %s type. Ensure you passed the data as the " "first argument." % (group, type(dims).__name__)) for dim in dims: if not isinstance(dim, (tuple, str, Dimension, dict)): raise ValueError('Dimensions must be defined as a tuple, ' 'string, dictionary or Dimension instance, ' 'found a %s type.' % type(dim).__name__) dimensions[group] = [asdim(d) for d in dims] return dimensions class Dimension(param.Parameterized): """ Dimension objects are used to specify some important general features that may be associated with a collection of values. For instance, a Dimension may specify that a set of numeric values actually correspond to 'Height' (dimension name), in units of meters, with a descriptive label 'Height of adult males'. All dimensions object have a name that identifies them and a label containing a suitable description. If the label is not explicitly specified it matches the name. These two parameters define the core identity of the dimension object and must match if two dimension objects are to be considered equivalent. All other parameters are considered optional metadata and are not used when testing for equality. Unlike all the other parameters, these core parameters can be used to construct a Dimension object from a tuple. This format is sufficient to define an identical Dimension: Dimension('a', label='Dimension A') == Dimension(('a', 'Dimension A')) Everything else about a dimension is considered to reflect non-semantic preferences. Examples include the default value (which may be used in a visualization to set an initial slider position), how the value is to rendered as text (which may be used to specify the printed floating point precision) or a suitable range of values to consider for a particular analysis. Units ----- Full unit support with automated conversions are on the HoloViews roadmap. Once rich unit objects are supported, the unit (or more specifically the type of unit) will be part of the core dimension specification used to establish equality. Until this feature is implemented, there are two auxiliary parameters that hold some partial information about the unit: the name of the unit and whether or not it is cyclic. The name of the unit is used as part of the pretty-printed representation and knowing whether it is cyclic is important for certain operations. """ name = param.String(doc=""" Short name associated with the Dimension, such as 'height' or 'weight'. Valid Python identifiers make good names, because they can be used conveniently as a keyword in many contexts.""") label = param.String(default=None, doc=""" Unrestricted label used to describe the dimension. A label should succinctly describe the dimension and may contain any characters, including Unicode and LaTeX expression.""") cyclic = param.Boolean(default=False, doc=""" Whether the range of this feature is cyclic such that the maximum allowed value (defined by the range parameter) is continuous with the minimum allowed value.""") default = param.Parameter(default=None, doc=""" Default value of the Dimension which may be useful for widget or other situations that require an initial or default value.""") nodata = param.Integer(default=None, doc=""" Optional missing-data value for integer data. If non-None, data with this value will be replaced with NaN.""") range = param.Tuple(default=(None, None), doc=""" Specifies the minimum and maximum allowed values for a Dimension. None is used to represent an unlimited bound.""") soft_range = param.Tuple(default=(None, None), doc=""" Specifies a minimum and maximum reference value, which may be overridden by the data.""") step = param.Number(default=None, doc=""" Optional floating point step specifying how frequently the underlying space should be sampled. May be used to define a discrete sampling over the range.""") type = param.Parameter(default=None, doc=""" Optional type associated with the Dimension values. The type may be an inbuilt constructor (such as int, str, float) or a custom class object.""") unit = param.String(default=None, allow_None=True, doc=""" Optional unit string associated with the Dimension. For instance, the string 'm' may be used represent units of meters and 's' to represent units of seconds.""") value_format = param.Callable(default=None, doc=""" Formatting function applied to each value before display.""") values = param.List(default=[], doc=""" Optional specification of the allowed value set for the dimension that may also be used to retain a categorical ordering.""") # Defines default formatting by type type_formatters = {} unit_format = ' ({unit})' presets = {} # A dictionary-like mapping name, (name,) or # (name, unit) to a preset Dimension object def __init__(self, spec, **params): """ Initializes the Dimension object with the given name. """ if 'name' in params: raise KeyError('Dimension name must only be passed as the positional argument') if isinstance(spec, Dimension): existing_params = dict(spec.param.get_param_values()) elif (spec, params.get('unit', None)) in self.presets.keys(): preset = self.presets[(str(spec), str(params['unit']))] existing_params = dict(preset.param.get_param_values()) elif isinstance(spec, dict): existing_params = spec elif spec in self.presets: existing_params = dict(self.presets[spec].param.get_param_values()) elif (spec,) in self.presets: existing_params = dict(self.presets[(spec,)].param.get_param_values()) else: existing_params = {} all_params = dict(existing_params, **params) if isinstance(spec, tuple): if not all(isinstance(s, str) for s in spec) or len(spec) != 2: raise ValueError("Dimensions specified as a tuple must be a tuple " "consisting of the name and label not: %s" % str(spec)) name, label = spec all_params['name'] = name all_params['label'] = label if 'label' in params and (label != params['label']): if params['label'] != label: self.param.warning( 'Using label as supplied by keyword ({!r}), ignoring ' 'tuple value {!r}'.format(params['label'], label)) all_params['label'] = params['label'] elif isinstance(spec, str): all_params['name'] = spec all_params['label'] = params.get('label', spec) if all_params['name'] == '': raise ValueError('Dimension name cannot be the empty string') if all_params['label'] in ['', None]: raise ValueError('Dimension label cannot be None or the empty string') values = params.get('values', []) if isinstance(values, str) and values == 'initial': self.param.warning("The 'initial' string for dimension values " "is no longer supported.") values = [] all_params['values'] = list(util.unique_array(values)) super().__init__(**all_params) if self.default is not None: if self.values and self.default not in values: raise ValueError('%r default %s not found in declared values: %s' % (self, self.default, self.values)) elif (self.range != (None, None) and ((self.range[0] is not None and self.default < self.range[0]) or (self.range[0] is not None and self.default > self.range[1]))): raise ValueError('%r default %s not in declared range: %s' % (self, self.default, self.range)) @property def spec(self): """"Returns the Dimensions tuple specification Returns: tuple: Dimension tuple specification """ return (self.name, self.label) def clone(self, spec=None, **overrides): """Clones the Dimension with new parameters Derive a new Dimension that inherits existing parameters except for the supplied, explicit overrides Args: spec (tuple, optional): Dimension tuple specification **overrides: Dimension parameter overrides Returns: Cloned Dimension object """ settings = dict(self.param.get_param_values(), **overrides) if spec is None: spec = (self.name, overrides.get('label', self.label)) if 'label' in overrides and isinstance(spec, str) : spec = (spec, overrides['label']) elif 'label' in overrides and isinstance(spec, tuple) : if overrides['label'] != spec[1]: self.param.warning( 'Using label as supplied by keyword ({!r}), ignoring ' 'tuple value {!r}'.format(overrides['label'], spec[1])) spec = (spec[0], overrides['label']) return self.__class__(spec, **{k:v for k,v in settings.items() if k not in ['name', 'label']}) def __hash__(self): """Hashes object on Dimension spec, i.e. (name, label). """ return hash(self.spec) def __setstate__(self, d): """ Compatibility for pickles before alias attribute was introduced. """ super().__setstate__(d) if '_label_param_value' not in d: self.label = self.name def __eq__(self, other): "Implements equals operator including sanitized comparison." if isinstance(other, Dimension): return self.spec == other.spec # For comparison to strings. Name may be sanitized. return other in [self.name, self.label, util.dimension_sanitizer(self.name)] def __ne__(self, other): "Implements not equal operator including sanitized comparison." return not self.__eq__(other) def __lt__(self, other): "Dimensions are sorted alphanumerically by name" return self.name < other.name if isinstance(other, Dimension) else self.name < other def __str__(self): return self.name def __repr__(self): return self.pprint() @property def pprint_label(self): "The pretty-printed label string for the Dimension" unit = ('' if self.unit is None else type(self.unit)(self.unit_format).format(unit=self.unit)) return bytes_to_unicode(self.label) + bytes_to_unicode(unit) def pprint(self): changed = dict(self.param.get_param_values(onlychanged=True)) if len(set([changed.get(k, k) for k in ['name','label']])) == 1: return 'Dimension({spec})'.format(spec=repr(self.name)) params = self.param.objects('existing') ordering = sorted( sorted(changed.keys()), key=lambda k: ( -float('inf') if params[k].precedence is None else params[k].precedence)) kws = ", ".join('%s=%r' % (k, changed[k]) for k in ordering if k != 'name') return 'Dimension({spec}, {kws})'.format(spec=repr(self.name), kws=kws) def pprint_value(self, value, print_unit=False): """Applies the applicable formatter to the value. Args: value: Dimension value to format Returns: Formatted dimension value """ own_type = type(value) if self.type is None else self.type formatter = (self.value_format if self.value_format else self.type_formatters.get(own_type)) if formatter: if callable(formatter): formatted_value = formatter(value) elif isinstance(formatter, str): if isinstance(value, (dt.datetime, dt.date)): formatted_value = value.strftime(formatter) elif isinstance(value, np.datetime64): formatted_value = util.dt64_to_dt(value).strftime(formatter) elif re.findall(r"\{(\w+)\}", formatter): formatted_value = formatter.format(value) else: formatted_value = formatter % value else: formatted_value = bytes_to_unicode(value) if print_unit and self.unit is not None: formatted_value = formatted_value + ' ' + bytes_to_unicode(self.unit) return formatted_value def pprint_value_string(self, value): """Pretty print the dimension value and unit with title_format Args: value: Dimension value to format Returns: Formatted dimension value string with unit """ unit = '' if self.unit is None else ' ' + bytes_to_unicode(self.unit) value = self.pprint_value(value) return title_format.format(name=bytes_to_unicode(self.label), val=value, unit=unit) class LabelledData(param.Parameterized): """ LabelledData is a mix-in class designed to introduce the group and label parameters (and corresponding methods) to any class containing data. This class assumes that the core data contents will be held in the attribute called 'data'. Used together, group and label are designed to allow a simple and flexible means of addressing data. For instance, if you are collecting the heights of people in different demographics, you could specify the values of your objects as 'Height' and then use the label to specify the (sub)population. In this scheme, one object may have the parameters set to [group='Height', label='Children'] and another may use [group='Height', label='Adults']. Note: Another level of specification is implicit in the type (i.e class) of the LabelledData object. A full specification of a LabelledData object is therefore given by the tuple (<type>, <group>, label>). This additional level of specification is used in the traverse method. Any strings can be used for the group and label, but it can be convenient to use a capitalized string of alphanumeric characters, in which case the keys used for matching in the matches and traverse method will correspond exactly to {type}.{group}.{label}. Otherwise the strings provided will be sanitized to be valid capitalized Python identifiers, which works fine but can sometimes be confusing. """ group = param.String(default='LabelledData', constant=True, doc=""" A string describing the type of data contained by the object. By default this will typically mirror the class name.""") label = param.String(default='', constant=True, doc=""" Optional label describing the data, typically reflecting where or how it was measured. The label should allow a specific measurement or dataset to be referenced for a given group.""") _deep_indexable = False def __init__(self, data, id=None, plot_id=None, **params): """ All LabelledData subclasses must supply data to the constructor, which will be held on the .data attribute. This class also has an id instance attribute, which may be set to associate some custom options with the object. """ self.data = data self._id = None self.id = id self._plot_id = plot_id or util.builtins.id(self) if isinstance(params.get('label',None), tuple): (alias, long_name) = params['label'] util.label_sanitizer.add_aliases(**{alias:long_name}) params['label'] = long_name if isinstance(params.get('group',None), tuple): (alias, long_name) = params['group'] util.group_sanitizer.add_aliases(**{alias:long_name}) params['group'] = long_name super().__init__(**params) if not util.group_sanitizer.allowable(self.group): raise ValueError("Supplied group %r contains invalid characters." % self.group) elif not util.label_sanitizer.allowable(self.label): raise ValueError("Supplied label %r contains invalid characters." % self.label) @property def id(self): return self._id @id.setter def id(self, opts_id): """Handles tracking and cleanup of custom ids.""" old_id = self._id self._id = opts_id if old_id is not None: cleanup_custom_options(old_id) if opts_id is not None and opts_id != old_id: if opts_id not in Store._weakrefs: Store._weakrefs[opts_id] = [] ref = weakref.ref(self, partial(cleanup_custom_options, opts_id)) Store._weakrefs[opts_id].append(ref) def clone(self, data=None, shared_data=True, new_type=None, link=True, *args, **overrides): """Clones the object, overriding data and parameters. Args: data: New data replacing the existing data shared_data (bool, optional): Whether to use existing data new_type (optional): Type to cast object to link (bool, optional): Whether clone should be linked Determines whether Streams and Links attached to original object will be inherited. *args: Additional arguments to pass to constructor **overrides: New keyword arguments to pass to constructor Returns: Cloned object """ params = dict(self.param.get_param_values()) if new_type is None: clone_type = self.__class__ else: clone_type = new_type new_params = new_type.param.objects('existing') params = {k: v for k, v in params.items() if k in new_params} if params.get('group') == self.param.objects('existing')['group'].default: params.pop('group') settings = dict(params, **overrides) if 'id' not in settings: settings['id'] = self.id if data is None and shared_data: data = self.data if link: settings['plot_id'] = self._plot_id # Apply name mangling for __ attribute pos_args = getattr(self, '_' + type(self).__name__ + '__pos_params', []) return clone_type(data, *args, **{k:v for k,v in settings.items() if k not in pos_args}) def relabel(self, label=None, group=None, depth=0): """Clone object and apply new group and/or label. Applies relabeling to children up to the supplied depth. Args: label (str, optional): New label to apply to returned object group (str, optional): New group to apply to returned object depth (int, optional): Depth to which relabel will be applied If applied to container allows applying relabeling to contained objects up to the specified depth Returns: Returns relabelled object """ new_data = self.data if (depth > 0) and getattr(self, '_deep_indexable', False): new_data = [] for k, v in self.data.items(): relabelled = v.relabel(group=group, label=label, depth=depth-1) new_data.append((k, relabelled)) keywords = [('label', label), ('group', group)] kwargs = {k: v for k, v in keywords if v is not None} return self.clone(new_data, **kwargs) def matches(self, spec): """Whether the spec applies to this object. Args: spec: A function, spec or type to check for a match * A 'type[[.group].label]' string which is compared against the type, group and label of this object * A function which is given the object and returns a boolean. * An object type matched using isinstance. Returns: bool: Whether the spec matched this object. """ if callable(spec) and not isinstance(spec, type): return spec(self) elif isinstance(spec, type): return isinstance(self, spec) specification = (self.__class__.__name__, self.group, self.label) split_spec = tuple(spec.split('.')) if not isinstance(spec, tuple) else spec split_spec, nocompare = zip(*((None, True) if s == '*' or s is None else (s, False) for s in split_spec)) if all(nocompare): return True match_fn = itemgetter(*(idx for idx, nc in enumerate(nocompare) if not nc)) self_spec = match_fn(split_spec) unescaped_match = match_fn(specification[:len(split_spec)]) == self_spec if unescaped_match: return True sanitizers = [util.sanitize_identifier, util.group_sanitizer, util.label_sanitizer] identifier_specification = tuple(fn(ident, escape=False) for ident, fn in zip(specification, sanitizers)) identifier_match = match_fn(identifier_specification[:len(split_spec)]) == self_spec return identifier_match def traverse(self, fn=None, specs=None, full_breadth=True): """Traverses object returning matching items Traverses the set of children of the object, collecting the all objects matching the defined specs. Each object can be processed with the supplied function. Args: fn (function, optional): Function applied to matched objects specs: List of specs to match Specs must be types, functions or type[.group][.label] specs to select objects to return, by default applies to all objects. full_breadth: Whether to traverse all objects Whether to traverse the full set of objects on each container or only the first. Returns: list: List of objects that matched """ if fn is None: fn = lambda x: x if specs is not None and not isinstance(specs, (list, set, tuple)): specs = [specs] accumulator = [] matches = specs is None if not matches: for spec in specs: matches = self.matches(spec) if matches: break if matches: accumulator.append(fn(self)) # Assumes composite objects are iterables if self._deep_indexable: for el in self: if el is None: continue accumulator += el.traverse(fn, specs, full_breadth) if not full_breadth: break return accumulator def map(self, map_fn, specs=None, clone=True): """Map a function to all objects matching the specs Recursively replaces elements using a map function when the specs apply, by default applies to all objects, e.g. to apply the function to all contained Curve objects: dmap.map(fn, hv.Curve) Args: map_fn: Function to apply to each object specs: List of specs to match List of types, functions or type[.group][.label] specs to select objects to return, by default applies to all objects. clone: Whether to clone the object or transform inplace Returns: Returns the object after the map_fn has been applied """ if specs is not None and not isinstance(specs, (list, set, tuple)): specs = [specs] applies = specs is None or any(self.matches(spec) for spec in specs) if self._deep_indexable: deep_mapped = self.clone(shared_data=False) if clone else self for k, v in self.items(): new_val = v.map(map_fn, specs, clone) if new_val is not None: deep_mapped[k] = new_val if applies: deep_mapped = map_fn(deep_mapped) return deep_mapped else: return map_fn(self) if applies else self def __getstate__(self): "Ensures pickles save options applied to this objects." obj_dict = self.__dict__.copy() try: if Store.save_option_state and (obj_dict.get('_id', None) is not None): custom_key = '_custom_option_%d' % obj_dict['_id'] if custom_key not in obj_dict: obj_dict[custom_key] = {backend:s[obj_dict['_id']] for backend,s in Store._custom_options.items() if obj_dict['_id'] in s} else: obj_dict['_id'] = None except: self.param.warning("Could not pickle custom style information.") return obj_dict def __setstate__(self, d): "Restores options applied to this object." d = param_aliases(d) # Backwards compatibility for objects before id was made a property opts_id = d['_id'] if '_id' in d else d.pop('id', None) try: load_options = Store.load_counter_offset is not None if load_options: matches = [k for k in d if k.startswith('_custom_option')] for match in matches: custom_id = int(match.split('_')[-1])+Store.load_counter_offset if not isinstance(d[match], dict): # Backward compatibility before multiple backends backend_info = {'matplotlib':d[match]} else: backend_info = d[match] for backend, info in backend_info.items(): if backend not in Store._custom_options: Store._custom_options[backend] = {} Store._custom_options[backend][custom_id] = info if backend_info: if custom_id not in Store._weakrefs: Store._weakrefs[custom_id] = [] ref = weakref.ref(self, partial(cleanup_custom_options, custom_id)) Store._weakrefs[opts_id].append(ref) d.pop(match) if opts_id is not None: opts_id += Store.load_counter_offset except: self.param.warning("Could not unpickle custom style information.") d['_id'] = opts_id self.__dict__.update(d) super().__setstate__({}) class Dimensioned(LabelledData): """ Dimensioned is a base class that allows the data contents of a class to be associated with dimensions. The contents associated with dimensions may be partitioned into one of three types * key dimensions: These are the dimensions that can be indexed via the __getitem__ method. Dimension objects supporting key dimensions must support indexing over these dimensions and may also support slicing. This list ordering of dimensions describes the positional components of each multi-dimensional indexing operation. For instance, if the key dimension names are 'weight' followed by 'height' for Dimensioned object 'obj', then obj[80,175] indexes a weight of 80 and height of 175. Accessed using either kdims. * value dimensions: These dimensions correspond to any data held on the Dimensioned object not in the key dimensions. Indexing by value dimension is supported by dimension name (when there are multiple possible value dimensions); no slicing semantics is supported and all the data associated with that dimension will be returned at once. Note that it is not possible to mix value dimensions and deep dimensions. Accessed using either vdims. * deep dimensions: These are dynamically computed dimensions that belong to other Dimensioned objects that are nested in the data. Objects that support this should enable the _deep_indexable flag. Note that it is not possible to mix value dimensions and deep dimensions. Accessed using either ddims. Dimensioned class support generalized methods for finding the range and type of values along a particular Dimension. The range method relies on the appropriate implementation of the dimension_values methods on subclasses. The index of an arbitrary dimension is its positional index in the list of all dimensions, starting with the key dimensions, followed by the value dimensions and ending with the deep dimensions. """ cdims = param.Dict(default=OrderedDict(), doc=""" The constant dimensions defined as a dictionary of Dimension:value pairs providing additional dimension information about the object. Aliased with constant_dimensions.""") kdims = param.List(bounds=(0, None), constant=True, doc=""" The key dimensions defined as list of dimensions that may be used in indexing (and potential slicing) semantics. The order of the dimensions listed here determines the semantics of each component of a multi-dimensional indexing operation. Aliased with key_dimensions.""") vdims = param.List(bounds=(0, None), constant=True, doc=""" The value dimensions defined as the list of dimensions used to describe the components of the data. If multiple value dimensions are supplied, a particular value dimension may be indexed by name after the key dimensions. Aliased with value_dimensions.""") group = param.String(default='Dimensioned', constant=True, doc=""" A string describing the data wrapped by the object.""") __abstract = True _dim_groups = ['kdims', 'vdims', 'cdims', 'ddims'] _dim_aliases = dict(key_dimensions='kdims', value_dimensions='vdims', constant_dimensions='cdims', deep_dimensions='ddims') def __init__(self, data, kdims=None, vdims=None, **params): params.update(process_dimensions(kdims, vdims)) if 'cdims' in params: params['cdims'] = {d if isinstance(d, Dimension) else Dimension(d): val for d, val in params['cdims'].items()} super().__init__(data, **params) self.ndims = len(self.kdims) cdims = [(d.name, val) for d, val in self.cdims.items()] self._cached_constants = OrderedDict(cdims) self._settings = None # Instantiate accessors @property def apply(self): return Apply(self) @property def opts(self): return Opts(self) @property def redim(self): return Redim(self) def _valid_dimensions(self, dimensions): """Validates key dimension input Returns kdims if no dimensions are specified""" if dimensions is None: dimensions = self.kdims elif not isinstance(dimensions, list): dimensions = [dimensions] valid_dimensions = [] for dim in dimensions: if isinstance(dim, Dimension): dim = dim.name if dim not in self.kdims: raise Exception("Supplied dimensions %s not found." % dim) valid_dimensions.append(dim) return valid_dimensions @property def ddims(self): "The list of deep dimensions" if self._deep_indexable and self: return self.values()[0].dimensions() else: return [] def dimensions(self, selection='all', label=False): """Lists the available dimensions on the object Provides convenient access to Dimensions on nested Dimensioned objects. Dimensions can be selected by their type, i.e. 'key' or 'value' dimensions. By default 'all' dimensions are returned. Args: selection: Type of dimensions to return The type of dimension, i.e. one of 'key', 'value', 'constant' or 'all'. label: Whether to return the name, label or Dimension Whether to return the Dimension objects (False), the Dimension names (True/'name') or labels ('label'). Returns: List of Dimension objects or their names or labels """ if label in ['name', True]: label = 'short' elif label == 'label': label = 'long' elif label: raise ValueError("label needs to be one of True, False, 'name' or 'label'") lambdas = {'k': (lambda x: x.kdims, {'full_breadth': False}), 'v': (lambda x: x.vdims, {}), 'c': (lambda x: x.cdims, {})} aliases = {'key': 'k', 'value': 'v', 'constant': 'c'} if selection in ['all', 'ranges']: groups = [d for d in self._dim_groups if d != 'cdims'] dims = [dim for group in groups for dim in getattr(self, group)] elif isinstance(selection, list): dims = [dim for group in selection for dim in getattr(self, '%sdims' % aliases.get(group))] elif aliases.get(selection) in lambdas: selection = aliases.get(selection, selection) lmbd, kwargs = lambdas[selection] key_traversal = self.traverse(lmbd, **kwargs) dims = [dim for keydims in key_traversal for dim in keydims] else: raise KeyError("Invalid selection %r, valid selections include" "'all', 'value' and 'key' dimensions" % repr(selection)) return [(dim.label if label == 'long' else dim.name) if label else dim for dim in dims] def get_dimension(self, dimension, default=None, strict=False): """Get a Dimension object by name or index. Args: dimension: Dimension to look up by name or integer index default (optional): Value returned if Dimension not found strict (bool, optional): Raise a KeyError if not found Returns: Dimension object for the requested dimension or default """ if dimension is not None and not isinstance(dimension, (int, str, Dimension)): raise TypeError('Dimension lookup supports int, string, ' 'and Dimension instances, cannot lookup ' 'Dimensions using %s type.' % type(dimension).__name__) all_dims = self.dimensions() if isinstance(dimension, int): if 0 <= dimension < len(all_dims): return all_dims[dimension] elif strict: raise KeyError("Dimension %r not found" % dimension) else: return default if isinstance(dimension, Dimension): dims = [d for d in all_dims if dimension == d] if strict and not dims: raise KeyError("%r not found." % dimension) elif dims: return dims[0] else: return None else: dimension = dimension_name(dimension) name_map = {dim.spec: dim for dim in all_dims} name_map.update({dim.name: dim for dim in all_dims}) name_map.update({dim.label: dim for dim in all_dims}) name_map.update({util.dimension_sanitizer(dim.name): dim for dim in all_dims}) if strict and dimension not in name_map: raise KeyError("Dimension %r not found." % dimension) else: return name_map.get(dimension, default) def get_dimension_index(self, dimension): """Get the index of the requested dimension. Args: dimension: Dimension to look up by name or by index Returns: Integer index of the requested dimension """ if isinstance(dimension, int): if (dimension < (self.ndims + len(self.vdims)) or dimension < len(self.dimensions())): return dimension else: return IndexError('Dimension index out of bounds') dim = dimension_name(dimension) try: dimensions = self.kdims+self.vdims return [i for i, d in enumerate(dimensions) if d == dim][0] except IndexError: raise Exception("Dimension %s not found in %s." % (dim, self.__class__.__name__)) def get_dimension_type(self, dim): """Get the type of the requested dimension. Type is determined by Dimension.type attribute or common type of the dimension values, otherwise None. Args: dimension: Dimension to look up by name or by index Returns: Declared type of values along the dimension """ dim_obj = self.get_dimension(dim) if dim_obj and dim_obj.type is not None: return dim_obj.type dim_vals = [type(v) for v in self.dimension_values(dim)] if len(set(dim_vals)) == 1: return dim_vals[0] else: return None def __getitem__(self, key): """ Multi-dimensional indexing semantics is determined by the list of key dimensions. For instance, the first indexing component will index the first key dimension. After the key dimensions are given, *either* a value dimension name may follow (if there are multiple value dimensions) *or* deep dimensions may then be listed (for applicable deep dimensions). """ return self def select(self, selection_specs=None, **kwargs): """Applies selection by dimension name Applies a selection along the dimensions of the object using keyword arguments. The selection may be narrowed to certain objects using selection_specs. For container objects the selection will be applied to all children as well. Selections may select a specific value, slice or set of values: * value: Scalar values will select rows along with an exact match, e.g.: ds.select(x=3) * slice: Slices may be declared as tuples of the upper and lower bound, e.g.: ds.select(x=(0, 3)) * values: A list of values may be selected using a list or set, e.g.: ds.select(x=[0, 1, 2]) Args: selection_specs: List of specs to match on A list of types, functions, or type[.group][.label] strings specifying which objects to apply the selection on. **selection: Dictionary declaring selections by dimension Selections can be scalar values, tuple ranges, lists of discrete values and boolean arrays Returns: Returns an Dimensioned object containing the selected data or a scalar if a single value was selected """ if selection_specs is not None and not isinstance(selection_specs, (list, tuple)): selection_specs = [selection_specs] # Apply all indexes applying on this object vdims = self.vdims+['value'] if self.vdims else [] kdims = self.kdims local_kwargs = {k: v for k, v in kwargs.items() if k in kdims+vdims} # Check selection_spec applies if selection_specs is not None: if not isinstance(selection_specs, (list, tuple)): selection_specs = [selection_specs] matches = any(self.matches(spec) for spec in selection_specs) else: matches = True # Apply selection to self if local_kwargs and matches: ndims = self.ndims if any(d in self.vdims for d in kwargs): ndims = len(self.kdims+self.vdims) select = [slice(None) for _ in range(ndims)] for dim, val in local_kwargs.items(): if dim == 'value': select += [val] else: if isinstance(val, tuple): val = slice(*val) select[self.get_dimension_index(dim)] = val if self._deep_indexable: selection = self.get(tuple(select), None) if selection is None: selection = self.clone(shared_data=False) else: selection = self[tuple(select)] else: selection = self if not isinstance(selection, Dimensioned): return selection elif type(selection) is not type(self) and isinstance(selection, Dimensioned): # Apply the selection on the selected object of a different type dimensions = selection.dimensions() + ['value'] if any(kw in dimensions for kw in kwargs): selection = selection.select(selection_specs=selection_specs, **kwargs) elif isinstance(selection, Dimensioned) and selection._deep_indexable: # Apply the deep selection on each item in local selection items = [] for k, v in selection.items(): dimensions = v.dimensions() + ['value'] if any(kw in dimensions for kw in kwargs): items.append((k, v.select(selection_specs=selection_specs, **kwargs))) else: items.append((k, v)) selection = selection.clone(items) return selection def dimension_values(self, dimension, expanded=True, flat=True): """Return the values along the requested dimension. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values Whether to return the expanded values, behavior depends on the type of data: * Columnar: If false returns unique values * Geometry: If false returns scalar values per geometry * Gridded: If false returns 1D coordinates flat (bool, optional): Whether to flatten array Returns: NumPy array of values along the requested dimension """ val = self._cached_constants.get(dimension, None) if val: return np.array([val]) else: raise Exception("Dimension %s not found in %s." % (dimension, self.__class__.__name__)) def range(self, dimension, data_range=True, dimension_range=True): """Return the lower and upper bounds of values along dimension. Args: dimension: The dimension to compute the range on. data_range (bool): Compute range from data values dimension_range (bool): Include Dimension ranges Whether to include Dimension range and soft_range in range calculation Returns: Tuple containing the lower and upper bound """ dimension = self.get_dimension(dimension) if dimension is None or (not data_range and not dimension_range): return (None, None) elif all(util.isfinite(v) for v in dimension.range) and dimension_range: return dimension.range elif data_range: if dimension in self.kdims+self.vdims: dim_vals = self.dimension_values(dimension.name) lower, upper = util.find_range(dim_vals) else: dname = dimension.name match_fn = lambda x: dname in x.kdims + x.vdims range_fn = lambda x: x.range(dname) ranges = self.traverse(range_fn, [match_fn]) lower, upper = util.max_range(ranges) else: lower, upper = (np.NaN, np.NaN) if not dimension_range: return lower, upper return util.dimension_range(lower, upper, dimension.range, dimension.soft_range) def __repr__(self): return PrettyPrinter.pprint(self) def __str__(self): return repr(self) def __unicode__(self): return PrettyPrinter.pprint(self) def options(self, *args, clone=True, **kwargs): """Applies simplified option definition returning a new object. Applies options on an object or nested group of objects in a flat format returning a new object with the options applied. If the options are to be set directly on the object a simple format may be used, e.g.: obj.options(cmap='viridis', show_title=False) If the object is nested the options must be qualified using a type[.group][.label] specification, e.g.: obj.options('Image', cmap='viridis', show_title=False) or using: obj.options({'Image': dict(cmap='viridis', show_title=False)}) Identical to the .opts method but returns a clone of the object by default. Args: *args: Sets of options to apply to object Supports a number of formats including lists of Options objects, a type[.group][.label] followed by a set of keyword options to apply and a dictionary indexed by type[.group][.label] specs. backend (optional): Backend to apply options to Defaults to current selected backend clone (bool, optional): Whether to clone object Options can be applied inplace with clone=False **kwargs: Keywords of options Set of options to apply to the object Returns: Returns the cloned object with the options applied """ backend = kwargs.get('backend', None) if not (args or kwargs): options = None elif args and isinstance(args[0], str): options = {args[0]: kwargs} elif args and isinstance(args[0], list): if kwargs: raise ValueError('Please specify a list of option objects, or kwargs, but not both') options = args[0] elif args and [k for k in kwargs.keys() if k != 'backend']: raise ValueError("Options must be defined in one of two formats. " "Either supply keywords defining the options for " "the current object, e.g. obj.options(cmap='viridis'), " "or explicitly define the type, e.g. " "obj.options({'Image': {'cmap': 'viridis'}}). " "Supplying both formats is not supported.") elif args and all(isinstance(el, dict) for el in args): if len(args) > 1: self.param.warning('Only a single dictionary can be passed ' 'as a positional argument. Only processing ' 'the first dictionary') options = [Options(spec, **kws) for spec,kws in args[0].items()] elif args: options = list(args) elif kwargs: options = {type(self).__name__: kwargs} from ..util import opts if options is None: expanded_backends = [(backend, {})] elif isinstance(options, list): # assuming a flat list of Options objects expanded_backends = opts._expand_by_backend(options, backend) else: expanded_backends = [(backend, opts._expand_options(options, backend))] obj = self for backend, expanded in expanded_backends: obj = obj.opts._dispatch_opts(expanded, backend=backend, clone=clone) return obj def _repr_mimebundle_(self, include=None, exclude=None): """ Resolves the class hierarchy for the class rendering the object using any display hooks registered on Store.display hooks. The output of all registered display_hooks is then combined and returned. """ return Store.render(self) class ViewableElement(Dimensioned): """ A ViewableElement is a dimensioned datastructure that may be associated with a corresponding atomic visualization. An atomic visualization will display the data on a single set of axes (i.e. excludes multiple subplots that are displayed at once). The only new parameter introduced by ViewableElement is the title associated with the object for display. """ __abstract = True _auxiliary_component = False group = param.String(default='ViewableElement', constant=True) class ViewableTree(AttrTree, Dimensioned): """ A ViewableTree is an AttrTree with Viewable objects as its leaf nodes. It combines the tree like data structure of a tree while extending it with the deep indexable properties of Dimensioned and LabelledData objects. """ group = param.String(default='ViewableTree', constant=True) _deep_indexable = True def __init__(self, items=None, identifier=None, parent=None, **kwargs): if items and all(isinstance(item, Dimensioned) for item in items): items = self._process_items(items) params = {p: kwargs.pop(p) for p in list(self.param)+['id', 'plot_id'] if p in kwargs} AttrTree.__init__(self, items, identifier, parent, **kwargs) Dimensioned.__init__(self, self.data, **params) @classmethod def _process_items(cls, vals): "Processes list of items assigning unique paths to each." if type(vals) is cls: return vals.data elif not isinstance(vals, (list, tuple)): vals = [vals] items = [] counts = defaultdict(lambda: 1) cls._unpack_paths(vals, items, counts) items = cls._deduplicate_items(items) return items def __setstate__(self, d): """ Ensure that object does not try to reference its parent during unpickling. """ parent = d.pop('parent', None) d['parent'] = None super(AttrTree, self).__setstate__(d) self.__dict__['parent'] = parent @classmethod def _deduplicate_items(cls, items): "Deduplicates assigned paths by incrementing numbering" counter = Counter([path[:i] for path, _ in items for i in range(1, len(path)+1)]) if sum(counter.values()) == len(counter): return items new_items = [] counts = defaultdict(lambda: 0) for i, (path, item) in enumerate(items): if counter[path] > 1: path = path + (util.int_to_roman(counts[path]+1),) else: inc = 1 while counts[path]: path = path[:-1] + (util.int_to_roman(counts[path]+inc),) inc += 1 new_items.append((path, item)) counts[path] += 1 return new_items @classmethod def _unpack_paths(cls, objs, items, counts): """ Recursively unpacks lists and ViewableTree-like objects, accumulating into the supplied list of items. """ if type(objs) is cls: objs = objs.items() for item in objs: path, obj = item if isinstance(item, tuple) else (None, item) if type(obj) is cls: cls._unpack_paths(obj, items, counts) continue new = path is None or len(path) == 1 path = util.get_path(item) if new else path new_path = util.make_path_unique(path, counts, new) items.append((new_path, obj)) @property def uniform(self): "Whether items in tree have uniform dimensions" from .traversal import uniform return uniform(self) def dimension_values(self, dimension, expanded=True, flat=True): """Return the values along the requested dimension. Concatenates values on all nodes with requested dimension. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values Whether to return the expanded values, behavior depends on the type of data: * Columnar: If false returns unique values * Geometry: If false returns scalar values per geometry * Gridded: If false returns 1D coordinates flat (bool, optional): Whether to flatten array Returns: NumPy array of values along the requested dimension """ dimension = self.get_dimension(dimension, strict=True).name all_dims = self.traverse(lambda x: [d.name for d in x.dimensions()]) if dimension in chain.from_iterable(all_dims): values = [el.dimension_values(dimension) for el in self if dimension in el.dimensions(label=True)] vals = np.concatenate(values) return vals if expanded else util.unique_array(vals) else: return super().dimension_values( dimension, expanded, flat) def __len__(self): return len(self.data)
40.600834
100
0.602888
2437819d891e245092147a7835d9287fcb89c249
1,631
py
Python
diagnostic/controllerslocal.py
sjjhsjjh/blender-driver
7e164f4049f1bb7292c835c084eaed5faf7be5fd
[ "MIT" ]
2
2017-08-21T13:42:05.000Z
2020-06-14T11:02:43.000Z
diagnostic/controllerslocal.py
sjjhsjjh/blender-driver
7e164f4049f1bb7292c835c084eaed5faf7be5fd
[ "MIT" ]
null
null
null
diagnostic/controllerslocal.py
sjjhsjjh/blender-driver
7e164f4049f1bb7292c835c084eaed5faf7be5fd
[ "MIT" ]
null
null
null
#!/usr/bin/python # (c) 2017 Jim Hawkins. MIT licensed, see https://opensource.org/licenses/MIT # Part of Blender Driver, see https://github.com/sjjhsjjh/blender-driver """Python module for the Blender Games Engine controller interface. This module is a diagnostic and demonstration version of the proper blender_driver.controllers module. This code demonstrates: - Access to a local variable set when the controllers module is imported. The value of the local variable isn't changed in this code, so it's not very useful. Trying to change the value is demonstrated in the controllersunboundlocal.py file in this directory. This module can only be used from within the Blender Game Engine.""" # Exit if run other than as a module. if __name__ == '__main__': print(__doc__) raise SystemExit(1) # Local imports. # # Proper controllers, which have some utility subroutines. import blender_driver.controllers counter = -1 def initialise(controller): """Controller entry point for the first ever tick.""" # Assume there is only a single sensor if not controller.sensors[0].positive: # Only take action on the positive transition. return try: # Next line prints the expected counter value, -1. print('initialise 0', counter) print('Terminate the game engine manually, with the Escape key.') except: blender_driver.controllers.terminate_engine() raise def tick(controller): pass def keyboard(controller): pass # # Next line prints the expected counter value, -1. print("".join(('Controllers module "', __name__, '" ', str(counter))))
31.365385
77
0.726548
b6c3567d49a36ad4b4182fd330ff17c219c76594
780
py
Python
dashboard/views/admin_allegation_request_analysis_view.py
invinst/CPDB
c2d8ae8888b13d956cc1068742f18d45736d4121
[ "Apache-2.0" ]
16
2016-05-20T09:03:32.000Z
2020-09-13T14:23:06.000Z
dashboard/views/admin_allegation_request_analysis_view.py
invinst/CPDB
c2d8ae8888b13d956cc1068742f18d45736d4121
[ "Apache-2.0" ]
2
2016-05-24T01:44:14.000Z
2016-06-17T22:19:45.000Z
dashboard/views/admin_allegation_request_analysis_view.py
invinst/CPDB
c2d8ae8888b13d956cc1068742f18d45736d4121
[ "Apache-2.0" ]
2
2016-10-10T16:14:19.000Z
2020-10-26T00:17:02.000Z
import json from django.http import HttpResponse from django.views.generic import View from dashboard.query_builders import AllegationDocumentQueryBuilder, DOCUMENT_REQUEST_FILTERS from document.models import Document class AdminAllegationRequestAnalysisView(View): def get(self, request): document_type = request.GET.get('type', 'CR') document_request_analysis = {} for request_type in DOCUMENT_REQUEST_FILTERS: queries = AllegationDocumentQueryBuilder().build({ 'request_type': request_type, 'document_type': document_type }) document_request_analysis[request_type] = Document.objects.filter(queries).count() return HttpResponse(json.dumps(document_request_analysis))
33.913043
94
0.724359
42da7ad13f0bb7028784b6bd98c5db8636f3278d
3,384
py
Python
whats_fresh/whats_fresh_api/tests/views/entry/test_inline_video.py
osu-cass/whats-fresh-api
0ace76c3d7d423e95d5e3b3c7cd0f74abcf975bd
[ "Apache-2.0" ]
4
2015-08-20T19:38:03.000Z
2016-01-20T18:52:24.000Z
whats_fresh/whats_fresh_api/tests/views/entry/test_inline_video.py
osu-cass/whats-fresh-api
0ace76c3d7d423e95d5e3b3c7cd0f74abcf975bd
[ "Apache-2.0" ]
39
2015-01-08T23:50:47.000Z
2021-01-05T20:19:15.000Z
whats_fresh/whats_fresh_api/tests/views/entry/test_inline_video.py
osu-cass/whats-fresh-api
0ace76c3d7d423e95d5e3b3c7cd0f74abcf975bd
[ "Apache-2.0" ]
8
2015-03-07T23:52:30.000Z
2015-12-25T04:25:23.000Z
from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh.whats_fresh_api.models import Video from django.contrib.auth.models import User, Group class InlineVideoTestCase(TestCase): """ Test that the Inline Video form works as expected. Things tested: URLs reverse correctly The outputted popup form has the correct form fields POSTing "correct" data will result in the creation of a new object with the specified details POSTing data with all fields missing (hitting "save" without entering data) returns the same field with notations of missing fields """ def setUp(self): user = User.objects.create_user( 'temporary', 'temporary@gmail.com', 'temporary') user.save() admin_group = Group(name='Administration Users') admin_group.save() user.groups.add(admin_group) response = self.client.login( username='temporary', password='temporary') self.assertEqual(response, True) def test_not_logged_in(self): self.client.logout() response = self.client.get( reverse('video_ajax')) self.assertRedirects(response, '/login?next=/entry/stories/new/videos/new') def test_url_endpoint(self): url = reverse('video_ajax') self.assertEqual(url, '/entry/stories/new/videos/new') def test_form_fields(self): """ Tests to see if the form contains all of the right fields """ response = self.client.get(reverse('video_ajax')) fields = {'video': 'input', 'name': 'input', 'caption': 'input'} form = response.context['video_form'] for field in fields: # for the Edit tests, you should be able to access # form[field].value self.assertIn(fields[field], str(form[field])) def test_successful_video_creation(self): """ POST a proper "new video" command to the server, and see if the new video appears in the database. All optional fields are null. """ Video.objects.all().delete() # Data that we'll post to the server to get the new video created inline_video = { 'caption': "A thrilling display of utmost might", 'name': "You won't believe number 3!", 'video': 'http://www.youtube.com/watch?v=dQw4w9WgXcQ'} self.client.post(reverse('video_ajax'), inline_video) video = Video.objects.all()[0] for field in inline_video: self.assertEqual( getattr(video, field), inline_video[field]) def test_no_data_error(self): """ POST a "new video" command to the server missing all of the required fields, and test to see what the error comes back as. """ # Create a list of all objects before sending bad POST data all_videos = Video.objects.all() response = self.client.post(reverse('video_ajax')) required_fields = ['video'] for field_name in required_fields: self.assertIn(field_name, response.context['video_form'].errors) # Test that we didn't add any new objects self.assertEqual( list(Video.objects.all()), list(all_videos))
34.886598
77
0.621158
ca255ef32e3ef71f6a6b06002c3f1969698657c4
382
py
Python
events/wagtail_hooks.py
kinaklub/next.filmfest.by
b537c0d2dac4195e9e7b460c569007d20a5954e7
[ "Unlicense" ]
7
2016-07-18T07:37:37.000Z
2022-03-23T08:12:04.000Z
events/wagtail_hooks.py
kinaklub/next.filmfest.by
b537c0d2dac4195e9e7b460c569007d20a5954e7
[ "Unlicense" ]
119
2015-11-08T07:16:44.000Z
2022-03-11T23:25:53.000Z
events/wagtail_hooks.py
kinaklub/next.filmfest.by
b537c0d2dac4195e9e7b460c569007d20a5954e7
[ "Unlicense" ]
3
2016-07-21T17:22:31.000Z
2016-10-04T08:38:48.000Z
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register from events.models import Venue class VenueModelAdmin(ModelAdmin): model = Venue menu_label = 'Venues' menu_icon = 'site' menu_order = 270 list_display = ('name_en', 'name_be', 'name_ru') search_fields = ('name_en', 'name_be', 'name_ru') modeladmin_register(VenueModelAdmin)
25.466667
78
0.732984
31ca0b14cf180998d2e1b96bd8b34032a31724f3
820
py
Python
https_example.py
Abhi256207/ECEx73hw4-1
913ae3e3317074cdc4388c7dea5d6a1f7fb793a1
[ "MIT" ]
null
null
null
https_example.py
Abhi256207/ECEx73hw4-1
913ae3e3317074cdc4388c7dea5d6a1f7fb793a1
[ "MIT" ]
null
null
null
https_example.py
Abhi256207/ECEx73hw4-1
913ae3e3317074cdc4388c7dea5d6a1f7fb793a1
[ "MIT" ]
null
null
null
# ABHIMANYU MANI : Inser your name here import socket, ssl context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_REQUIRED context.check_hostname = True context.load_default_certs() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssl_sock = context.wrap_socket(s, server_hostname='https://github.com/Abhi256207/ECEx73hw4-1.git') try: ssl_sock.connect(('https://github.com/Abhi256207/ECEx73hw4-1.git', 443)) ssl_sock.settimeout(1.0) ssl_sock.sendall("GET /articles/which-remote-url-should-i-use/ HTTP/1.1\r\nHostname:https://github.com/Abhi256207/ECEx73hw4-1.git\r\n\r\n") while 1: try: data = ssl_sock.recv(2048).strip() print data except: break except: print "Socket connection error!" finally: ssl_sock.close()
31.538462
143
0.706098
ba7b6c04280557ec59c1a25690d161e2cd66283e
916
py
Python
nowdawn/precipitation.py
fossabot/pyNowDawn
ac553872afe3303cce1e4b98c9dc533de809b37b
[ "MIT" ]
null
null
null
nowdawn/precipitation.py
fossabot/pyNowDawn
ac553872afe3303cce1e4b98c9dc533de809b37b
[ "MIT" ]
null
null
null
nowdawn/precipitation.py
fossabot/pyNowDawn
ac553872afe3303cce1e4b98c9dc533de809b37b
[ "MIT" ]
null
null
null
"""""" #!/usr/bin/env python # -*- coding: utf-8 -*- class Precipitation: """""" def __init__(self, intensity=None, unit="C", precip_type=None, probability=0.0): """""" self.intensity = intensity self.unit = unit self.precip_type = precip_type self.probability = probability def unit(self): """""" return self.unit def type(self): """""" return self.precip_type def probability(self): """""" return self.probability def __str__(self): """""" if self.intensity is None: return "None" return self.intensity def __repr__(self): """""" return str('{intensity=' + str(self.intensity) + ', precip_type=' + \ str(self.precip_type) + ', probability=' + str(self.probability) + \ ', precip_unit=' + str(self.unit) + '}')
23.487179
84
0.522926
f1e1d691bb260dd7367ccb861fc5db0fb75baf6d
1,751
py
Python
hdp-ambari-mpack-3.1.4.0/stacks/HDP/3.0/services/DRUID/package/scripts/service_check.py
dropoftruth/dfhz_hdp_mpack
716f0396dce25803365c1aed9904b74fbe396f79
[ "Apache-2.0" ]
2
2020-07-23T03:28:33.000Z
2022-02-20T15:39:50.000Z
hdp-ambari-mpack-3.1.4.0/stacks/HDP/3.0/services/DRUID/package/scripts/service_check.py
dropoftruth/dfhz_hdp_mpack
716f0396dce25803365c1aed9904b74fbe396f79
[ "Apache-2.0" ]
13
2019-06-05T07:47:00.000Z
2019-12-29T08:29:27.000Z
hdp-ambari-mpack-3.1.4.0/stacks/HDP/3.0/services/DRUID/package/scripts/service_check.py
dropoftruth/dfhz_hdp_mpack
716f0396dce25803365c1aed9904b74fbe396f79
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 resource_management.libraries.script.script import Script from resource_management.libraries.functions.format import format from resource_management.core.resources.system import Execute class ServiceCheck(Script): def service_check(self, env): import params env.set_params(params) self.checkComponent(params, "druid_coordinator", "druid-coordinator") self.checkComponent(params, "druid_overlord", "druid-overlord") def checkComponent(self, params, component_name, config_name): component_port = params.config['configurations'][format('{config_name}')]['druid.port'] for component_host in params.config['clusterHostInfo'][format('{component_name}_hosts')]: Execute(format( "curl -s -o /dev/null -w'%{{http_code}}' --negotiate -u: -k {component_host}:{component_port}/status/health | grep 200"), tries=10, try_sleep=3, logoutput=True) if __name__ == "__main__": ServiceCheck().execute()
38.911111
129
0.758424
0739b5dc4601775deaf2bd48478258f51255bfc3
7,413
py
Python
gatkcwlgenerator/main.py
wtsi-hgi/PY
36f8d95a2fae310795bdf6f16169363b7450fc68
[ "MIT" ]
8
2017-10-12T06:36:30.000Z
2020-06-09T15:32:07.000Z
gatkcwlgenerator/main.py
wtsi-hgi/PY
36f8d95a2fae310795bdf6f16169363b7450fc68
[ "MIT" ]
17
2017-09-08T10:59:12.000Z
2020-04-08T18:07:05.000Z
gatkcwlgenerator/main.py
wtsi-hgi/PY
36f8d95a2fae310795bdf6f16169363b7450fc68
[ "MIT" ]
1
2017-11-22T04:02:23.000Z
2017-11-22T04:02:23.000Z
#!/bin/python import argparse import json import logging import os import shutil import sys import time from typing import * import coloredlogs from ruamel import yaml from .gatk_tool_to_cwl import gatk_tool_to_cwl from .common import GATKVersion from .web_to_gatk_tool import get_tool_name, get_gatk_links, get_gatk_tool, get_extra_arguments _logger: logging.Logger = logging.getLogger("gatkcwlgenerator") _logger.addHandler(logging.StreamHandler()) class CmdLineArguments(argparse.Namespace): version: str verbose: bool output_dir: str include: Optional[str] dev: bool use_cache: Optional[str] no_docker: bool docker_image_name: str gatk_command: str class OutputWriter: def __init__(self, cmd_line_options: CmdLineArguments) -> None: # Get current directory and make folders for files json_dir = os.path.join(cmd_line_options.output_dir, "json") cwl_dir = os.path.join(cmd_line_options.output_dir, "cwl") try: os.makedirs(json_dir) os.makedirs(cwl_dir) except OSError: if cmd_line_options.dev: # Remove existing generated files if the folder already exists, for testing shutil.rmtree(json_dir) shutil.rmtree(cwl_dir) os.makedirs(json_dir) os.makedirs(cwl_dir) else: raise self._json_dir = json_dir self._cwl_dir = cwl_dir def write_cwl_file(self, cwl_dict: Dict, tool_name: str) -> None: cwl_path = os.path.join(self._cwl_dir, tool_name + ".cwl") _logger.info(f"Writing CWL file to {cwl_path}") with open(cwl_path, "w") as file: yaml.round_trip_dump(cwl_dict, file) def write_gatk_json_file(self, gatk_json_dict: Dict, tool_name: str) -> None: gatk_json_path = os.path.join(self._json_dir, tool_name + ".json") _logger.info(f"Writing GATK JSON file to {gatk_json_path}") with open(gatk_json_path, "w") as file: json.dump(gatk_json_dict, file) def should_generate_file(tool_url, gatk_version: GATKVersion, include_pattern: str = None) -> bool: no_ext_url = tool_url[:-len(".php.json" if gatk_version.is_3() else ".json")] return include_pattern is None or no_ext_url.endswith(include_pattern) def main(cmd_line_options: CmdLineArguments) -> None: start = time.time() gatk_version = GATKVersion(cmd_line_options.version) output_writer = OutputWriter(cmd_line_options) gatk_links = get_gatk_links(gatk_version) extra_arguments = get_extra_arguments( gatk_version, gatk_links ) have_generated_file = False annotation_names = [get_tool_name(url) for url in gatk_links.annotator_urls] for tool_url in gatk_links.tool_urls: if should_generate_file(tool_url, gatk_version, cmd_line_options.include): have_generated_file = True gatk_tool = get_gatk_tool(tool_url, extra_arguments=extra_arguments) output_writer.write_gatk_json_file(gatk_tool.original_dict, gatk_tool.name) cwl = gatk_tool_to_cwl(gatk_tool, cmd_line_options, annotation_names) output_writer.write_cwl_file(cwl, gatk_tool.name) if not have_generated_file: _logger.warning("No files have been generated. Check the include pattern is correct") end = time.time() _logger.info(f"Completed in {end - start:.2f} seconds") def gatk_cwl_generator(**cmd_line_options) -> None: """ Programmatic entry to gatk_cwl_generator. This converts the object to cmd line flags and passes it though the command line interface, to apply defaults """ args = [] for key, value in cmd_line_options.items(): if isinstance(value, bool): if value: args.append("--" + key) else: args.append("--" + key) args.append(str(value)) cmdline_main(args) def cmdline_main(args=None) -> None: """ Function to be called when this is invoked on the command line. """ if args is None: args = sys.argv[1:] default_cache_location = "cache" parser = argparse.ArgumentParser(description='Generates CWL files from the GATK documentation') parser.add_argument("--version", "-v", dest='version', default="3.5-0", help="Sets the version of GATK to parse documentation for. Default is 3.5-0") parser.add_argument("--verbose", dest='verbose', action="store_true", help="Set the logging to be verbose. Default is False.") parser.add_argument('--out', "-o", dest='output_dir', help="Sets the output directory for generated files. Default is ./gatk_cmdline_tools/<VERSION>/") parser.add_argument('--include', dest='include', help="Only generate this file (note, CommandLineGATK has to be generated for v3.x)") parser.add_argument("--dev", dest="dev", action="store_true", help="Enable --use_cache and overwriting of the generated files (for development purposes). " + "Requires requests_cache to be installed") parser.add_argument("--use_cache", dest="use_cache", nargs="?", const=default_cache_location, metavar="CACHE_LOCATION", help="Use requests_cache, using the cache at CACHE_LOCATION, or 'cache' if not specified. Default is False.") parser.add_argument("--no_docker", dest="no_docker", action="store_true", help="Make the generated CWL files not use Docker containers. Default is False.") parser.add_argument("--docker_image_name", "-c", dest="docker_image_name", help="Docker image name for generated CWL files. Default is 'broadinstitute/gatk3:<VERSION>' " + "for version 3.x and 'broadinstitute/gatk:<VERSION>' for 4.x") parser.add_argument("--gatk_command", "-l", dest="gatk_command", help="Command to launch GATK. Default is 'java -jar /usr/GenomeAnalysisTK.jar' for GATK 3.x and 'java -jar /gatk/gatk.jar' for GATK 4.x") cmd_line_options = parser.parse_args(args, namespace=CmdLineArguments()) log_format = "%(asctime)s %(name)s[%(process)d] %(levelname)s %(message)s" version = GATKVersion(cmd_line_options.version) if cmd_line_options.verbose: coloredlogs.install(level='DEBUG', logger=_logger, fmt=log_format) else: coloredlogs.install(level='WARNING', logger=_logger, fmt=log_format) if not cmd_line_options.output_dir: cmd_line_options.output_dir = os.getcwd() + '/gatk_cmdline_tools/' + cmd_line_options.version if not cmd_line_options.docker_image_name: if version.is_3(): cmd_line_options.docker_image_name = "broadinstitute/gatk3:" + cmd_line_options.version else: cmd_line_options.docker_image_name = "broadinstitute/gatk:" + cmd_line_options.version if not cmd_line_options.gatk_command: if version.is_3(): cmd_line_options.gatk_command = "java -jar /usr/GenomeAnalysisTK.jar" else: cmd_line_options.gatk_command = "java -jar /gatk/gatk.jar" if cmd_line_options.dev: cmd_line_options.use_cache = default_cache_location if cmd_line_options.use_cache: import requests_cache requests_cache.install_cache(cmd_line_options.use_cache) # Decreases the time to run dramatically main(cmd_line_options) if __name__ == '__main__': cmdline_main()
37.251256
145
0.689599
0eb4adb10e3b18d26555a787d77a8eb4d26172b5
4,850
py
Python
DNSIR/database/genDB.py
aasensio/DeepLearning
71838115ce93e0ca96c8314cff3f07de1d64c235
[ "MIT" ]
null
null
null
DNSIR/database/genDB.py
aasensio/DeepLearning
71838115ce93e0ca96c8314cff3f07de1d64c235
[ "MIT" ]
null
null
null
DNSIR/database/genDB.py
aasensio/DeepLearning
71838115ce93e0ca96c8314cff3f07de1d64c235
[ "MIT" ]
null
null
null
import numpy as np # import matplotlib.pyplot as pl # import sys from mpi4py import MPI from enum import IntEnum import pyiacsun as ps import h5py # from ipdb import set_trace as stop class tags(IntEnum): READY = 0 DONE = 1 EXIT = 2 START = 3 nBlocks = 100 nSizeBlock = 1000 n_profiles = nBlocks * nSizeBlock # Hinode's wavelength axis is 112 in length hinode_lambda = np.loadtxt('wavelengthHinode.txt') center = 6301.5080 initial = np.min(hinode_lambda - center) * 1e3 final = np.max(hinode_lambda - center) * 1e3 step = (hinode_lambda[1] - hinode_lambda[0]) * 1e3 lines = [['200,201', initial, step, final]] n_lambda = ps.radtran.initializeSIR(lines) hsra = np.loadtxt('hsra_64.model', skiprows=2, dtype='float32')[::-1] logTau = hsra[:,0] nz = len(logTau) model = np.zeros((nz,7), dtype='float32') model[:,0] = logTau psf = np.loadtxt('PSF.dat', dtype=np.float32) ps.radtran.setPSF(psf[:,0].flatten(), psf[:,1].flatten()) def compute(pars): n_sizeblock, n_par = pars.shape stokesOut = np.zeros((n_sizeblock,4,n_lambda)) for i in range(n_sizeblock): out = ps.radtran.buildModel(logTau, nodes_T=[pars[i,0],pars[i,1],pars[i,2]], nodes_vmic=[pars[i,3]], nodes_B=[pars[i,4],pars[i,5]], nodes_v=[pars[i,6],pars[i,7]], nodes_thB=[pars[i,8],pars[i,9]], nodes_phiB=[pars[i,10],pars[i,11]], var_T=hsra[:,1]) model[:,1:] = out stokes = ps.radtran.synthesizeSIR(model) stokesOut[i,:,:] = stokes[1:,:] return stokesOut # T, vmic, B, v, thB, phiB lower = np.asarray([-3000.0, -1500.0, -3000.0, 0.0, 0.0, 0.0, -7.0, -7.0, 0.0, 0.0, 0.0, 0.0]) upper = np.asarray([3000.0, 3000.0, 5000.0, 4.0, 3000.0, 3000.0, 7.0, 7.0, 180.0, 180.0, 180.0, 180.0]) n_par = 12 # Initializations and preliminaries comm = MPI.COMM_WORLD # get MPI communicator object size = comm.size # total number of processes rank = comm.rank # rank of this process status = MPI.Status() # get MPI status object if rank == 0: f = h5py.File('/net/viga/scratch1/deepLearning/DNSIR/database/database_sir.h5', 'w') databaseStokes = f.create_dataset("stokes", (n_profiles, 4, n_lambda), dtype='float32') databaseLambda = f.create_dataset("lambda", (n_lambda,), dtype='float32') databasePars = f.create_dataset("parameters", (n_profiles, n_par)) databaseLambda[:] = hinode_lambda # Master process executes code below tasks = [] for i in range(nBlocks): rnd = np.random.rand(nSizeBlock,n_par) pars = (upper - lower)[None,:] * rnd + lower[None,:] tasks.append(pars) task_index = 0 num_workers = size - 1 closed_workers = 0 print("*** Master starting with {0} workers".format(num_workers)) while closed_workers < num_workers: dataReceived = comm.recv(source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG, status=status) source = status.Get_source() tag = status.Get_tag() if tag == tags.READY: # Worker is ready, so send it a task if task_index < len(tasks): dataToSend = {'index': task_index, 'parameters': tasks[task_index]} comm.send(dataToSend, dest=source, tag=tags.START) print(" * MASTER : sending task {0}/{1} to worker {2}".format(task_index, nBlocks, source), flush=True) task_index += 1 else: comm.send(None, dest=source, tag=tags.EXIT) elif tag == tags.DONE: stokes = dataReceived['stokes'] index = dataReceived['index'] pars = dataReceived['parameters'] databaseStokes[index*nSizeBlock:(index+1)*nSizeBlock,:,:] = stokes databasePars[index*nSizeBlock:(index+1)*nSizeBlock,:] = pars print(" * MASTER : got block {0} from worker {1} - saved from {2} to {3}".format(index, source, index*nSizeBlock, (index+1)*nSizeBlock), flush=True) elif tag == tags.EXIT: print(" * MASTER : worker {0} exited.".format(source)) closed_workers += 1 print("Master finishing") f.close() else: # Worker processes execute code below name = MPI.Get_processor_name() while True: comm.send(None, dest=0, tag=tags.READY) dataReceived = comm.recv(source=0, tag=MPI.ANY_TAG, status=status) tag = status.Get_tag() if tag == tags.START: # Do the work here task_index = dataReceived['index'] task = dataReceived['parameters'] stokes = compute(task) dataToSend = {'index': task_index, 'stokes': stokes, 'parameters': task} comm.send(dataToSend, dest=0, tag=tags.DONE) elif tag == tags.EXIT: break comm.send(None, dest=0, tag=tags.EXIT)
33.916084
160
0.610103
1a92536e42f876a46180e65d19d00f55dce68e90
3,882
py
Python
scripts/logreg_sgd_sklearn.py
always-newbie161/pyprobml
eb70c84f9618d68235ef9ba7da147c009b2e4a80
[ "MIT" ]
2
2021-08-22T14:40:18.000Z
2021-12-07T02:46:00.000Z
scripts/logreg_sgd_sklearn.py
always-newbie161/pyprobml
eb70c84f9618d68235ef9ba7da147c009b2e4a80
[ "MIT" ]
9
2021-03-31T20:18:21.000Z
2022-03-12T00:52:47.000Z
scripts/logreg_sgd_sklearn.py
always-newbie161/pyprobml
eb70c84f9618d68235ef9ba7da147c009b2e4a80
[ "MIT" ]
1
2021-06-21T01:18:07.000Z
2021-06-21T01:18:07.000Z
# Compare various online solvers (SGD, SAG) on various classification # datasets using multinomial logisti regression with L2 regularizer. #https://scikit-learn.org/stable/modules/linear_model.html import numpy as np import sklearn.preprocessing from sklearn.linear_model import LogisticRegression from sklearn.linear_model import SGDClassifier #from lightning.classification import SGDClassifier as SGDClassifierLGT from sklearn import datasets from sklearn.model_selection import train_test_split import time """ iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first two features. #X = iris.data # all 4 features y = iris.target # multiclass # BFGS gets 10 errors, SGD/OVO gets 20! #y = (iris.target==2) # make into a binary problem # class 0: both get 0 errors, # class 1: both get 15 err # class 2: bfgs gets 8, sgd gets 10 """ """ digits = datasets.load_digits() X, y = digits.data, digits.target # (1797, 64) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42) max_iter = 20 """ from sklearn.datasets import fetch_openml mnist = fetch_openml('mnist_784', version=1, cache=True) X, y = mnist["data"], mnist["target"] X = X / 255 # convert to real in [0,1] y = y.astype(np.uint8) print(X.shape) # (70000, 784) # Standard train/ test split X_train, X_test = X[:60000], X[60000:] y_train, y_test = y[:60000], y[60000:] #https://scikit-learn.org/stable/auto_examples/linear_model/plot_sparse_logistic_regression_mnist.html from sklearn.utils import check_random_state random_state = check_random_state(0) permutation = random_state.permutation(X.shape[0]) X = X[permutation] y = y[permutation] train_samples = 10000 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=train_samples, test_size=10000) scaler = sklearn.preprocessing.StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) max_iter = 10 # L2-regularizer is alpha=1/C for sklearn # Note that alpha is internally multiplied by 1/N before being used #https://github.com/scikit-learn/scikit-learn/blob/a24c8b464d094d2c468a16ea9f8bf8d42d949f84/sklearn/linear_model/sag.py#L244 #https://stats.stackexchange.com/questions/216095/how-does-alpha-relate-to-c-in-scikit-learns-sgdclassifier #1. / C_svr ~ 1. / C_svc ~ 1. / C_logistic ~ alpha_elastic_net * n_samples ~ alpha_lasso * n_samples ~ alpha_sgd * n_samples ~ alpha_ridge Ntrain = np.shape(X_train)[0] l2reg = 1e-2 alpha = l2reg * Ntrain solvers = [] if Ntrain < 2000: solvers.append( ('BFGS', LogisticRegression( C=1/alpha, penalty='l2', solver='lbfgs', multi_class='multinomial'))) solvers.append( ('SAG', LogisticRegression( C=1/alpha, penalty='l2', solver='sag', multi_class='multinomial', max_iter = max_iter, tol=1e-1))) solvers.append( ('SAGA', LogisticRegression( C=1/alpha, penalty='l2', solver='saga', multi_class='multinomial', max_iter = max_iter, tol=1e-1))) solvers.append( ('SGD', SGDClassifier( loss='log', alpha=alpha, penalty='l2', eta0 = 1e-3, learning_rate='adaptive', max_iter=max_iter, tol=1e-1))) #solvers.append( ('SGD', SGDClassifier( # loss='log', alpha=alpha, penalty='l2', # learning_rate='optimal', max_iter=max_iter, tol=1e-1))) #solvers.append( ('SGD-LGT', SGDClassifierLGT( # loss='log', alpha=l2reg, penalty='l2', # multiclass=True, max_iter=30))) for name, model in solvers: t0 = time.time() model.fit(X_train, y_train) train_time = time.time() - t0 train_acc = model.score(X_train, y_train) test_acc = model.score(X_test, y_test) print("{}: train time {:0.2f}, train acc {:0.2f}, test acc {:0.2f}".format( name, train_time, train_acc, test_acc)) """ SAG: train time 3.25, train acc 0.89, test acc 0.89 SAGA: train time 4.61, train acc 0.88, test acc 0.88 SGD: train time 5.28, train acc 0.24, test acc 0.25 """
31.819672
138
0.724369
d9b6f4c8c643e993be08f63f6807df196ca6613d
82
py
Python
chapter 2/sampleCode6.py
DTAIEB/Thoughtful-Data-Science
8b80e8f3e33b6fdc6672ecee1f27e0b983b28241
[ "Apache-2.0" ]
15
2018-06-01T19:18:32.000Z
2021-11-28T03:31:35.000Z
chapter 2/sampleCode6.py
chshychen/Thoughtful-Data-Science
8b80e8f3e33b6fdc6672ecee1f27e0b983b28241
[ "Apache-2.0" ]
1
2018-12-17T02:01:42.000Z
2018-12-17T02:01:42.000Z
chapter 2/sampleCode6.py
chshychen/Thoughtful-Data-Science
8b80e8f3e33b6fdc6672ecee1f27e0b983b28241
[ "Apache-2.0" ]
10
2018-09-23T02:45:45.000Z
2022-03-12T15:32:05.000Z
import pixiedust data_url = "https://server/path" pixiedust.wrangleData(data_url)
20.5
32
0.804878
0b20997a3bb3bb0fe51dc01edde8eab7df18bfe8
585
py
Python
unifier/apps/core/management/commands/mangahost_replace.py
sosolidkk/manga-unifier
4cca148affbb197b9284d46ef04c66d42d96c03a
[ "MIT" ]
6
2021-03-25T14:55:36.000Z
2021-05-25T15:12:41.000Z
unifier/apps/core/management/commands/mangahost_replace.py
sosolidkk/manga-unifier
4cca148affbb197b9284d46ef04c66d42d96c03a
[ "MIT" ]
6
2021-02-19T12:32:26.000Z
2021-03-25T16:54:40.000Z
unifier/apps/core/management/commands/mangahost_replace.py
sosolidkk/manga-unifier
4cca148affbb197b9284d46ef04c66d42d96c03a
[ "MIT" ]
null
null
null
from django.core.management.base import BaseCommand from unifier.apps.core.models import Platform class Command(BaseCommand): def handle(self, *args, **kwargs): platform = Platform.objects.get(name="mangahost") mangas = platform.mangas.all() for manga in mangas: chapters = manga.manga_chapters.all() for chapter in chapters: images = chapter.images _images = [image.replace("filestatic1", "filestatic3") for image in images] chapter.images = _images chapter.save()
34.411765
91
0.623932
6f3ce44e2c355080ed0497aad7527ccfda3cad89
21,728
py
Python
lib/util.py
ComputerCraftr/openswap
7de04aa80dab79bebe4b64483011dad70a48694c
[ "MIT" ]
16
2018-11-05T13:19:02.000Z
2021-04-06T12:11:49.000Z
lib/util.py
ComputerCraftr/openswap
7de04aa80dab79bebe4b64483011dad70a48694c
[ "MIT" ]
9
2018-09-19T03:37:26.000Z
2019-04-17T21:58:27.000Z
lib/util.py
ComputerCraftr/openswap
7de04aa80dab79bebe4b64483011dad70a48694c
[ "MIT" ]
5
2018-11-05T13:19:02.000Z
2020-10-20T09:15:54.000Z
# Electrum - lightweight Bitcoin client # Copyright (C) 2011 Thomas Voegtlin # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import binascii import os, sys, re, json from collections import defaultdict from datetime import datetime import decimal from decimal import Decimal import traceback import threading import hmac import stat from .i18n import _ import queue def inv_dict(d): return {v: k for k, v in d.items()} base_units = {'BCH':8, 'mBCH':5, 'cash':2} fee_levels = [_('Within 25 blocks'), _('Within 10 blocks'), _('Within 5 blocks'), _('Within 2 blocks'), _('In the next block')] def normalize_version(v): return [int(x) for x in re.sub(r'(\.0+)*$','', v).split(".")] class NotEnoughFunds(Exception): pass class ExcessiveFee(Exception): pass class InvalidPassword(Exception): def __str__(self): return _("Incorrect password") class FileImportFailed(Exception): def __str__(self): return _("Failed to import file.") class FileImportFailedEncrypted(FileImportFailed): def __str__(self): return (_('Failed to import file.') + ' ' + _('Perhaps it is encrypted...') + '\n' + _('Importing encrypted files is not supported.')) # Throw this exception to unwind the stack like when an error occurs. # However unlike other exceptions the user won't be informed. class UserCancelled(Exception): '''An exception that is suppressed from the user''' pass class MyEncoder(json.JSONEncoder): def default(self, obj): from .transaction import Transaction if isinstance(obj, Transaction): return obj.as_dict() return super(MyEncoder, self).default(obj) class PrintError(object): '''A handy base class''' def diagnostic_name(self): return self.__class__.__name__ def print_error(self, *msg): # only prints with --verbose flag print_error("[%s]" % self.diagnostic_name(), *msg) def print_stderr(self, *msg): print_stderr("[%s]" % self.diagnostic_name(), *msg) def print_msg(self, *msg): print_msg("[%s]" % self.diagnostic_name(), *msg) class ThreadJob(PrintError): """A job that is run periodically from a thread's main loop. run() is called from that thread's context. """ def run(self): """Called periodically from the thread""" pass class DebugMem(ThreadJob): '''A handy class for debugging GC memory leaks''' def __init__(self, classes, interval=30): self.next_time = 0 self.classes = classes self.interval = interval def mem_stats(self): import gc self.print_error("Start memscan") gc.collect() objmap = defaultdict(list) for obj in gc.get_objects(): for class_ in self.classes: if isinstance(obj, class_): objmap[class_].append(obj) for class_, objs in objmap.items(): self.print_error("%s: %d" % (class_.__name__, len(objs))) self.print_error("Finish memscan") def run(self): if time.time() > self.next_time: self.mem_stats() self.next_time = time.time() + self.interval class DaemonThread(threading.Thread, PrintError): """ daemon thread that terminates cleanly """ def __init__(self): threading.Thread.__init__(self) self.parent_thread = threading.currentThread() self.running = False self.running_lock = threading.Lock() self.job_lock = threading.Lock() self.jobs = [] def add_jobs(self, jobs): with self.job_lock: self.jobs.extend(jobs) def run_jobs(self): # Don't let a throwing job disrupt the thread, future runs of # itself, or other jobs. This is useful protection against # malformed or malicious server responses with self.job_lock: for job in self.jobs: try: job.run() except Exception as e: traceback.print_exc(file=sys.stderr) def remove_jobs(self, jobs): with self.job_lock: for job in jobs: self.jobs.remove(job) def start(self): with self.running_lock: self.running = True return threading.Thread.start(self) def is_running(self): with self.running_lock: return self.running and self.parent_thread.is_alive() def stop(self): with self.running_lock: self.running = False def on_stop(self): if 'ANDROID_DATA' in os.environ: try: import jnius jnius.detach() self.print_error("jnius detach") except ImportError: pass # Chaquopy detaches automatically. self.print_error("stopped") # TODO: disable is_verbose = True def set_verbosity(b): global is_verbose is_verbose = b # Method decorator. To be used for calculations that will always # deliver the same result. The method cannot take any arguments # and should be accessed as an attribute. class cachedproperty(object): def __init__(self, f): self.f = f def __get__(self, obj, type): obj = obj or type value = self.f(obj) setattr(obj, self.f.__name__, value) return value def print_error(*args): if not is_verbose: return print_stderr(*args) def print_stderr(*args): args = [str(item) for item in args] sys.stderr.write(" ".join(args) + "\n") sys.stderr.flush() def print_msg(*args): # Stringify args args = [str(item) for item in args] sys.stdout.write(" ".join(args) + "\n") sys.stdout.flush() def json_encode(obj): try: s = json.dumps(obj, sort_keys = True, indent = 4, cls=MyEncoder) except TypeError: s = repr(obj) return s def json_decode(x): try: return json.loads(x, parse_float=Decimal) except: return x # taken from Django Source Code def constant_time_compare(val1, val2): """Return True if the two strings are equal, False otherwise.""" return hmac.compare_digest(to_bytes(val1, 'utf8'), to_bytes(val2, 'utf8')) # decorator that prints execution time def profiler(func): def do_profile(func, args, kw_args): n = func.__name__ t0 = time.time() o = func(*args, **kw_args) t = time.time() - t0 print_error("[profiler]", n, "%.4f"%t) return o return lambda *args, **kw_args: do_profile(func, args, kw_args) def android_ext_dir(): try: import jnius env = jnius.autoclass('android.os.Environment') except ImportError: from android.os import Environment as env # Chaquopy import hook return env.getExternalStorageDirectory().getPath() def android_data_dir(): try: import jnius context = jnius.autoclass('org.kivy.android.PythonActivity').mActivity except ImportError: from com.chaquo.python import Python context = Python.getPlatform().getApplication() return context.getFilesDir().getPath() + '/data' def android_headers_dir(): try: import jnius d = android_ext_dir() + '/org.electron.electron' if not os.path.exists(d): os.mkdir(d) return d except ImportError: return android_data_dir() def ensure_sparse_file(filename): if os.name == "nt": try: os.system("fsutil sparse setFlag \""+ filename +"\" 1") except: pass def get_headers_dir(config): return android_headers_dir() if 'ANDROID_DATA' in os.environ else config.path def assert_datadir_available(config_path): path = config_path if os.path.exists(path): return else: raise FileNotFoundError( 'Electron Cash datadir does not exist. Was it deleted while running?' + '\n' + 'Should be at {}'.format(path)) def assert_file_in_datadir_available(path, config_path): if os.path.exists(path): return else: assert_datadir_available(config_path) raise FileNotFoundError( 'Cannot find file but datadir is there.' + '\n' + 'Should be at {}'.format(path)) def assert_bytes(*args): """ porting helper, assert args type """ try: for x in args: assert isinstance(x, (bytes, bytearray)) except: print('assert bytes failed', list(map(type, args))) raise def assert_str(*args): """ porting helper, assert args type """ for x in args: assert isinstance(x, str) def to_string(x, enc): if isinstance(x, (bytes, bytearray)): return x.decode(enc) if isinstance(x, str): return x else: raise TypeError("Not a string or bytes like object") def to_bytes(something, encoding='utf8'): """ cast string to bytes() like object, but for python2 support it's bytearray copy """ if isinstance(something, bytes): return something if isinstance(something, str): return something.encode(encoding) elif isinstance(something, bytearray): return bytes(something) else: raise TypeError("Not a string or bytes like object") bfh = bytes.fromhex hfu = binascii.hexlify def bh2u(x): """ str with hex representation of a bytes-like object >>> x = bytes((1, 2, 10)) >>> bh2u(x) '01020A' :param x: bytes :rtype: str """ return hfu(x).decode('ascii') def user_dir(prefer_local=False): if 'ANDROID_DATA' in os.environ: raise NotImplementedError('We do not support android yet') elif os.name == 'posix' and "HOME" in os.environ: return os.path.join(os.environ["HOME"], ".openswap" ) elif "APPDATA" in os.environ or "LOCALAPPDATA" in os.environ: app_dir = os.environ.get("APPDATA") localapp_dir = os.environ.get("LOCALAPPDATA") # Prefer APPDATA, but may get LOCALAPPDATA if present and req'd. if localapp_dir is not None and prefer_local or app_dir is None: app_dir = localapp_dir return os.path.join(app_dir, "OpenSwap") else: #raise Exception("No home directory found in environment variables.") return def make_dir(path): # Make directory if it does not yet exist. if not os.path.exists(path): if os.path.islink(path): raise BaseException('Dangling link: ' + path) os.makedirs(path) #os.mkdir(path) os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) def format_satoshis_plain(x, decimal_point = 8): """Display a satoshi amount scaled. Always uses a '.' as a decimal point and has no thousands separator""" scale_factor = pow(10, decimal_point) return "{:.8f}".format(Decimal(x) / scale_factor).rstrip('0').rstrip('.') def format_satoshis(x, num_zeros=0, decimal_point=8, precision=None, is_diff=False, whitespaces=False): from locale import localeconv if x is None: return 'unknown' if precision is None: precision = decimal_point decimal_format = ".0" + str(precision) if precision > 0 else "" if is_diff: decimal_format = '+' + decimal_format result = ("{:" + decimal_format + "f}").format(x / pow (10, decimal_point)).rstrip('0') integer_part, fract_part = result.split(".") dp = localeconv()['decimal_point'] if len(fract_part) < num_zeros: fract_part += "0" * (num_zeros - len(fract_part)) result = integer_part + dp + fract_part if whitespaces: result += " " * (decimal_point - len(fract_part)) result = " " * (15 - len(result)) + result return result def format_fee_satoshis(fee, num_zeros=0): return format_satoshis(fee, num_zeros, 0, precision=num_zeros) def format_satoshis_plain_nofloat(x, decimal_point = 8): """Display a satoshi amount scaled. Always uses a '.' as a decimal point and has no thousands separator. Does not use any floating point representation internally, so no rounding ever occurs. """ x = int(x) xstr = str(abs(x)) if decimal_point > 0: integer_part = xstr[:-decimal_point] fract_part = xstr[-decimal_point:] fract_part = '0'*(decimal_point - len(fract_part)) + fract_part # add leading zeros fract_part = fract_part.rstrip('0') # snip off trailing zeros else: integer_part = xstr fract_part = '' if not integer_part: integer_part = '0' if x < 0: integer_part = '-' + integer_part if fract_part: return integer_part + '.' + fract_part else: return integer_part def format_satoshis_nofloat(x, num_zeros=0, decimal_point=8, precision=None, is_diff=False, whitespaces=False): """ Format the quantity x/10**decimal_point, for integer x. Does not use any floating point representation internally, so no rounding ever occurs when precision is None. Don't pass values other than nonnegative integers for decimal_point or num_zeros or precision. Undefined things will occur. `whitespaces` may be passed as an integer or True (the latter defaulting to 15, as in format_satoshis). """ if x is None: return 'unknown' if precision is not None: x = round(int(x), precision - decimal_point) else: x = int(x) xstr = str(abs(x)) if decimal_point > 0: integer_part = xstr[:-decimal_point] fract_part = xstr[-decimal_point:] fract_part = '0'*(decimal_point - len(fract_part)) + fract_part # add leading zeros fract_part = fract_part.rstrip('0') # snip off trailing zeros else: integer_part = xstr fract_part = '' if not integer_part: integer_part = '0' if x < 0: # put the sign on integer_part = '-' + integer_part elif is_diff: integer_part = '+' + integer_part fract_part += "0" * (num_zeros - len(fract_part)) # restore desired minimum number of fractional figures dp = localeconv()['decimal_point'] result = integer_part + dp + fract_part if whitespaces is True: whitespaces = 15 if whitespaces: result += " " * (decimal_point - len(fract_part)) result = " " * (whitespaces - len(result)) + result return result def get_satoshis_nofloat(s, decimal_point=8): """ Convert a decimal string to integer. e.g., "5.6663" to 566630000 when decimal_point = 8 Does not round, ever. If too many fractional digits are provided (even zeros) then ValueError is raised. """ dec = decimal.Decimal(s) dtup = dec.as_tuple() if dtup.exponent < -decimal_point: raise ValueError('Too many fractional digits', s, decimal_point) # Create context with right amount of precision; we want to raise Inexact # just in case any rounding occurs (still, it should never happen!). C = decimal.Context(prec=len(dtup.digits), traps=[decimal.Inexact]) res = int(C.to_integral_exact(C.scaleb(dec, decimal_point))) return res def timestamp_to_datetime(timestamp): try: return datetime.fromtimestamp(timestamp) except: return None def format_time(timestamp): if timestamp: date = timestamp_to_datetime(timestamp) if date: return date.isoformat(' ')[:-3] return _("Unknown") # Takes a timestamp and returns a string with the approximation of the age def age(from_date, since_date = None, target_tz=None, include_seconds=False): if from_date is None: return "Unknown" from_date = datetime.fromtimestamp(from_date) if since_date is None: since_date = datetime.now(target_tz) td = time_difference(from_date - since_date, include_seconds) return td + " ago" if from_date < since_date else "in " + td def time_difference(distance_in_time, include_seconds): #distance_in_time = since_date - from_date distance_in_seconds = int(round(abs(distance_in_time.days * 86400 + distance_in_time.seconds))) distance_in_minutes = int(round(distance_in_seconds/60)) if distance_in_minutes <= 1: if include_seconds: for remainder in [5, 10, 20]: if distance_in_seconds < remainder: return "less than %s seconds" % remainder if distance_in_seconds < 40: return "half a minute" elif distance_in_seconds < 60: return "less than a minute" else: return "1 minute" else: if distance_in_minutes == 0: return "less than a minute" else: return "1 minute" elif distance_in_minutes < 45: return "%s minutes" % distance_in_minutes elif distance_in_minutes < 90: return "about 1 hour" elif distance_in_minutes < 1440: return "about %d hours" % (round(distance_in_minutes / 60.0)) elif distance_in_minutes < 2880: return "1 day" elif distance_in_minutes < 43220: return "%d days" % (round(distance_in_minutes / 1440)) elif distance_in_minutes < 86400: return "about 1 month" elif distance_in_minutes < 525600: return "%d months" % (round(distance_in_minutes / 43200)) elif distance_in_minutes < 1051200: return "about 1 year" else: return "over %d years" % (round(distance_in_minutes / 525600)) # Python bug (http://bugs.python.org/issue1927) causes raw_input # to be redirected improperly between stdin/stderr on Unix systems #TODO: py3 def raw_input(prompt=None): if prompt: sys.stdout.write(prompt) return builtin_raw_input() import builtins builtin_raw_input = builtins.input builtins.input = raw_input def parse_json(message): # TODO: check \r\n pattern n = message.find(b'\n') if n==-1: return None, message try: j = json.loads(message[0:n].decode('utf8')) except: j = None return j, message[n+1:] class timeout(Exception): pass TimeoutException = timeout # Future compat. with Electrum codebase/cherrypicking import socket import json import ssl import time class SocketPipe(PrintError): def __init__(self, socket): self.socket = socket self.message = b'' self.set_timeout(0.1) self.recv_time = time.time() def set_timeout(self, t): self.socket.settimeout(t) def idle_time(self): return time.time() - self.recv_time def get(self): while True: response, self.message = parse_json(self.message) if response is not None: return response try: data = self.socket.recv(1024) except socket.timeout: raise timeout except ssl.SSLError: raise timeout except socket.error as err: if err.errno == 60: raise timeout elif err.errno in [11, 35, 10035]: self.print_error("socket errno %d (resource temporarily unavailable)"% err.errno) time.sleep(0.2) raise timeout else: self.print_error("socket error:", err) data = b'' except: traceback.print_exc(file=sys.stderr) data = b'' if not data: # Connection closed remotely return None self.message += data self.recv_time = time.time() def send(self, request): out = json.dumps(request) + '\n' out = out.encode('utf8') self._send(out) def send_all(self, requests): out = b''.join(map(lambda x: (json.dumps(x) + '\n').encode('utf8'), requests)) self._send(out) def _send(self, out): while out: sent = self.socket.send(out) out = out[sent:] def setup_thread_excepthook(): """ Workaround for `sys.excepthook` thread bug from: http://bugs.python.org/issue1230540 Call once from the main thread before creating any threads. """ init_original = threading.Thread.__init__ def init(self, *args, **kwargs): init_original(self, *args, **kwargs) run_original = self.run def run_with_except_hook(*args2, **kwargs2): try: run_original(*args2, **kwargs2) except Exception: sys.excepthook(*sys.exc_info()) self.run = run_with_except_hook threading.Thread.__init__ = init def versiontuple(v): return tuple(map(int, (v.split("."))))
30.388811
127
0.631719
c1d870e5d9fef04cb6490f24c2366421f312e4d5
1,874
py
Python
quantum-ugly-duckling-main/nqrng.py
rochisha0/quantum-ugly-duckling
9cd3164b49240a2342172c8c09950f1f51904793
[ "Apache-2.0" ]
11
2020-10-08T15:26:11.000Z
2021-05-02T21:25:26.000Z
quantum-ugly-duckling-main/nqrng.py
rochisha0/quantum-ugly-duckling
9cd3164b49240a2342172c8c09950f1f51904793
[ "Apache-2.0" ]
null
null
null
quantum-ugly-duckling-main/nqrng.py
rochisha0/quantum-ugly-duckling
9cd3164b49240a2342172c8c09950f1f51904793
[ "Apache-2.0" ]
4
2020-10-08T17:44:32.000Z
2022-01-29T22:35:16.000Z
import numpy as np from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.providers.aer import QasmSimulator # Import from Qiskit Aer noise module from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise import QuantumError, ReadoutError from qiskit.providers.aer.noise import pauli_error ## Applying bit flip error def get_noise(): p_reset = 0.03 p_meas = 0.1 p_gate1 = 0.05 # QuantumError objects error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)]) error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)]) error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)]) error_gate2 = error_gate1.tensor(error_gate1) # Add errors to noise model noise_bit_flip = NoiseModel() noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset") noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure") noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"]) noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"]) return noise_bit_flip def random_number(): circ = QuantumCircuit(4) simulator = QasmSimulator() #NQRNS Circuit for i in range(200): circ.u3(0,0,0,0) circ.u3(0,0,0,1) circ.u3(0,0,0,2) circ.u3(0,0,0,3) circ.cx(0,1) circ.cx(1,2) circ.cx(0,2) circ.cx(0,3) circ.cx(1,3) circ.cx(2,3) circ.barrier() circ.measure_all() noise_bit_flip = get_noise() #get output job = execute(circ, simulator, basis_gates=noise_bit_flip.basis_gates, noise_model=noise_bit_flip, shots= 1) result_bit_flip = job.result() counts_bit_flip = result_bit_flip.get_counts(0) num=list(counts_bit_flip.keys())[0] num = int(num, 2) return num
27.970149
79
0.668623
9129caa54ebab33e726d5ea215c9ff222d5f22a6
3,230
py
Python
parakeet/exps/gan_vocoder/parallelwave_gan/synthesize.py
zh794390558/DeepSpeech
34178893327ad359cb816e55d7c66a10244fa08a
[ "Apache-2.0" ]
null
null
null
parakeet/exps/gan_vocoder/parallelwave_gan/synthesize.py
zh794390558/DeepSpeech
34178893327ad359cb816e55d7c66a10244fa08a
[ "Apache-2.0" ]
null
null
null
parakeet/exps/gan_vocoder/parallelwave_gan/synthesize.py
zh794390558/DeepSpeech
34178893327ad359cb816e55d7c66a10244fa08a
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from pathlib import Path import jsonlines import numpy as np import paddle import soundfile as sf import yaml from paddle import distributed as dist from timer import timer from yacs.config import CfgNode from parakeet.datasets.data_table import DataTable from parakeet.models.parallel_wavegan import PWGGenerator def main(): parser = argparse.ArgumentParser( description="Synthesize with parallel wavegan.") parser.add_argument( "--config", type=str, help="parallel wavegan config file.") parser.add_argument("--checkpoint", type=str, help="snapshot to load.") parser.add_argument("--test-metadata", type=str, help="dev data.") parser.add_argument("--output-dir", type=str, help="output dir.") parser.add_argument( "--device", type=str, default="gpu", help="device to run.") parser.add_argument("--verbose", type=int, default=1, help="verbose.") args = parser.parse_args() with open(args.config) as f: config = CfgNode(yaml.safe_load(f)) print("========Args========") print(yaml.safe_dump(vars(args))) print("========Config========") print(config) print( f"master see the word size: {dist.get_world_size()}, from pid: {os.getpid()}" ) paddle.set_device(args.device) generator = PWGGenerator(**config["generator_params"]) state_dict = paddle.load(args.checkpoint) generator.set_state_dict(state_dict["generator_params"]) generator.remove_weight_norm() generator.eval() with jsonlines.open(args.test_metadata, 'r') as reader: metadata = list(reader) test_dataset = DataTable( metadata, fields=['utt_id', 'feats'], converters={ 'utt_id': None, 'feats': np.load, }) output_dir = Path(args.output_dir) output_dir.mkdir(parents=True, exist_ok=True) N = 0 T = 0 for example in test_dataset: utt_id = example['utt_id'] mel = example['feats'] mel = paddle.to_tensor(mel) # (T, C) with timer() as t: with paddle.no_grad(): wav = generator.inference(c=mel) wav = wav.numpy() N += wav.size T += t.elapse speed = wav.size / t.elapse print( f"{utt_id}, mel: {mel.shape}, wave: {wav.shape}, time: {t.elapse}s, Hz: {speed}, RTF: {config.fs / speed}." ) sf.write(str(output_dir / (utt_id + ".wav")), wav, samplerate=config.fs) print(f"generation speed: {N / T}Hz, RTF: {config.fs / (N / T) }") if __name__ == "__main__": main()
32.959184
119
0.647678
357afa8566a6f81b0e5c826845be0eef4537c6d7
704
py
Python
components/google-cloud/google_cloud_pipeline_components/version.py
droctothorpe/pipelines
c1142f02e62425a6a5ef9ecb5392420b1e5fbe48
[ "Apache-2.0" ]
null
null
null
components/google-cloud/google_cloud_pipeline_components/version.py
droctothorpe/pipelines
c1142f02e62425a6a5ef9ecb5392420b1e5fbe48
[ "Apache-2.0" ]
null
null
null
components/google-cloud/google_cloud_pipeline_components/version.py
droctothorpe/pipelines
c1142f02e62425a6a5ef9ecb5392420b1e5fbe48
[ "Apache-2.0" ]
null
null
null
# Copyright 2021 The Kubeflow Authors. 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. """Contains the version string of Google Cloud Pipeline Components.""" __version__ = "1.0.7.dev"
41.411765
74
0.761364
8cd12937c3e9d4285f62088062eb15d5e0aea9f5
1,888
py
Python
msgraph-cli-extensions/beta/compliance_beta/setup.py
thewahome/msgraph-cli
33127d9efa23a0e5f5303c93242fbdbb73348671
[ "MIT" ]
null
null
null
msgraph-cli-extensions/beta/compliance_beta/setup.py
thewahome/msgraph-cli
33127d9efa23a0e5f5303c93242fbdbb73348671
[ "MIT" ]
null
null
null
msgraph-cli-extensions/beta/compliance_beta/setup.py
thewahome/msgraph-cli
33127d9efa23a0e5f5303c93242fbdbb73348671
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from codecs import open from setuptools import setup, find_packages # HISTORY.rst entry. VERSION = '0.1.0' try: from azext_compliance_beta.manual.version import VERSION except ImportError: pass # The full list of classifiers is available at # https://pypi.python.org/pypi?%3Aaction=list_classifiers CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'License :: OSI Approved :: MIT License', ] DEPENDENCIES = [] try: from azext_compliance_beta.manual.dependency import DEPENDENCIES except ImportError: pass with open('README.md', 'r', encoding='utf-8') as f: README = f.read() with open('HISTORY.rst', 'r', encoding='utf-8') as f: HISTORY = f.read() setup( name='compliance_beta', version=VERSION, description='Microsoft Azure Command-Line Tools Compliance Extension', author='Microsoft Corporation', author_email='azpycli@microsoft.com', url='https://github.com/Azure/azure-cli-extensions/tree/master/compliance_beta', long_description=README + '\n\n' + HISTORY, license='MIT', classifiers=CLASSIFIERS, packages=find_packages(), install_requires=DEPENDENCIES, package_data={'azext_compliance_beta': ['azext_metadata.json']}, )
32
94
0.636123
9e9e546d9e39da66be90019c1476ae687fe867c3
399
py
Python
backend/src/apps/Interactions/Models.py
HirataYoshiki/Ticketter
3884ba2f6d5329ca1f4f18530fc169b7b8b65e27
[ "MIT" ]
null
null
null
backend/src/apps/Interactions/Models.py
HirataYoshiki/Ticketter
3884ba2f6d5329ca1f4f18530fc169b7b8b65e27
[ "MIT" ]
null
null
null
backend/src/apps/Interactions/Models.py
HirataYoshiki/Ticketter
3884ba2f6d5329ca1f4f18530fc169b7b8b65e27
[ "MIT" ]
null
null
null
from db import Base,engine from sqlalchemy import Column, Integer, String, Boolean, DateTime,ForeignKey from sqlalchemy.orm import relationship class Interactions(Base): __tablename__ = "interactions" interactionid = Column(Integer, primary_key = True, autoincrement = True) ticketid = Column(Integer) from_ = Column(String(100)) to_ = Column(String(100)) timestamp = Column(DateTime)
30.692308
76
0.769424
f4de9fa7c58c2285a88a25a72b76b13ec9ba6bc5
14,320
py
Python
pysnmp-with-texts/ZHNFIREWALL.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
8
2019-05-09T17:04:00.000Z
2021-06-09T06:50:51.000Z
pysnmp-with-texts/ZHNFIREWALL.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
4
2019-05-31T16:42:59.000Z
2020-01-31T21:57:17.000Z
pysnmp-with-texts/ZHNFIREWALL.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # PySNMP MIB module ZHNFIREWALL (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHNFIREWALL # Produced by pysmi-0.3.4 at Wed May 1 15:46:38 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion") ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance") Integer32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, enterprises, IpAddress, Bits, Gauge32, Counter32, Counter64, NotificationType, ObjectIdentity, MibIdentifier, ModuleIdentity, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "enterprises", "IpAddress", "Bits", "Gauge32", "Counter32", "Counter64", "NotificationType", "ObjectIdentity", "MibIdentifier", "ModuleIdentity", "TimeTicks") TruthValue, RowStatus, DisplayString, MacAddress, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "RowStatus", "DisplayString", "MacAddress", "TextualConvention") lanEthernetIndex, lanDeviceIndex = mibBuilder.importSymbols("ZHNLANDEVICE", "lanEthernetIndex", "lanDeviceIndex") zhoneWtn, = mibBuilder.importSymbols("Zhone", "zhoneWtn") ZhoneRowStatus, = mibBuilder.importSymbols("Zhone-TC", "ZhoneRowStatus") zhnFirewall = ModuleIdentity((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45)) zhnFirewall.setRevisions(('2012-04-18 12:00', '2012-02-03 12:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: zhnFirewall.setRevisionsDescriptions(('Added https to FirewallMgmtAccessServiceValues', 'First Draft',)) if mibBuilder.loadTexts: zhnFirewall.setLastUpdated('201204181200Z') if mibBuilder.loadTexts: zhnFirewall.setOrganization('Zhone Technologies, Inc.') if mibBuilder.loadTexts: zhnFirewall.setContactInfo('Zhone Technologies, Inc. Florida Design Center 8545 126th Avenue North Largo, FL 33773 Toll-Free: +1 877-ZHONE20 (+1 877-946-6320) Tel: +1-510-777-7000 Fax: +1-510-777-7001 E-mail: support@zhone.com') if mibBuilder.loadTexts: zhnFirewall.setDescription('This file defines the private Enterprise MIB extensions that define LAN Management Access Service Filters and Port Forwarding objects supported by the Zhone CPEs.') zhnFirewallObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1)) class FirewallMgmtAccessServiceValues(TextualConvention, Integer32): description = 'LAN Management Access Services that can be blocked from the CPEs management network.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7)) namedValues = NamedValues(("http", 1), ("https", 2), ("ping", 3), ("snmp", 4), ("snmpTrap", 5), ("ssh", 6), ("telnet", 7)) class FirewallMgmtAccessServiceActions(TextualConvention, Integer32): description = 'LAN Management Access Service actions to perform for the specified service.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3)) namedValues = NamedValues(("allow", 1), ("deny", 2), ("undefined", 3)) class FirewallPortTypeValues(TextualConvention, Integer32): description = 'LAN Port Forwarding actions supported.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3)) namedValues = NamedValues(("portRange", 1), ("portRemap", 2), ("dmz", 3)) class FirewallPortProtocolValues(TextualConvention, Integer32): description = 'LAN Port Forwarding protocols that can be filtered, per port.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6)) namedValues = NamedValues(("tcp", 1), ("udp", 2), ("tcpOrUdp", 3), ("icmp", 4), ("icmpv4", 5), ("none", 6)) firewallMgmtAccessTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 1), ) if mibBuilder.loadTexts: firewallMgmtAccessTable.setStatus('current') if mibBuilder.loadTexts: firewallMgmtAccessTable.setDescription('Table of LAN Management Access Service Filters') firewallMgmtAccessEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 1, 1), ).setIndexNames((0, "ZHNLANDEVICE", "lanDeviceIndex"), (0, "ZHNLANDEVICE", "lanEthernetIndex"), (0, "ZHNFIREWALL", "firewallMgmtServiceIndex")) if mibBuilder.loadTexts: firewallMgmtAccessEntry.setStatus('current') if mibBuilder.loadTexts: firewallMgmtAccessEntry.setDescription('Table of entries of LAN Management Access service filters. This table is used to configure management access on the device. It is useful in making the device management network by blocking protocols or services that are highly susceptible to external attacks.') firewallMgmtServiceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 1, 1, 1), FirewallMgmtAccessServiceValues()) if mibBuilder.loadTexts: firewallMgmtServiceIndex.setStatus('current') if mibBuilder.loadTexts: firewallMgmtServiceIndex.setDescription('LAN Management Access Services Table index. Enumerated values: Http (1), Https (2), Ping (3), Snmp (4), SnmpTrap (5), Ssh (6), Telnet (7) ') firewallMgmtService = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 1, 1, 2), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: firewallMgmtService.setStatus('current') if mibBuilder.loadTexts: firewallMgmtService.setDescription('LAN Management Access Service description.') firewallMgmtAction = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 1, 1, 3), FirewallMgmtAccessServiceActions()).setMaxAccess("readwrite") if mibBuilder.loadTexts: firewallMgmtAction.setStatus('current') if mibBuilder.loadTexts: firewallMgmtAction.setDescription('LAN Management Access Service filtering action. Enumerated values: Allow (1), Deny (2), Undefined (3) ') firewallPortForwardingTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 2), ) if mibBuilder.loadTexts: firewallPortForwardingTable.setStatus('current') if mibBuilder.loadTexts: firewallPortForwardingTable.setDescription('Table of LAN Port Forwarding Rules. Note that the rules in this table have no effect until the global firewall object (sysFirewallEnable) is enabled.') firewallPortForwardingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 2, 1), ).setIndexNames((0, "ZHNLANDEVICE", "lanDeviceIndex"), (0, "ZHNLANDEVICE", "lanEthernetIndex"), (0, "ZHNFIREWALL", "firewallPortForwardingIndex")) if mibBuilder.loadTexts: firewallPortForwardingEntry.setStatus('current') if mibBuilder.loadTexts: firewallPortForwardingEntry.setDescription('This table is used to configure port forwarding firewall rules for the device.') firewallPortForwardingIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 2, 1, 1), Unsigned32()) if mibBuilder.loadTexts: firewallPortForwardingIndex.setStatus('current') if mibBuilder.loadTexts: firewallPortForwardingIndex.setDescription('LAN Port Forwarding Rules index.') firewallPortForwardingName = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 2, 1, 2), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: firewallPortForwardingName.setStatus('current') if mibBuilder.loadTexts: firewallPortForwardingName.setDescription('Descriptive name for a LAN Port Forwarding Rule.') firewallPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 2, 1, 3), FirewallPortTypeValues()).setMaxAccess("readwrite") if mibBuilder.loadTexts: firewallPortType.setStatus('current') if mibBuilder.loadTexts: firewallPortType.setDescription('Enumerated value of: portRange (1), -- Range indicates that any traffic on those ports will be -- sent to the private IP address. portRemap (2), -- Remap indicates that any traffic on those ports will be -- sent to the private IP address at the private port. dmz (3) -- When DMZ is chosen it is the only rule allowed on that -- interface. A DMZ rule is effectively the same as a Range -- rule with all ports included. Range rules are more secure -- than setting a DMZ rule, because Range rules allow specific -- ports or groups of ports to be opened up. ') firewallPortProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 2, 1, 4), FirewallPortProtocolValues()).setMaxAccess("readwrite") if mibBuilder.loadTexts: firewallPortProtocol.setStatus('current') if mibBuilder.loadTexts: firewallPortProtocol.setDescription('Enumerated value of: tcp (1), udp (2), tcpOrUdp (3), icmp (4), icmpv4 (5), none (6) ') firewallPortPublicPortStart = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 2, 1, 5), Unsigned32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: firewallPortPublicPortStart.setStatus('current') if mibBuilder.loadTexts: firewallPortPublicPortStart.setDescription('Lowest value port number for the range.') firewallPortPublicPortEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 2, 1, 6), Unsigned32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: firewallPortPublicPortEnd.setStatus('current') if mibBuilder.loadTexts: firewallPortPublicPortEnd.setDescription('Highest value port number for the range. This can be equal to firewallPortPublicPortStart if there is only one port.') firewallPortPrivatePort = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 2, 1, 7), Unsigned32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: firewallPortPrivatePort.setStatus('current') if mibBuilder.loadTexts: firewallPortPrivatePort.setDescription('The port number with which to send the traffic.') firewallPortPrivateIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 2, 1, 8), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: firewallPortPrivateIPAddress.setStatus('current') if mibBuilder.loadTexts: firewallPortPrivateIPAddress.setDescription('The port IP Address with which to send the traffic.') firewallPortForwardingRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 1, 2, 1, 9), ZhoneRowStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: firewallPortForwardingRowStatus.setStatus('current') if mibBuilder.loadTexts: firewallPortForwardingRowStatus.setDescription('The SNMP RowStatus of the current row. The following objects must be specified upon row creation: firewallPortForwardingName firewallPortPrivateIPAddress ') zhnFirewallConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 3)) zhnFirewallGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 3, 1)) zhnFirewallCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 3, 2)) zhnFirewallCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 3, 2, 1)).setObjects(("ZHNFIREWALL", "zhnFirewallMgmtAccessGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): zhnFirewallCompliance = zhnFirewallCompliance.setStatus('current') if mibBuilder.loadTexts: zhnFirewallCompliance.setDescription('The Compliance statement for SNMP entities which manage the Zhone CPE LAN Firewall Management Access Services and Port Forwarding Information') zhnFirewallMgmtAccessGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 3, 1, 1)).setObjects(("ZHNFIREWALL", "firewallMgmtService"), ("ZHNFIREWALL", "firewallMgmtAction")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): zhnFirewallMgmtAccessGroup = zhnFirewallMgmtAccessGroup.setStatus('current') if mibBuilder.loadTexts: zhnFirewallMgmtAccessGroup.setDescription('A collection of Zhone IP objects that describe the LAN Management Access Services that can be filtered for a particular LAN interface.') zhnFirewallPortForwardingGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 5504, 2, 5, 45, 3, 1, 2)).setObjects(("ZHNFIREWALL", "firewallPortForwardingName"), ("ZHNFIREWALL", "firewallPortType"), ("ZHNFIREWALL", "firewallPortProtocol"), ("ZHNFIREWALL", "firewallPortPublicPortStart"), ("ZHNFIREWALL", "firewallPortPublicPortEnd"), ("ZHNFIREWALL", "firewallPortPrivatePort"), ("ZHNFIREWALL", "firewallPortPrivateIPAddress"), ("ZHNFIREWALL", "firewallPortForwardingRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): zhnFirewallPortForwardingGroup = zhnFirewallPortForwardingGroup.setStatus('current') if mibBuilder.loadTexts: zhnFirewallPortForwardingGroup.setDescription('A collection of Zhone IP objects that describe the LAN Port Forwarding Management rules for filtering protocols and ports for a particular LAN interface.') mibBuilder.exportSymbols("ZHNFIREWALL", FirewallMgmtAccessServiceActions=FirewallMgmtAccessServiceActions, firewallPortProtocol=firewallPortProtocol, firewallMgmtAccessTable=firewallMgmtAccessTable, zhnFirewall=zhnFirewall, FirewallPortTypeValues=FirewallPortTypeValues, FirewallMgmtAccessServiceValues=FirewallMgmtAccessServiceValues, firewallPortType=firewallPortType, firewallPortForwardingEntry=firewallPortForwardingEntry, firewallPortForwardingTable=firewallPortForwardingTable, firewallMgmtAction=firewallMgmtAction, firewallMgmtService=firewallMgmtService, PYSNMP_MODULE_ID=zhnFirewall, firewallMgmtServiceIndex=firewallMgmtServiceIndex, firewallPortPublicPortStart=firewallPortPublicPortStart, firewallMgmtAccessEntry=firewallMgmtAccessEntry, zhnFirewallPortForwardingGroup=zhnFirewallPortForwardingGroup, firewallPortForwardingRowStatus=firewallPortForwardingRowStatus, firewallPortPrivatePort=firewallPortPrivatePort, zhnFirewallCompliance=zhnFirewallCompliance, firewallPortForwardingName=firewallPortForwardingName, zhnFirewallGroups=zhnFirewallGroups, FirewallPortProtocolValues=FirewallPortProtocolValues, firewallPortPublicPortEnd=firewallPortPublicPortEnd, zhnFirewallMgmtAccessGroup=zhnFirewallMgmtAccessGroup, zhnFirewallObjects=zhnFirewallObjects, firewallPortPrivateIPAddress=firewallPortPrivateIPAddress, zhnFirewallConformance=zhnFirewallConformance, zhnFirewallCompliances=zhnFirewallCompliances, firewallPortForwardingIndex=firewallPortForwardingIndex)
123.448276
1,477
0.782402
0c9d911582a005b4fe537c72862724b82f99df75
4,809
py
Python
orangecontrib/wavepy2/widgets/imaging/ow_sgt_calculate_2nd_order_component_of_the_phase_1.py
APS-XSD-OPT-Group/OASYS1-WavePy2
f1147104f99f44bb850ad5668d1c9997d4880a3a
[ "BSD-3-Clause" ]
null
null
null
orangecontrib/wavepy2/widgets/imaging/ow_sgt_calculate_2nd_order_component_of_the_phase_1.py
APS-XSD-OPT-Group/OASYS1-WavePy2
f1147104f99f44bb850ad5668d1c9997d4880a3a
[ "BSD-3-Clause" ]
null
null
null
orangecontrib/wavepy2/widgets/imaging/ow_sgt_calculate_2nd_order_component_of_the_phase_1.py
APS-XSD-OPT-Group/OASYS1-WavePy2
f1147104f99f44bb850ad5668d1c9997d4880a3a
[ "BSD-3-Clause" ]
null
null
null
# ######################################################################### # Copyright (c) 2020, UChicago Argonne, LLC. All rights reserved. # # # # Copyright 2020. UChicago Argonne, LLC. This software was produced # # under U.S. Government contract DE-AC02-06CH11357 for Argonne National # # Laboratory (ANL), which is operated by UChicago Argonne, LLC for the # # U.S. Department of Energy. The U.S. Government has rights to use, # # reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR # # UChicago Argonne, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR # # ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is # # modified to produce derivative works, such modified software should # # be clearly marked, so as not to confuse it with the version available # # from ANL. # # # # Additionally, redistribution and use in source and binary forms, with # # or without modification, are permitted provided that the following # # conditions are met: # # # # * Redistributions of source code must retain the above copyright # # notice, this list of conditions and the following disclaimer. # # # # * 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. # # # # * Neither the name of UChicago Argonne, LLC, Argonne National # # Laboratory, ANL, the U.S. Government, nor the names of its # # contributors may be used to endorse or promote products derived # # from this software without specific prior written permission. # # # # THIS SOFTWARE IS PROVIDED BY UChicago Argonne, LLC AND CONTRIBUTORS # # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UChicago # # Argonne, LLC 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 wavepy2.util.plot.plot_tools import PlottingProperties from orangecontrib.wavepy2.util.gui.ow_wavepy_process_widget import WavePyProcessWidget class OWSGTCalculate2ndOrderComponentOfThePhase1(WavePyProcessWidget): name = "S.G.T. - Calculate 2nd Order Component of the Phase 1" id = "sgt_calculate_2nd_order_cpt_phase_1" description = "S.G.T. - Calculate 2nd Order Component of the Phase 1" icon = "icons/sgt_calculate_2nd_order_cpt_phase_1.png" priority = 15 category = "" keywords = ["wavepy", "tools", "crop"] CONTROL_AREA_WIDTH = 1030 MAX_WIDTH_NO_MAIN = CONTROL_AREA_WIDTH + 10 def __init__(self): super(OWSGTCalculate2ndOrderComponentOfThePhase1, self).__init__() def _get_execute_button_label(self): return "Calculate 2nd Order Component of the Phase 1" def _get_output_parameters(self): self._initialization_parameters.set_parameter("remove_linear", True) return self._process_manager.calc_2nd_order_component_of_the_phase_1(integration_result=self._calculation_parameters, initialization_parameters=self._initialization_parameters, plotting_properties=self._get_default_plotting_properties(), figure_height=650, figure_width=900)
61.653846
137
0.568933
f50fe2b56a64978dc21a49ed644035d15c626c9f
1,659
py
Python
python/oneflow/test/modules/test_allreduce.py
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
null
null
null
python/oneflow/test/modules/test_allreduce.py
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
null
null
null
python/oneflow/test/modules/test_allreduce.py
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
null
null
null
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import unittest import numpy as np import oneflow as flow import oneflow.unittest @unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases") class TestAllReduce(flow.unittest.TestCase): @flow.unittest.skip_unless_1n2d() def test_all_reduce(test_case): arr_rank1 = np.array([1, 2]) arr_rank2 = np.array([3, 4]) if flow.distributed.get_rank() == 0: x = flow.Tensor(arr_rank1) elif flow.distributed.get_rank() == 1: x = flow.Tensor(arr_rank2) else: raise ValueError x = x.to("cuda") y = flow.F.all_reduce(x) test_case.assertTrue(np.allclose(y.numpy(), arr_rank1 + arr_rank2)) @flow.unittest.skip_unless_2n2d() def test_all_reduce_2nodes(test_case): np_arr = np.array([1, 2]) x = flow.Tensor(np_arr * (flow.distributed.get_rank() + 1)) x = x.to("cuda") y = flow.F.all_reduce(x) test_case.assertTrue(np.allclose(y.numpy(), np_arr * 10)) if __name__ == "__main__": unittest.main()
31.903846
75
0.684147
ff268083f98891d5829a57e16549529b5e78563c
3,825
py
Python
analysis/analysis_utils.py
tginart/competing-ai
75c456854e4770adf8be7cd56e58177d50f74a24
[ "Apache-2.0" ]
2
2021-03-10T23:46:31.000Z
2021-04-13T00:41:12.000Z
analysis/analysis_utils.py
tginart/competing-ai
75c456854e4770adf8be7cd56e58177d50f74a24
[ "Apache-2.0" ]
null
null
null
analysis/analysis_utils.py
tginart/competing-ai
75c456854e4770adf8be7cd56e58177d50f74a24
[ "Apache-2.0" ]
null
null
null
import torch import torch import torch.nn.functional as F import numpy as np import pickle import glob import os import re import sys import multiprocessing from joblib import Parallel, delayed sys.path.insert(0,'..') from data import * from agent import * from auction import * from user import * from simulator import * def _depickle(run, log=True): os.chdir(run) r_id = int(run.split('/')[-1][3:]) logger = None if log: logger = pickle.load(open('logger.pickle','rb')) config = pickle.load(open('config.pickle','rb')) return config, logger def _enumerate_runs(outpath): #also initializes the logs & configs runs = glob.glob(f'{outpath}/run*') logs = [None]*len(runs) configs = [None]*len(runs) return runs, logs, configs def _sort_runs(runs): runs_sorted = [None]*len(runs) for run in runs: s = int(re.sub("[^0-9]", "", run.split('/')[-1])) runs_sorted[s] = run return runs_sorted def _agg_corr(logger): return torch.tensor(logger['agg-correct']).int().numpy() def _y_hats(logger): A = logger['agents'] Y_hat = torch.zeros( (1+len(A), len(A[0]['y_hat'])) ) for i in A: Y_hat[i] = torch.tensor(A[i]['y_hat']) #last Y_hat row is ground truth Y_hat[-1] = torch.tensor(logger['y']) return Y_hat.numpy() def _cf_process(logger): x = torch.tensor(logger['x']) u_choices = torch.tensor(logger['choices']) y_hats = [] for i in logger['agents']: #print(i) y_hat = torch.tensor(logger['agents'][i]['y_hat']) y_hats.append(y_hat) y_hats = torch.stack(y_hats).t() choices = torch.nn.functional.one_hot(u_choices, i+1) rec = torch.sum(y_hats * choices,dim=1) U = logger['uEmb'] V = logger['vEmb'] return x, rec, U, V, u_choices, y_hats def process_select(proc): if proc == 'agg_corr': process = _agg_corr elif proc == 'y_hats': process = _y_hats elif proc == 'cf': process = _cf_process else: raise ValueError(f'Proc {proc} not supported') return process def depickler(outpath, log=False): runs, logs, configs = _enumerate_runs(outpath) for run in runs: print(run) r_id = int(run.split('/')[-1][3:]) config, logger = _depickle(run,log) configs[r_id] = config if logger != None: logs[r_id] = logger return configs, logs def depickler_special(outpath): runs, logs, configs = _enumerate_runs(outpath) for run in runs: print(run) r_id = int(run.split('/')[-1][3:]) config, _ = _depickle(run,log=False) configs[r_id] = config logs[r_id] = np.load(f'{run}/special_log') return configs, logs def depickler_process(outpath, proc='agg_corr'): runs, logs, configs = _enumerate_runs(outpath) for run in runs: print(run) r_id = int(run.split('/')[-1][3:]) config, logger = _depickle(run,log=True) configs[r_id] = config logs[r_id] = process_select(proc)(logger) del logger return configs, logs def para_depickler(outpath, proc='agg_corr'): from joblib import Parallel, delayed import multiprocessing process = process_select(proc) def processInput(run): config, logger = _depickle(run,log=True) log = process(logger) del logger return config,log n_cores = multiprocessing.cpu_count() runs, logs, configs = _enumerate_runs(outpath) runs = _sort_runs(runs) results = Parallel(n_jobs=n_cores)(delayed(processInput)(r) for r in runs) configs,logs = zip(*results) return configs, logs def data_saver(data, outpath, proc): process_select(proc) #just to make sure user gave valid proc np.save(f'{outpath}/{proc}',data)
26.93662
78
0.624575
4b36ef60f452194c2c206bee4c930481645d13e1
2,259
py
Python
masterArtistNameCorrection.py
tgadf/musicnames
71c4cbc8dbb68860e9688b47c4889ea559d6e22c
[ "MIT" ]
null
null
null
masterArtistNameCorrection.py
tgadf/musicnames
71c4cbc8dbb68860e9688b47c4889ea559d6e22c
[ "MIT" ]
null
null
null
masterArtistNameCorrection.py
tgadf/musicnames
71c4cbc8dbb68860e9688b47c4889ea559d6e22c
[ "MIT" ]
null
null
null
from convertByteString import convertByteString class masterArtistNameCorrection: def __init__(self, debug=False): self.debug = debug self.cbs = convertByteString() ## Test assert self.clean("3/3") == "3-3" assert self.clean("...Hello") == "Hello" def directoryName(self, x): if x is None: return x if "..." in x: x = x.replace("...", "") if "/" in x: x = x.replace("/", "-") return x def realName(self, x): if x is None: return [None,-1] lenx = len(x) if len(x) < 1: return [x,-1] if x[-1] != ")": return [x, None] if lenx >=5: if x[-3] == "(": try: num = int(x[-2:-1]) val = x[:-3].strip() return [val, num] except: return [x, None] if lenx >= 6: if x[-4] == "(": try: num = int(x[-3:-1]) val = x[:-4].strip() return [val, num] except: return [x, None] if lenx >= 7: if x[-4] == "(": try: num = int(x[-3:-1]) val = x[:-4].strip() return [val, num] except: return [x, None] return [x, None] def discConv(self, x): if x is None: return "" x = x.replace("/", "-") x = x.replace("¡", "") while x.startswith(".") and len(x) > 1: x = x[1:] x = x.strip() x = self.cbs.convert(x) return x def cleanMB(self, x): pos = [x.rfind("(")+1, x.rfind(")")] if sum([p > 0 for p in pos]) != len(pos): return x parval = x[pos[0]:pos[1]] return x[:pos[0]-2].strip() def clean(self, name): if self.debug: print("Pre Cleaning [{0}]".format(name)) name = self.discConv(name) if self.debug: print("Post Cleaning [{0}]".format(name)) return name
24.824176
53
0.376273
b8fa6ffe23e58b0c2249e2b803723cad9ee543b1
9,222
py
Python
procedures/datasetBuilder.py
tilacyn/CT-GAN
92640099a9ea771e2851b32a7b8c292876efd163
[ "MIT" ]
null
null
null
procedures/datasetBuilder.py
tilacyn/CT-GAN
92640099a9ea771e2851b32a7b8c292876efd163
[ "MIT" ]
null
null
null
procedures/datasetBuilder.py
tilacyn/CT-GAN
92640099a9ea771e2851b32a7b8c292876efd163
[ "MIT" ]
null
null
null
# MIT License # # Copyright (c) 2019 Yisroel Mirsky # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from config import * import pandas as pd import multiprocessing from scipy.ndimage.interpolation import rotate from joblib import Parallel, delayed import itertools from utils.equalizer import * from utils.dicom_utils import * from utils.utils import * class Extractor: # is_healthy_dataset: indicates if the datset are of healthy scans or of unhealthy scans # src_dir: Path to directory containing all of the scans (folders of dicom series, or mhd/raw files) # dst_path: Path to file to save the dataset in np serialized format. e.g., data/healthy_samples.npy # norm_save_dir: the directory where the normalization parameters should be saved. e.g, data/models/INJ/ # coords_csv: path to csv of the candidate locations with the header: filename, z, x, y (if vox, slice should be 0-indexed) # if filename is a directory or has a *.dcm extension, then dicom format is assumed (each scan should have its own directory contianting all of its dcm slices) # if filename has the *.mhd extension, then mhd/raw is assumed (all mdh/raw files should be in same directory) # parallelize: inidates whether the processign should be run over multiple CPU cores # coordSystem: if the coords are the matrix indexes, then choose 'vox'. If the coords are realworld locations, then choose 'world' def __init__(self, is_healthy_dataset, src_dir=None, coords_csv_path=None, dst_path=None, norm_save_dir=None, parallelize=False, coordSystem=None): self.parallelize = parallelize if coordSystem is None: self.coordSystem = config['traindata_coordSystem'] else: self.coordSystem = coordSystem if is_healthy_dataset: self.src_dir = src_dir if src_dir is not None else config['healthy_scans_raw'] self.dst_path = dst_path if dst_path is not None else config['healthy_samples'] self.norm_save_dir = norm_save_dir if norm_save_dir is not None else config['modelpath_remove'] self.coords = pd.read_csv(coords_csv_path) if coords_csv_path is not None else pd.read_csv( config['healthy_coords']) else: self.src_dir = src_dir if src_dir is not None else config['unhealthy_scans_raw'] self.dst_path = dst_path if dst_path is not None else config['unhealthy_samples'] self.norm_save_dir = norm_save_dir if norm_save_dir is not None else config['modelpath_inject'] self.coords = pd.read_csv(coords_csv_path) if coords_csv_path is not None else pd.read_csv( config['unhealthy_coords']) def extract(self, plot=True): # # Prep jobs (one per coordinate) print("preparing jobs...") J = [] # jobs for i, sample in self.coords.iterrows(): coord = np.array([sample.coordZ, sample.coordY, sample.coordX]) path_to_file = os.path.join(self.src_dir, '{}.mhd'.format(str(sample.seriesuid))) if not pd.isnull(sample.coordZ) and os.path.exists(path_to_file) and sample.diameter_mm > 10 and sample.diameter_mm < 16: print('diameter: {}'.format(sample.diameter_mm)) # job: (path to scan, coordinate, instance shape, coord system 'vox' or 'world') J.append([path_to_file, coord, config['cube_shape'], self.coordSystem]) print(len(J)) # J = J[:30] subset_number = 5 subset_len = len(J) // subset_number + 1 total_len = 0 for i in range(subset_number): subset = J[i * subset_len:(i + 1) * subset_len] total_len += self.extract_subset(subset, i) np.save('data/data_len.npy', total_len) def extract_subset(self, J, subset_i, plot=True): X = [] for job in J: try: X.append(self._processJob(job)) except: print("Failed to process sample") instances = np.array(list( itertools.chain.from_iterable(X))) # each job creates a batch of augmented instances: so collect hem # Histogram Equalization: print("equalizing the data...") eq = histEq(instances) instances = eq.equalize(instances) os.makedirs(self.norm_save_dir, exist_ok=True) eq.save(path=os.path.join(self.norm_save_dir, 'equalization.pkl')) # -1 1 Normalization print("normalizing the data...") min_v = np.min(instances) max_v = np.max(instances) mean_v = np.mean(instances) norm_data = np.array([mean_v, min_v, max_v]) instances = (instances - mean_v) / (max_v - min_v) np.save(os.path.join(self.norm_save_dir, 'normalization.npy'), norm_data) if plot: self.plot_sample(instances) print("saving the dataset") np.save(self.dst_path + '_{}.npy'.format(subset_i), instances) return len(instances) def _processJob(self, args): print("Working on job: " + args[0] + " " + args[3] + " coord (zyx): ", args[1]) instances = self._get_instances_from_scan(scan_path=args[0], coord=args[1], cube_shape=args[2], coordSystem=args[3]) return instances def _get_instances_from_scan(self, scan_path, coord, cube_shape, coordSystem): # load scan data scan, spacing, orientation, origin, raw_slices = load_scan(scan_path) # scale the image # scan_resized, resize_factor = scale_scan(scan, spacing) # compute sample coords as vox if coordSystem == 'world': # convert from world to vox coord = world2vox(coord, spacing, orientation, origin) elif coordSystem != 'vox': raise Exception("Coordinate conversion error: you can only select world or vox") # coordn = scale_vox_coord(coord, spacing) # ccord relative to scaled scan # extract instances X = [] init_cube_shape = get_scaled_shape(cube_shape + 8, 1 / spacing) clean_cube_unscaled = cutCube(scan, coord, init_cube_shape, padd=-1000) x, resize_factor = scale_scan(clean_cube_unscaled, spacing) # perform data augmentations to generate more instances Xaug = self._augmentInstance(x) # trim the borders to get the actual desired shape for xa in Xaug: center = np.array(x.shape) // 2 X.append(cutCube(xa, center, cube_shape, padd=-1000)) # cut out augmented cancer without extra boundry return X def _augmentInstance(self, x0): # xy flip xf_x = np.flip(x0, 1) xf_y = np.flip(x0, 2) xf_xy = np.flip(xf_x, 2) # xy shift xs1 = scipy.ndimage.shift(x0, (0, 4, 4), mode='constant') xs2 = scipy.ndimage.shift(x0, (0, -4, 4), mode='constant') xs3 = scipy.ndimage.shift(x0, (0, 4, -4), mode='constant') xs4 = scipy.ndimage.shift(x0, (0, -4, -4), mode='constant') # small rotations R = [] for ang in range(6, 360, 6): R.append(rotate(x0, ang, axes=(1, 2), mode='reflect', reshape=False)) X = [x0, xf_x, xf_y, xf_xy, xs1, xs2, xs3, xs4] + R # remove instances which are cropped out of bounds of scan Res = [] for x in X: if (x.shape[0] != 0) and (x.shape[1] != 0) and (x.shape[2] != 0): Res.append(x) return Res def plot_sample(self, X): import matplotlib.pyplot as plt r, c = 3, 10 batch = X[np.random.permutation(len(X))[:30]] fig, axs = plt.subplots(r, c, figsize=np.array([30, 10]) * .5) fig.suptitle( 'Random sample of extracted instances: middle slice shown\nIf target samples are incorrect, consider swapping input target x and y coords.') cnt = 0 for i in range(r): for j in range(c): if cnt < len(batch): axs[i, j].imshow(batch[cnt][16, :, :], cmap='bone') axs[i, j].axis('off') cnt += 1 plt.show()
48.282723
165
0.639666
5018913c352ec47afecd8b332cfa1d3d960cefc4
4,473
py
Python
bot/bot_handlers/register.py
alimahdiyar/Developing-Community-Web
a663a687e0f286f197d4a7bf347f67cd130275f7
[ "MIT" ]
2
2018-06-02T12:30:00.000Z
2018-07-19T14:41:39.000Z
bot/bot_handlers/register.py
Developing-Community/Developing-Community-Web
a663a687e0f286f197d4a7bf347f67cd130275f7
[ "MIT" ]
5
2021-06-08T19:09:00.000Z
2022-03-11T23:25:14.000Z
bot/bot_handlers/register.py
Developing-Community/web
a663a687e0f286f197d4a7bf347f67cd130275f7
[ "MIT" ]
2
2018-05-27T14:58:34.000Z
2018-05-27T15:03:04.000Z
from django.contrib.auth import get_user_model from bot.bot_strings import bot_commands, bot_messages, bot_keyboards from bot.models import TelegramUserInputKeys, TelegramUserInput, MenuState from web import settings User = get_user_model() # TODO: validate email, username and password to have only valid characters def handle_pv_register_get_email(telegram_profile, msg): if msg['text'] == bot_commands['return']: message = bot_messages['start_msg'] % (settings.HOST_URL, telegram_profile.verify_token) keyboard = bot_keyboards['login_or_register'] telegram_profile.user_input.all().delete() telegram_profile.menu_state = MenuState.START telegram_profile.save() else: telegram_profile.user_input.all().delete() if User.objects.filter(email=msg['text']).exists(): message = bot_messages['register_email_exists_err'] keyboard = bot_keyboards['return'] else: telegram_profile.user_input.create(key=TelegramUserInputKeys.EMAIL, value=msg['text']) message = bot_messages['register_get_username'] keyboard = bot_keyboards['return'] telegram_profile.menu_state = MenuState.REGISTER_GET_USERNAME telegram_profile.save() return message, keyboard def handle_pv_register_get_username(telegram_profile, msg): if msg['text'] == bot_commands['return']: message = bot_messages['register_get_email'] keyboard = bot_keyboards['return'] telegram_profile.user_input.all().delete() telegram_profile.menu_state = MenuState.REGISTER_GET_EMAIL telegram_profile.save() else: try: email = telegram_profile.user_input.get(key=TelegramUserInputKeys.EMAIL).value except TelegramUserInput.DoesNotExist: telegram_profile.user_input.all().delete() telegram_profile.menu_state = MenuState.REGISTER_GET_EMAIL telegram_profile.save() message, keyboard = handle_pv_register_get_email(telegram_profile, msg) else: telegram_profile.user_input.filter(key=TelegramUserInputKeys.USERNAME).delete() if User.objects.filter(username=msg['text']).exists(): message = bot_messages['register_username_exists_err'] keyboard = [[bot_commands['return']]] else: telegram_profile.user_input.create(key=TelegramUserInputKeys.USERNAME, value=msg['text']) message = bot_messages['register_get_password'] keyboard = [[bot_commands['return']]] telegram_profile.menu_state = MenuState.REGISTER_GET_PASSWORD telegram_profile.save() return message, keyboard def handle_pv_register_get_password(telegram_profile, msg): if msg['text'] == bot_commands['return']: message = bot_messages['register_get_username'] keyboard = bot_keyboards['return'] telegram_profile.user_input.filter(key=TelegramUserInputKeys.USERNAME).delete() telegram_profile.menu_state = MenuState.REGISTER_GET_USERNAME telegram_profile.save() else: try: email = telegram_profile.user_input.get(key=TelegramUserInputKeys.EMAIL).value except TelegramUserInput.DoesNotExist: telegram_profile.user_input.all().delete() telegram_profile.menu_state = MenuState.REGISTER_GET_EMAIL telegram_profile.save() message, keyboard = handle_pv_register_get_email(telegram_profile, msg) else: try: username = telegram_profile.user_input.get(key=TelegramUserInputKeys.USERNAME).value except TelegramUserInput.DoesNotExist: telegram_profile.menu_state = MenuState.REGISTER_GET_USERNAME telegram_profile.save() message, keyboard = handle_pv_register_get_username(telegram_profile, msg) else: user = User(username=username, email=email) user.set_password(msg['text']) user.save() telegram_profile.user_input.all().delete() telegram_profile.profile = user.profile.first() telegram_profile.menu_state = MenuState.START telegram_profile.save() message = bot_messages['register_success'] keyboard = bot_keyboards['main_menu'] return message, keyboard
41.416667
105
0.674939
c8195473907b16e959adac6522ac7be5ac39a826
265
py
Python
Python/treehopper/libraries/sensors/magnetic/__init__.py
ehailey1/treehopper-sdk
c242f939a93d93da11ff79577666130c15aecec7
[ "MIT" ]
3
2018-03-16T07:00:42.000Z
2022-03-27T00:39:55.000Z
Python/treehopper/libraries/sensors/magnetic/__init__.py
ehailey1/treehopper-sdk
c242f939a93d93da11ff79577666130c15aecec7
[ "MIT" ]
16
2016-08-12T18:51:04.000Z
2021-04-16T16:14:07.000Z
Python/treehopper/libraries/sensors/magnetic/__init__.py
ehailey1/treehopper-sdk
c242f939a93d93da11ff79577666130c15aecec7
[ "MIT" ]
6
2015-11-04T15:53:49.000Z
2020-06-25T18:34:47.000Z
""" Compasses, Hall effect sensors, and 3D magnetic position sensors """ ## @namespace treehopper.libraries.sensors.magnetic from treehopper.libraries.sensors.magnetic.ak8975 import Ak8975 from treehopper.libraries.sensors.magnetic.magnetometer import Magnetometer
37.857143
75
0.833962
baf6402a6215ee73ac3e09300ffdc174d8421763
13,907
py
Python
import_data/celery_fitbit.py
cjb/quantified-flu
c925c95704de846aab16273807ebc75f52024816
[ "MIT" ]
null
null
null
import_data/celery_fitbit.py
cjb/quantified-flu
c925c95704de846aab16273807ebc75f52024816
[ "MIT" ]
null
null
null
import_data/celery_fitbit.py
cjb/quantified-flu
c925c95704de846aab16273807ebc75f52024816
[ "MIT" ]
null
null
null
""" Asynchronous tasks that update data in Open Humans. These tasks: 1. delete any current files in OH if they match the planned upload filename 2. adds a data file """ import logging import json import tempfile import requests import arrow from datetime import datetime from quantified_flu.settings import rr from requests_respectful import RequestsRespectfulRateLimitedError # Set up logging. logger = logging.getLogger(__name__) def fetch_fitbit_data(fitbit_member): """ Fetches all of the fitbit data for a given user """ restart_job = None fitbit_urls = [ # Requires the 'settings' scope, which we haven't asked for # {'name': 'devices', 'url': '/-/devices.json', 'period': None}, { "name": "activities-overview", "url": "/{user_id}/activities.json", "period": None, }, # interday timeline data { "name": "heart", "url": "/{user_id}/activities/heart/date/{start_date}/{end_date}.json", "period": "month", }, # MPB 2016-12-12: Although docs allowed for 'year' for this endpoint, # switched to 'month' bc/ req for full year started resulting in 504. { "name": "tracker-activity-calories", "url": "/{user_id}/activities/tracker/activityCalories/date/{start_date}/{end_date}.json", "period": "month", }, { "name": "tracker-calories", "url": "/{user_id}/activities/tracker/calories/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "tracker-distance", "url": "/{user_id}/activities/tracker/distance/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "tracker-elevation", "url": "/{user_id}/activities/tracker/elevation/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "tracker-floors", "url": "/{user_id}/activities/tracker/floors/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "tracker-minutes-fairly-active", "url": "/{user_id}/activities/tracker/minutesFairlyActive/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "tracker-minutes-lightly-active", "url": "/{user_id}/activities/tracker/minutesLightlyActive/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "tracker-minutes-sedentary", "url": "/{user_id}/activities/tracker/minutesSedentary/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "tracker-minutes-very-active", "url": "/{user_id}/activities/tracker/minutesVeryActive/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "tracker-steps", "url": "/{user_id}/activities/tracker/steps/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "weight-log", "url": "/{user_id}/body/log/weight/date/{start_date}/{end_date}.json", "period": "month", }, { "name": "weight", "url": "/{user_id}/body/weight/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "sleep-awakenings", "url": "/{user_id}/sleep/awakeningsCount/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "sleep-efficiency", "url": "/{user_id}/sleep/efficiency/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "sleep-minutes-after-wakeup", "url": "/{user_id}/sleep/minutesAfterWakeup/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "sleep-minutes", "url": "/{user_id}/sleep/minutesAsleep/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "awake-minutes", "url": "/{user_id}/sleep/minutesAwake/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "minutes-to-sleep", "url": "/{user_id}/sleep/minutesToFallAsleep/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "sleep-start-time", "url": "/{user_id}/sleep/startTime/date/{start_date}/{end_date}.json", "period": "year", }, { "name": "time-in-bed", "url": "/{user_id}/sleep/timeInBed/date/{start_date}/{end_date}.json", "period": "year", }, ] fitbit_access_token = fitbit_member.get_access_token() # Get existing data as currently stored on OH fitbit_data, old_fid = get_existing_fitbit(fitbit_member.member, fitbit_urls) # Set up user realm since rate limiting is per-user print(fitbit_member.member) user_realm = "fitbit-{}".format(fitbit_member.member.oh_id) rr.register_realm(user_realm, max_requests=150, timespan=3600) rr.update_realm(user_realm, max_requests=150, timespan=3600) # Get initial information about user from Fitbit print("Creating header and going to get user profile") headers = {"Authorization": "Bearer %s" % fitbit_access_token} query_result = requests.get( "https://api.fitbit.com/1/user/-/profile.json", headers=headers ).json() # Store the user ID since it's used in all future queries user_id = query_result["user"]["encodedId"] member_since = query_result["user"]["memberSince"] start_date = arrow.get(member_since, "YYYY-MM-DD") # TODO: update this so it just checks the expired field. # if query_result.status_code == 401: # fitbit_member._refresh_tokens() if not fitbit_data: print("empty data") # fitbit_data = {} # return # Reset data if user account ID has changed. print("reset data if user account ID changed") if "profile" in fitbit_data: if fitbit_data["profile"]["encodedId"] != user_id: logging.info( "User ID changed from {} to {}. Resetting all data.".format( fitbit_data["profile"]["encodedId"], user_id ) ) fitbit_data = {} for url in fitbit_urls: fitbit_data[url["name"]] = {} else: logging.debug("User ID ({}) matches old data.".format(user_id)) fitbit_data["profile"] = { "averageDailySteps": query_result["user"]["averageDailySteps"], "encodedId": user_id, "height": query_result["user"]["height"], "memberSince": member_since, "strideLengthRunning": query_result["user"]["strideLengthRunning"], "strideLengthWalking": query_result["user"]["strideLengthWalking"], "weight": query_result["user"]["weight"], } print("entering try block") try: # Some block about if the period is none print("period none") for url in [u for u in fitbit_urls if u["period"] is None]: if not user_id and "profile" in fitbit_data: user_id = fitbit_data["profile"]["user"]["encodedId"] # Build URL fitbit_api_base_url = "https://api.fitbit.com/1/user" final_url = fitbit_api_base_url + url["url"].format(user_id=user_id) # Fetch the data print(final_url) r = rr.get( url=final_url, headers=headers, realms=["Fitbit", "fitbit-{}".format(fitbit_member.member.oh_id)], ) print(r.text) # print(fitbit_data) fitbit_data[url["name"]] = r.json() # Period year URLs print("period year") # print(fitbit_data) for url in [u for u in fitbit_urls if u["period"] == "year"]: # print("LOOPED OVER A URL" + str(url)) print("attempting to print the latest YEAR that data is present") if len(list(fitbit_data[url["name"]].keys())) > 0: print(sorted(fitbit_data[url["name"]].keys())[-1]) last_present_year = sorted(fitbit_data[url["name"]].keys())[-1] else: print("no prior data") last_present_year = "" years = arrow.Arrow.range("year", start_date.floor("year"), arrow.get()) # print(years) for year_date in years: # print(year_date) year = year_date.format("YYYY") if year in fitbit_data[url["name"]] and year != last_present_year: logger.info("Skip retrieval {}: {}".format(url["name"], year)) continue logger.info("Retrieving %s: %s", url["name"], year) # Build URL fitbit_api_base_url = "https://api.fitbit.com/1/user" final_url = fitbit_api_base_url + url["url"].format( user_id=user_id, start_date=year_date.floor("year").format("YYYY-MM-DD"), end_date=year_date.ceil("year").format("YYYY-MM-DD"), ) # Fetch the data print(final_url) r = rr.get( url=final_url, headers=headers, realms=["Fitbit", "fitbit-{}".format(fitbit_member.member.oh_id)], ) # print([url['name']]['blah']) # print([str(year)]) fitbit_data[url["name"]][str(year)] = r.json() # Month period URLs/fetching # print(fitbit_data) print("period month") for url in [u for u in fitbit_urls if u["period"] == "month"]: # get the last time there was data print("attempting to print the latest month that data is present") if len(list(fitbit_data[url["name"]].keys())) > 0: print(sorted(fitbit_data[url["name"]].keys())[-1]) last_present_month = sorted(fitbit_data[url["name"]].keys())[-1] else: print("no prior month") last_present_month = "" months = arrow.Arrow.range("month", start_date.floor("month"), arrow.get()) for month_date in months: month = month_date.format("YYYY-MM") # print("in month loop, here is the json data") # print(fitbit_data[url['name']][month]) if month in fitbit_data[url["name"]] and month != last_present_month: print("skipping month, data is there") print(month) logger.info("Skip retrieval {}: {}".format(url["name"], month)) continue logger.info("Retrieving %s: %s", url["name"], month) # Build URL fitbit_api_base_url = "https://api.fitbit.com/1/user" final_url = fitbit_api_base_url + url["url"].format( user_id=user_id, start_date=month_date.floor("month").format("YYYY-MM-DD"), end_date=month_date.ceil("month").format("YYYY-MM-DD"), ) # Fetch the data print(final_url) r = rr.get( url=final_url, headers=headers, realms=["Fitbit", "fitbit-{}".format(fitbit_member.member.oh_id)], ) fitbit_data[url["name"]][month] = r.json() # Update the last updated date if the data successfully completes fitbit_member.last_updated = arrow.now().format() fitbit_member.save() except RequestsRespectfulRateLimitedError: logging.info("Requests-respectful reports rate limit hit.") print("hit requests respectful rate limit, going to requeue") restart_job = "yes please" # raise RateLimitException() finally: print("calling finally") # print(fitbit_data) replace_fitbit(fitbit_member.member, fitbit_data, old_fid) return restart_job # return fitbit_data def get_existing_fitbit(oh_member, fitbit_urls): print("entered get_existing_fitbit") for dfile in oh_member.list_files(): if "QF-Fitbit" in dfile["metadata"]["tags"]: print("got inside fitbit if") # get file here and read the json into memory tf_in = tempfile.NamedTemporaryFile(suffix=".json") tf_in.write(requests.get(dfile["download_url"]).content) tf_in.flush() fitbit_data = json.load(open(tf_in.name)) print("fetched existing data from OH") # print(fitbit_data) return fitbit_data, dfile["id"] fitbit_data = {} for url in fitbit_urls: fitbit_data[url["name"]] = {} return (fitbit_data, None) def replace_fitbit(oh_member, fitbit_data, old_fid): print("replace function started") # delete old file and upload new to open humans metadata = { "description": "Fitbit data from QF.", "tags": ["QF-Fitbit", "activity", "steps", "quantified flu"], "updated_at": str(datetime.utcnow()), } with tempfile.TemporaryFile() as f: js = json.dumps(fitbit_data) js = str.encode(js) f.write(js) f.flush() f.seek(0) oh_member.upload(stream=f, filename="QF-fitbit-data.json", metadata=metadata) if old_fid: oh_member.delete_single_file(file_id=old_fid)
37.997268
106
0.548501
86c3281e44592959e34696bef99fd7dcfe0ccd66
683
py
Python
tests/test_math.py
mlestep/octo_tribble
887bf40095ff99797f7e39282b82eb3b05067e88
[ "BSD-3-Clause" ]
null
null
null
tests/test_math.py
mlestep/octo_tribble
887bf40095ff99797f7e39282b82eb3b05067e88
[ "BSD-3-Clause" ]
null
null
null
tests/test_math.py
mlestep/octo_tribble
887bf40095ff99797f7e39282b82eb3b05067e88
[ "BSD-3-Clause" ]
null
null
null
""" Testing for the math.py module """ import octo_tribble as ot import pytest def test_add(): assert ot.math.add(5, 2) == 7 assert ot.math.add(2, 5) == 7 testdata = [ (2, 5, 10), (1, 2, 2), (11, 9, 99), (11, 0, 0), (0, 0, 0), ] @pytest.mark.parametrize("a,b,expected", testdata) def test_mult(a, b, expected): assert ot.math.mult(a, b) == expected assert ot.math.mult(b, a) == expected testdata2 = [ (1, 2, 95), (0, 0, 42), (-5, 10, 30167), (2, 2, 110), (3, 7, 7290), ] @pytest.mark.parametrize("a,b,expected", testdata2) def test_awesome(a, b, expected): assert ot.submodule.more_functs.awesome(a, b) == expected
17.973684
61
0.573939
7fb5301113467ba5428b0759d577892f77146142
20,921
py
Python
API/src/main/resources/Lib/xlrd/compdoc.py
MiguelDomingues/SikuliX1
4ff932ae616b1c1fd5409f6e8fbf6c4615aa52f3
[ "MIT" ]
4
2021-04-27T10:48:39.000Z
2022-02-13T12:04:04.000Z
API/src/main/resources/Lib/xlrd/compdoc.py
MiguelDomingues/SikuliX1
4ff932ae616b1c1fd5409f6e8fbf6c4615aa52f3
[ "MIT" ]
null
null
null
API/src/main/resources/Lib/xlrd/compdoc.py
MiguelDomingues/SikuliX1
4ff932ae616b1c1fd5409f6e8fbf6c4615aa52f3
[ "MIT" ]
null
null
null
# -*- coding: cp1252 -*- ## ## # No part of the content of this file was derived from the works of David Giffin. # 2008-11-04 SJM Avoid assertion error when -1 used instead of -2 for first_SID of empty SCSS [Frank Hoffsuemmer] # 2007-09-08 SJM Warning message if sector sizes are extremely large. # 2007-05-07 SJM Meaningful exception instead of IndexError if a SAT (sector allocation table) is corrupted. # 2007-04-22 SJM Missing "<" in a struct.unpack call => can't open files on bigendian platforms. from __future__ import print_function import sys from struct import unpack from .timemachine import * import array ## # Magic cookie that should appear in the first 8 bytes of the file. SIGNATURE = b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" EOCSID = -2 FREESID = -1 SATSID = -3 MSATSID = -4 EVILSID = -5 class CompDocError(Exception): pass class DirNode(object): def __init__(self, DID, dent, DEBUG=0, logfile=sys.stdout): # dent is the 128-byte directory entry self.DID = DID self.logfile = logfile (cbufsize, self.etype, self.colour, self.left_DID, self.right_DID, self.root_DID) = \ unpack('<HBBiii', dent[64:80]) (self.first_SID, self.tot_size) = \ unpack('<ii', dent[116:124]) if cbufsize == 0: self.name = UNICODE_LITERAL('') else: self.name = unicode(dent[0:cbufsize-2], 'utf_16_le') # omit the trailing U+0000 self.children = [] # filled in later self.parent = -1 # indicates orphan; fixed up later self.tsinfo = unpack('<IIII', dent[100:116]) if DEBUG: self.dump(DEBUG) def dump(self, DEBUG=1): fprintf( self.logfile, "DID=%d name=%r etype=%d DIDs(left=%d right=%d root=%d parent=%d kids=%r) first_SID=%d tot_size=%d\n", self.DID, self.name, self.etype, self.left_DID, self.right_DID, self.root_DID, self.parent, self.children, self.first_SID, self.tot_size ) if DEBUG == 2: # cre_lo, cre_hi, mod_lo, mod_hi = tsinfo print("timestamp info", self.tsinfo, file=self.logfile) def _build_family_tree(dirlist, parent_DID, child_DID): if child_DID < 0: return _build_family_tree(dirlist, parent_DID, dirlist[child_DID].left_DID) dirlist[parent_DID].children.append(child_DID) dirlist[child_DID].parent = parent_DID _build_family_tree(dirlist, parent_DID, dirlist[child_DID].right_DID) if dirlist[child_DID].etype == 1: # storage _build_family_tree(dirlist, child_DID, dirlist[child_DID].root_DID) ## # Compound document handler. # @param mem The raw contents of the file, as a string, or as an mmap.mmap() object. The # only operation it needs to support is slicing. class CompDoc(object): def __init__(self, mem, logfile=sys.stdout, DEBUG=0): self.logfile = logfile self.DEBUG = DEBUG if mem[0:8] != SIGNATURE: raise CompDocError('Not an OLE2 compound document') if mem[28:30] != b'\xFE\xFF': raise CompDocError('Expected "little-endian" marker, found %r' % mem[28:30]) revision, version = unpack('<HH', mem[24:28]) if DEBUG: print("\nCompDoc format: version=0x%04x revision=0x%04x" % (version, revision), file=logfile) self.mem = mem ssz, sssz = unpack('<HH', mem[30:34]) if ssz > 20: # allows for 2**20 bytes i.e. 1MB print("WARNING: sector size (2**%d) is preposterous; assuming 512 and continuing ..." \ % ssz, file=logfile) ssz = 9 if sssz > ssz: print("WARNING: short stream sector size (2**%d) is preposterous; assuming 64 and continuing ..." \ % sssz, file=logfile) sssz = 6 self.sec_size = sec_size = 1 << ssz self.short_sec_size = 1 << sssz if self.sec_size != 512 or self.short_sec_size != 64: print("@@@@ sec_size=%d short_sec_size=%d" % (self.sec_size, self.short_sec_size), file=logfile) ( SAT_tot_secs, self.dir_first_sec_sid, _unused, self.min_size_std_stream, SSAT_first_sec_sid, SSAT_tot_secs, MSATX_first_sec_sid, MSATX_tot_secs, # ) = unpack('<ii4xiiiii', mem[44:76]) ) = unpack('<iiiiiiii', mem[44:76]) mem_data_len = len(mem) - 512 mem_data_secs, left_over = divmod(mem_data_len, sec_size) if left_over: #### raise CompDocError("Not a whole number of sectors") mem_data_secs += 1 print("WARNING *** file size (%d) not 512 + multiple of sector size (%d)" \ % (len(mem), sec_size), file=logfile) self.mem_data_secs = mem_data_secs # use for checking later self.mem_data_len = mem_data_len seen = self.seen = array.array('B', [0]) * mem_data_secs if DEBUG: print('sec sizes', ssz, sssz, sec_size, self.short_sec_size, file=logfile) print("mem data: %d bytes == %d sectors" % (mem_data_len, mem_data_secs), file=logfile) print("SAT_tot_secs=%d, dir_first_sec_sid=%d, min_size_std_stream=%d" \ % (SAT_tot_secs, self.dir_first_sec_sid, self.min_size_std_stream,), file=logfile) print("SSAT_first_sec_sid=%d, SSAT_tot_secs=%d" % (SSAT_first_sec_sid, SSAT_tot_secs,), file=logfile) print("MSATX_first_sec_sid=%d, MSATX_tot_secs=%d" % (MSATX_first_sec_sid, MSATX_tot_secs,), file=logfile) nent = sec_size // 4 # number of SID entries in a sector fmt = "<%di" % nent trunc_warned = 0 # # === build the MSAT === # MSAT = list(unpack('<109i', mem[76:512])) SAT_sectors_reqd = (mem_data_secs + nent - 1) // nent expected_MSATX_sectors = max(0, (SAT_sectors_reqd - 109 + nent - 2) // (nent - 1)) actual_MSATX_sectors = 0 if MSATX_tot_secs == 0 and MSATX_first_sec_sid in (EOCSID, FREESID, 0): # Strictly, if there is no MSAT extension, then MSATX_first_sec_sid # should be set to EOCSID ... FREESID and 0 have been met in the wild. pass # Presuming no extension else: sid = MSATX_first_sec_sid while sid not in (EOCSID, FREESID): # Above should be only EOCSID according to MS & OOo docs # but Excel doesn't complain about FREESID. Zero is a valid # sector number, not a sentinel. if DEBUG > 1: print('MSATX: sid=%d (0x%08X)' % (sid, sid), file=logfile) if sid >= mem_data_secs: msg = "MSAT extension: accessing sector %d but only %d in file" % (sid, mem_data_secs) if DEBUG > 1: print(msg, file=logfile) break raise CompDocError(msg) elif sid < 0: raise CompDocError("MSAT extension: invalid sector id: %d" % sid) if seen[sid]: raise CompDocError("MSAT corruption: seen[%d] == %d" % (sid, seen[sid])) seen[sid] = 1 actual_MSATX_sectors += 1 if DEBUG and actual_MSATX_sectors > expected_MSATX_sectors: print("[1]===>>>", mem_data_secs, nent, SAT_sectors_reqd, expected_MSATX_sectors, actual_MSATX_sectors, file=logfile) offset = 512 + sec_size * sid MSAT.extend(unpack(fmt, mem[offset:offset+sec_size])) sid = MSAT.pop() # last sector id is sid of next sector in the chain if DEBUG and actual_MSATX_sectors != expected_MSATX_sectors: print("[2]===>>>", mem_data_secs, nent, SAT_sectors_reqd, expected_MSATX_sectors, actual_MSATX_sectors, file=logfile) if DEBUG: print("MSAT: len =", len(MSAT), file=logfile) dump_list(MSAT, 10, logfile) # # === build the SAT === # self.SAT = [] actual_SAT_sectors = 0 dump_again = 0 for msidx in xrange(len(MSAT)): msid = MSAT[msidx] if msid in (FREESID, EOCSID): # Specification: the MSAT array may be padded with trailing FREESID entries. # Toleration: a FREESID or EOCSID entry anywhere in the MSAT array will be ignored. continue if msid >= mem_data_secs: if not trunc_warned: print("WARNING *** File is truncated, or OLE2 MSAT is corrupt!!", file=logfile) print("INFO: Trying to access sector %d but only %d available" \ % (msid, mem_data_secs), file=logfile) trunc_warned = 1 MSAT[msidx] = EVILSID dump_again = 1 continue elif msid < -2: raise CompDocError("MSAT: invalid sector id: %d" % msid) if seen[msid]: raise CompDocError("MSAT extension corruption: seen[%d] == %d" % (msid, seen[msid])) seen[msid] = 2 actual_SAT_sectors += 1 if DEBUG and actual_SAT_sectors > SAT_sectors_reqd: print("[3]===>>>", mem_data_secs, nent, SAT_sectors_reqd, expected_MSATX_sectors, actual_MSATX_sectors, actual_SAT_sectors, msid, file=logfile) offset = 512 + sec_size * msid self.SAT.extend(unpack(fmt, mem[offset:offset+sec_size])) if DEBUG: print("SAT: len =", len(self.SAT), file=logfile) dump_list(self.SAT, 10, logfile) # print >> logfile, "SAT ", # for i, s in enumerate(self.SAT): # print >> logfile, "entry: %4d offset: %6d, next entry: %4d" % (i, 512 + sec_size * i, s) # print >> logfile, "%d:%d " % (i, s), print(file=logfile) if DEBUG and dump_again: print("MSAT: len =", len(MSAT), file=logfile) dump_list(MSAT, 10, logfile) for satx in xrange(mem_data_secs, len(self.SAT)): self.SAT[satx] = EVILSID print("SAT: len =", len(self.SAT), file=logfile) dump_list(self.SAT, 10, logfile) # # === build the directory === # dbytes = self._get_stream( self.mem, 512, self.SAT, self.sec_size, self.dir_first_sec_sid, name="directory", seen_id=3) dirlist = [] did = -1 for pos in xrange(0, len(dbytes), 128): did += 1 dirlist.append(DirNode(did, dbytes[pos:pos+128], 0, logfile)) self.dirlist = dirlist _build_family_tree(dirlist, 0, dirlist[0].root_DID) # and stand well back ... if DEBUG: for d in dirlist: d.dump(DEBUG) # # === get the SSCS === # sscs_dir = self.dirlist[0] assert sscs_dir.etype == 5 # root entry if sscs_dir.first_SID < 0 or sscs_dir.tot_size == 0: # Problem reported by Frank Hoffsuemmer: some software was # writing -1 instead of -2 (EOCSID) for the first_SID # when the SCCS was empty. Not having EOCSID caused assertion # failure in _get_stream. # Solution: avoid calling _get_stream in any case when the # SCSS appears to be empty. self.SSCS = "" else: self.SSCS = self._get_stream( self.mem, 512, self.SAT, sec_size, sscs_dir.first_SID, sscs_dir.tot_size, name="SSCS", seen_id=4) # if DEBUG: print >> logfile, "SSCS", repr(self.SSCS) # # === build the SSAT === # self.SSAT = [] if SSAT_tot_secs > 0 and sscs_dir.tot_size == 0: print("WARNING *** OLE2 inconsistency: SSCS size is 0 but SSAT size is non-zero", file=logfile) if sscs_dir.tot_size > 0: sid = SSAT_first_sec_sid nsecs = SSAT_tot_secs while sid >= 0 and nsecs > 0: if seen[sid]: raise CompDocError("SSAT corruption: seen[%d] == %d" % (sid, seen[sid])) seen[sid] = 5 nsecs -= 1 start_pos = 512 + sid * sec_size news = list(unpack(fmt, mem[start_pos:start_pos+sec_size])) self.SSAT.extend(news) sid = self.SAT[sid] if DEBUG: print("SSAT last sid %d; remaining sectors %d" % (sid, nsecs), file=logfile) assert nsecs == 0 and sid == EOCSID if DEBUG: print("SSAT", file=logfile) dump_list(self.SSAT, 10, logfile) if DEBUG: print("seen", file=logfile) dump_list(seen, 20, logfile) def _get_stream(self, mem, base, sat, sec_size, start_sid, size=None, name='', seen_id=None): # print >> self.logfile, "_get_stream", base, sec_size, start_sid, size sectors = [] s = start_sid if size is None: # nothing to check against while s >= 0: if seen_id is not None: if self.seen[s]: raise CompDocError("%s corruption: seen[%d] == %d" % (name, s, self.seen[s])) self.seen[s] = seen_id start_pos = base + s * sec_size sectors.append(mem[start_pos:start_pos+sec_size]) try: s = sat[s] except IndexError: raise CompDocError( "OLE2 stream %r: sector allocation table invalid entry (%d)" % (name, s) ) assert s == EOCSID else: todo = size while s >= 0: if seen_id is not None: if self.seen[s]: raise CompDocError("%s corruption: seen[%d] == %d" % (name, s, self.seen[s])) self.seen[s] = seen_id start_pos = base + s * sec_size grab = sec_size if grab > todo: grab = todo todo -= grab sectors.append(mem[start_pos:start_pos+grab]) try: s = sat[s] except IndexError: raise CompDocError( "OLE2 stream %r: sector allocation table invalid entry (%d)" % (name, s) ) assert s == EOCSID if todo != 0: fprintf(self.logfile, "WARNING *** OLE2 stream %r: expected size %d, actual size %d\n", name, size, size - todo) return b''.join(sectors) def _dir_search(self, path, storage_DID=0): # Return matching DirNode instance, or None head = path[0] tail = path[1:] dl = self.dirlist for child in dl[storage_DID].children: if dl[child].name.lower() == head.lower(): et = dl[child].etype if et == 2: return dl[child] if et == 1: if not tail: raise CompDocError("Requested component is a 'storage'") return self._dir_search(tail, child) dl[child].dump(1) raise CompDocError("Requested stream is not a 'user stream'") return None ## # Interrogate the compound document's directory; return the stream as a string if found, otherwise # return None. # @param qname Name of the desired stream e.g. u'Workbook'. Should be in Unicode or convertible thereto. def get_named_stream(self, qname): d = self._dir_search(qname.split("/")) if d is None: return None if d.tot_size >= self.min_size_std_stream: return self._get_stream( self.mem, 512, self.SAT, self.sec_size, d.first_SID, d.tot_size, name=qname, seen_id=d.DID+6) else: return self._get_stream( self.SSCS, 0, self.SSAT, self.short_sec_size, d.first_SID, d.tot_size, name=qname + " (from SSCS)", seen_id=None) ## # Interrogate the compound document's directory. # If the named stream is not found, (None, 0, 0) will be returned. # If the named stream is found and is contiguous within the original byte sequence ("mem") # used when the document was opened, # then (mem, offset_to_start_of_stream, length_of_stream) is returned. # Otherwise a new string is built from the fragments and (new_string, 0, length_of_stream) is returned. # @param qname Name of the desired stream e.g. u'Workbook'. Should be in Unicode or convertible thereto. def locate_named_stream(self, qname): d = self._dir_search(qname.split("/")) if d is None: return (None, 0, 0) if d.tot_size > self.mem_data_len: raise CompDocError("%r stream length (%d bytes) > file data size (%d bytes)" % (qname, d.tot_size, self.mem_data_len)) if d.tot_size >= self.min_size_std_stream: result = self._locate_stream( self.mem, 512, self.SAT, self.sec_size, d.first_SID, d.tot_size, qname, d.DID+6) if self.DEBUG: print("\nseen", file=self.logfile) dump_list(self.seen, 20, self.logfile) return result else: return ( self._get_stream( self.SSCS, 0, self.SSAT, self.short_sec_size, d.first_SID, d.tot_size, qname + " (from SSCS)", None), 0, d.tot_size ) def _locate_stream(self, mem, base, sat, sec_size, start_sid, expected_stream_size, qname, seen_id): # print >> self.logfile, "_locate_stream", base, sec_size, start_sid, expected_stream_size s = start_sid if s < 0: raise CompDocError("_locate_stream: start_sid (%d) is -ve" % start_sid) p = -99 # dummy previous SID start_pos = -9999 end_pos = -8888 slices = [] tot_found = 0 found_limit = (expected_stream_size + sec_size - 1) // sec_size while s >= 0: if self.seen[s]: print("_locate_stream(%s): seen" % qname, file=self.logfile); dump_list(self.seen, 20, self.logfile) raise CompDocError("%s corruption: seen[%d] == %d" % (qname, s, self.seen[s])) self.seen[s] = seen_id tot_found += 1 if tot_found > found_limit: raise CompDocError( "%s: size exceeds expected %d bytes; corrupt?" % (qname, found_limit * sec_size) ) # Note: expected size rounded up to higher sector if s == p+1: # contiguous sectors end_pos += sec_size else: # start new slice if p >= 0: # not first time slices.append((start_pos, end_pos)) start_pos = base + s * sec_size end_pos = start_pos + sec_size p = s s = sat[s] assert s == EOCSID assert tot_found == found_limit # print >> self.logfile, "_locate_stream(%s): seen" % qname; dump_list(self.seen, 20, self.logfile) if not slices: # The stream is contiguous ... just what we like! return (mem, start_pos, expected_stream_size) slices.append((start_pos, end_pos)) # print >> self.logfile, "+++>>> %d fragments" % len(slices) return (b''.join([mem[start_pos:end_pos] for start_pos, end_pos in slices]), 0, expected_stream_size) # ========================================================================================== def x_dump_line(alist, stride, f, dpos, equal=0): print("%5d%s" % (dpos, " ="[equal]), end=' ', file=f) for value in alist[dpos:dpos + stride]: print(str(value), end=' ', file=f) print(file=f) def dump_list(alist, stride, f=sys.stdout): def _dump_line(dpos, equal=0): print("%5d%s" % (dpos, " ="[equal]), end=' ', file=f) for value in alist[dpos:dpos + stride]: print(str(value), end=' ', file=f) print(file=f) pos = None oldpos = None for pos in xrange(0, len(alist), stride): if oldpos is None: _dump_line(pos) oldpos = pos elif alist[pos:pos+stride] != alist[oldpos:oldpos+stride]: if pos - oldpos > stride: _dump_line(pos - stride, equal=1) _dump_line(pos) oldpos = pos if oldpos is not None and pos is not None and pos != oldpos: _dump_line(pos, equal=1)
44.607676
159
0.551312
db985022d65a2c62821d236de1b742fc821e15c0
3,433
py
Python
python/Stream_Cipher/Transportation_Cipher.py
sys41x4/Cryptography_Scripts
85afa55e2534068d53ee7bcf384d567f56fa06bc
[ "MIT" ]
null
null
null
python/Stream_Cipher/Transportation_Cipher.py
sys41x4/Cryptography_Scripts
85afa55e2534068d53ee7bcf384d567f56fa06bc
[ "MIT" ]
null
null
null
python/Stream_Cipher/Transportation_Cipher.py
sys41x4/Cryptography_Scripts
85afa55e2534068d53ee7bcf384d567f56fa06bc
[ "MIT" ]
null
null
null
class Transportation_Cipher: def print_table(table): longest_cols = [ (max([len(str(row[i])) for row in table]) + 1) for i in range(len(table[0])) ] row_format = "".join(["{:>" + str(longest_col) + "}" for longest_col in longest_cols]) print('MATRIX:\n') for row_num in range(len(table)): print(row_format.format(*table[row_num])) if row_num<2: print (row_format.format(*(['-']*len(table[row_num])))) print() def encoder(plain_text, key, show_matrix='hide'): key_sorted = list(key.upper()) key_sorted.sort() key = list(key) key_matrix = [""]*len(key) # Get the total Number of columns required # for pt_matrix marker=0 pre_pt_matrix=[] for i in range (len(key),len(plain_text),len(key)):pre_pt_matrix+=[plain_text[marker:i]];marker=i pre_pt_matrix+=[plain_text[marker:]] pt_matrix = [] for i in range(len(pre_pt_matrix)):pt_matrix+=[['']*len(key)] # Set Matrix for key elements [KEY_MATRIX] for i in range (len(key_sorted)): key_matrix[i]=key_sorted.index(key[i].upper()) key_sorted[key_sorted.index(key[i].upper())]='' # Set Matrix for Text elements [TEXT_MATRIX] marker=0 for i in range (len(pt_matrix)): for j in range(len(pt_matrix[i])): if marker!=len(plain_text): pt_matrix[i][j]=plain_text[marker] marker+=1 # Set Plain_Text into proper matrix cipher_text='' for i in range (len(key_matrix)): for j in range (len(pt_matrix)): cipher_text+=pt_matrix[j][key_matrix.index(i)] # Generate matrix output if # show_matrix = 'SHOW' if show_matrix.upper()=='SHOW': matrix = [key]+[key_matrix]+pt_matrix Transportation_Cipher.print_table(matrix) return cipher_text def decoder(cipher_text, key, show_matrix='hide'): key_sorted = list(key.upper()) key_sorted.sort() key = list(key) key_matrix = [""]*len(key) # Set Cipher_Text MATRIX Layout marker=0 ct_matrix=[] for i in range (len(key),len(cipher_text),len(key)):ct_matrix+=[['\n']*len(cipher_text[marker:i])];marker=i ct_matrix+=[['\n']*len(cipher_text[marker:])] ct_matrix[-1]+=['']*(len(key)-len(cipher_text[marker:])) # Set Matrix for key elements [KEY_MATRIX] for i in range (len(key_sorted)): key_matrix[i]=key_sorted.index(key[i].upper()) key_sorted[key_sorted.index(key[i].upper())]='' # Set Matrix for Cipher Text elements [CipherText_MATRIX] marker=0 key_sorted = key_matrix for i in range(len(key_matrix)): for j in range(len(ct_matrix)): if marker!=len(cipher_text) and ct_matrix[j][key_matrix.index(i)]=='\n': ct_matrix[j][key_matrix.index(i)]=cipher_text[marker] marker+=1 # Set cipher text into proper matrix plain_text='' for i in range(len(ct_matrix)): for j in range(len(ct_matrix[i])): plain_text+=ct_matrix[i][j] # Generate matrix output if # show_matrix = 'SHOW' if show_matrix.upper()=='SHOW': matrix = [key]+[key_matrix]+ct_matrix Transportation_Cipher.print_table(matrix) return plain_text # -------------------------------- plain_text = 'Arijit Bhowmick :)' cipher_text = 'imjw) cABkio:tirh ' key = 'syS41x4' print(f"""Plain Text => {plain_text} Key => {key} Cipher Text => {Transportation_Cipher.encoder(plain_text, key, 'show')} {'*'*30}""") print(f"""Cipher Text => {cipher_text} Key => {key} Cipher Text => {Transportation_Cipher.decoder(cipher_text, key, 'show')}""")
25.058394
109
0.656277
5f958fe1376df57f90a624ab897905ad97db5f77
382
py
Python
Trakttv.bundle/Contents/Libraries/Shared/plugin/core/libraries/tests/cryptography_.py
disrupted/Trakttv.bundle
24712216c71f3b22fd58cb5dd89dad5bb798ed60
[ "RSA-MD" ]
1,346
2015-01-01T14:52:24.000Z
2022-03-28T12:50:48.000Z
Trakttv.bundle/Contents/Libraries/Shared/plugin/core/libraries/tests/cryptography_.py
alcroito/Plex-Trakt-Scrobbler
4f83fb0860dcb91f860d7c11bc7df568913c82a6
[ "RSA-MD" ]
474
2015-01-01T10:27:46.000Z
2022-03-21T12:26:16.000Z
Trakttv.bundle/Contents/Libraries/Shared/plugin/core/libraries/tests/cryptography_.py
alcroito/Plex-Trakt-Scrobbler
4f83fb0860dcb91f860d7c11bc7df568913c82a6
[ "RSA-MD" ]
191
2015-01-02T18:27:22.000Z
2022-03-29T10:49:48.000Z
from plugin.core.libraries.tests.core.base import BaseTest class Cryptography(BaseTest): name = 'cryptography' optional = True @staticmethod def test_import(): import cryptography.hazmat.bindings.openssl.binding return { 'versions': { 'cryptography': getattr(cryptography, '__version__', None) } }
22.470588
74
0.615183