hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | 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 245 | max_issues_repo_name stringlengths 6 130 | 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 245 | max_forks_repo_name stringlengths 6 130 | 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 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f73b7c904f290646d369fe3840c216cd9b34d97c | 5,606 | py | Python | tetris/ai/population.py | TomerHanochi/Tetris | 5be6c02b27164d0b3897006e5d1476b3e8546533 | [
"MIT"
] | null | null | null | tetris/ai/population.py | TomerHanochi/Tetris | 5be6c02b27164d0b3897006e5d1476b3e8546533 | [
"MIT"
] | null | null | null | tetris/ai/population.py | TomerHanochi/Tetris | 5be6c02b27164d0b3897006e5d1476b3e8546533 | [
"MIT"
] | null | null | null | from __future__ import annotations
from random import random
import numpy as np
from tetris.ai.network import Network
class Population:
def __init__(self, size: int = 500, old_pop: Population = None,
parent_candidates_pct: float = .1, offspring_pct: float = .3,
mutation_chance: float = .05, mutation_pwr: float = .2) -> None:
"""
Represents a list of networks that can evolve over time using a genetic algorithm.
The population starts with random networks, and each generation the fittest networks
are combined to produce child networks.
Afterwards the weakest networks are replaced by the children.
:param size: the size of the initial population.
:param old_pop: an old population on which we create a new population using the algorithm
described above.
:param parent_candidates_pct: the percent of the total number of networks that we use to
choose the number of parent candidates.
:param offspring_pct: the percent of the total number of networks that we use to choose
the number of offspring.
:param mutation_chance: the chance for a child to mutate.
:param mutation_pwr: the amount the child will mutate by, random number in the.
[-mutation_pwr, mutation_pwr] range.
"""
if old_pop is None:
self.__networks = [Network() for _ in range(size)]
self.__fitnesses = [0 for _ in range(size)]
else:
self.__networks = self.crossover(networks=old_pop.networks,
fitnesses=old_pop.fitnesses)
self.__fitnesses = [0 for _ in range(len(self.networks))]
self.offspring_pct = offspring_pct
self.parent_candidates_pct = parent_candidates_pct
self.mutation_chance = mutation_chance
self.mutation_pwr = mutation_pwr
def offspring(self, networks: list[Network], fitnesses: list[float]) -> list[Network]:
"""
Each iteration, we pick a random percent of the total networks. The two fittest networks
among them will become the parent networks.
We decide the weights for the child network as:
child_weights = weights1 * fitness1 + weights2 * fitness2
It then has a chance to mutate. Mutation causes a random part of the weights to increase by
a random number in the [-mutation_pwr, mutation_pwr] range.
It is then normalized, resulting in a weight vector that is between the two parents, but
closer to the fitter one.
:param networks: a list of networks to produce offspring from.
:param fitnesses: a list of fitnesses corresponding to the network.
:return: a list of child networks.
"""
num_of_offspring = int(len(networks) * self.offspring_pct)
num_of_parent_candidates = int(len(networks) * self.parent_candidates_pct)
offspring = list()
for _ in range(num_of_offspring):
# the indecies of the random parent candidates
parent_candidates_indices = np.random.choice(len(networks), num_of_parent_candidates,
replace=False)
# the parents and their corresponding fitnesses
parent_candidates = np.array([networks[index] for index in parent_candidates_indices])
parent_fitnesses = np.array([fitnesses[index] for index in parent_candidates_indices])
# the two fittest parents
parent_indices = np.argpartition(parent_fitnesses, -2)[-2:]
p1, p2 = parent_candidates[parent_indices]
f1, f2 = parent_fitnesses[parent_indices]
child = Network(weights=p1.weights * f1 + p2.weights * f2)
if random() < self.mutation_chance:
child.mutate(self.mutation_pwr)
offspring.append(child)
return offspring
def crossover(self, networks: list[Network], fitnesses: list[float]) -> list[Network]:
"""
The crossover is the replacement of weak networks with possibly stronger networks.
For each offspring we remove the weakest network, and replace it with the offspring.
:param networks: a list of networks to produce offspring from.
:param fitnesses: a list of fitnesses corresponding to the network.
:return: a list of networks with the same size as networks.
"""
offspring = self.offspring(networks, fitnesses)
num_of_offspring = len(offspring)
weakest_indices = np.argpartition(fitnesses, -num_of_offspring)[-num_of_offspring:]
new_networks = [
network for i, network in enumerate(networks) if i not in weakest_indices
]
new_networks.extend(offspring)
return new_networks
@property
def networks(self) -> list[Network]:
return self.__networks
@property
def fitnesses(self) -> list[float]:
return self.__fitnesses
@fitnesses.setter
def fitnesses(self, fitnesses: list[float]) -> None:
if isinstance(fitnesses, list):
if len(fitnesses) == len(self.fitnesses):
self.__fitnesses = fitnesses
else:
raise ValueError(f'Expected len {len(self.__fitnesses)}, got len {len(fitnesses)}')
else:
raise TypeError(f'Expected list, got {fitnesses.__class__.__name__}')
def __iter__(self) -> iter:
return iter(self.networks)
| 49.175439 | 99 | 0.644488 | from __future__ import annotations
from random import random
import numpy as np
from tetris.ai.network import Network
class Population:
def __init__(self, size: int = 500, old_pop: Population = None,
parent_candidates_pct: float = .1, offspring_pct: float = .3,
mutation_chance: float = .05, mutation_pwr: float = .2) -> None:
if old_pop is None:
self.__networks = [Network() for _ in range(size)]
self.__fitnesses = [0 for _ in range(size)]
else:
self.__networks = self.crossover(networks=old_pop.networks,
fitnesses=old_pop.fitnesses)
self.__fitnesses = [0 for _ in range(len(self.networks))]
self.offspring_pct = offspring_pct
self.parent_candidates_pct = parent_candidates_pct
self.mutation_chance = mutation_chance
self.mutation_pwr = mutation_pwr
def offspring(self, networks: list[Network], fitnesses: list[float]) -> list[Network]:
num_of_offspring = int(len(networks) * self.offspring_pct)
num_of_parent_candidates = int(len(networks) * self.parent_candidates_pct)
offspring = list()
for _ in range(num_of_offspring):
parent_candidates_indices = np.random.choice(len(networks), num_of_parent_candidates,
replace=False)
parent_candidates = np.array([networks[index] for index in parent_candidates_indices])
parent_fitnesses = np.array([fitnesses[index] for index in parent_candidates_indices])
parent_indices = np.argpartition(parent_fitnesses, -2)[-2:]
p1, p2 = parent_candidates[parent_indices]
f1, f2 = parent_fitnesses[parent_indices]
child = Network(weights=p1.weights * f1 + p2.weights * f2)
if random() < self.mutation_chance:
child.mutate(self.mutation_pwr)
offspring.append(child)
return offspring
def crossover(self, networks: list[Network], fitnesses: list[float]) -> list[Network]:
offspring = self.offspring(networks, fitnesses)
num_of_offspring = len(offspring)
weakest_indices = np.argpartition(fitnesses, -num_of_offspring)[-num_of_offspring:]
new_networks = [
network for i, network in enumerate(networks) if i not in weakest_indices
]
new_networks.extend(offspring)
return new_networks
@property
def networks(self) -> list[Network]:
return self.__networks
@property
def fitnesses(self) -> list[float]:
return self.__fitnesses
@fitnesses.setter
def fitnesses(self, fitnesses: list[float]) -> None:
if isinstance(fitnesses, list):
if len(fitnesses) == len(self.fitnesses):
self.__fitnesses = fitnesses
else:
raise ValueError(f'Expected len {len(self.__fitnesses)}, got len {len(fitnesses)}')
else:
raise TypeError(f'Expected list, got {fitnesses.__class__.__name__}')
def __iter__(self) -> iter:
return iter(self.networks)
| true | true |
f73b7ca19f8edaa9bba225fd779a3bdd7e08513f | 2,207 | py | Python | internal/notes/builtin-SAVE/packages/r-affyplm/package.py | HPCToolkit/hpctest | 5ff4455582bf39e75530a31badcf6142081b386b | [
"BSD-3-Clause"
] | 1 | 2019-01-17T20:07:19.000Z | 2019-01-17T20:07:19.000Z | internal/notes/builtin-SAVE/packages/r-affyplm/package.py | HPCToolkit/hpctest | 5ff4455582bf39e75530a31badcf6142081b386b | [
"BSD-3-Clause"
] | null | null | null | internal/notes/builtin-SAVE/packages/r-affyplm/package.py | HPCToolkit/hpctest | 5ff4455582bf39e75530a31badcf6142081b386b | [
"BSD-3-Clause"
] | 2 | 2019-08-06T18:13:57.000Z | 2021-11-05T18:19:49.000Z | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class RAffyplm(RPackage):
"""A package that extends and improves the functionality of
the base affy package. Routines that make heavy use of compiled
code for speed. Central focus is on implementation of methods
for fitting probe-level models and tools using these models.
PLM based quality assessment tools."""
homepage = "https://www.bioconductor.org/packages/affyPLM/"
url = "https://git.bioconductor.org/packages/affyPLM"
version('1.52.1', git='https://git.bioconductor.org/packages/affyPLM', commit='e8613a6018c4ee58045df6bf19128844f50a1f43')
depends_on('r@3.4.0:3.4.9', when='@1.52.1')
depends_on('r-biocgenerics', type=('build', 'run'))
depends_on('r-affy', type=('build', 'run'))
depends_on('r-biobase', type=('build', 'run'))
depends_on('r-gcrma', type=('build', 'run'))
depends_on('r-preprocesscore', type=('build', 'run'))
depends_on('r-zlibbioc', type=('build', 'run'))
| 46.957447 | 125 | 0.67739 | true | true | |
f73b7cb326a90d8c48085cb16779f4e82197e119 | 4,233 | py | Python | taxi_uploader.py | nicor88/data-sets-s3-uploader | 872f702ec0c366a25ef1b4e24f1d23ad435076bd | [
"MIT"
] | null | null | null | taxi_uploader.py | nicor88/data-sets-s3-uploader | 872f702ec0c366a25ef1b4e24f1d23ad435076bd | [
"MIT"
] | null | null | null | taxi_uploader.py | nicor88/data-sets-s3-uploader | 872f702ec0c366a25ef1b4e24f1d23ad435076bd | [
"MIT"
] | null | null | null | """
Script to upload the data set of New York Taxi trips in S3 data lake
Sources
http://www.nyc.gov/html/tlc/html/about/trip_record_data.shtml
https://github.com/toddwschneider/nyc-taxi-data/blob/master/setup_files/raw_data_urls.txt
Example
>>> sample_url = 'https://s3.amazonaws.com/nyc-tlc/trip+data/fhv_tripdata_2015-05.csv'
>>> destination_key = sample_url.split('/')[-1]
>>> save_to_s3(source_url=sample_url, s3_key=destination_key, s3_bucket='ef-sample-data')
"""
import argparse
import sys
import boto3
from dateutil import parser, relativedelta
import requests
s3 = boto3.resource('s3')
BASE_URL = 'https://s3.amazonaws.com/nyc-tlc/trip+data'
def save_to_s3(*, source_url, s3_key, s3_bucket):
destination_bucket_resource = s3.Bucket(s3_bucket)
global transfer_size_bytes
transfer_size_bytes = 0
file_size_bytes = int(requests.head(source_url).headers.get('Content-Length'))
file_size_megabytes = round(file_size_bytes / (1024 * 1024), 2)
def _print_transferred_bytes(bytes_transferred):
global transfer_size_bytes
transfer_size_bytes += bytes_transferred
transfer_percentage = round((transfer_size_bytes/file_size_bytes) * 100, 2)
sys.stdout.write('\033[F') # back to previous line
sys.stdout.write('\033[K') # clear line
print(f'Transferred {transfer_size_bytes} out of {file_size_bytes} bytes - {transfer_percentage}%')
def _upload_to_s3():
destination_obj = destination_bucket_resource.Object(s3_key)
with requests.get(source_url, stream=True) as response:
destination_obj.upload_fileobj(response.raw, Callback=_print_transferred_bytes)
transfer_size_megabytes = round(transfer_size_bytes / (1024 * 1024), 2)
print(f's3://{s3_bucket}/{s3_key} imported successfully, total size: {transfer_size_bytes} bytes, {transfer_size_megabytes} MB')
print(f'File size {source_url} is {file_size_bytes} bytes, {file_size_megabytes} MB')
# this string is going to be overridden
print(f'Starting the upload to s3://{s3_bucket}/{s3_key}')
_upload_to_s3()
def generate_months(start_month_str: str, end_month_str: str):
start_month = parser.parse(f'{start_month_str}-01')
end_month = parser.parse(f'{end_month_str}-01')
if start_month >= end_month:
raise Exception('Insert a start month bigger than the end month')
diff = relativedelta.relativedelta(start_month, end_month)
month_diff = abs(diff.months) + 1
for month in range(month_diff):
yield (start_month + relativedelta.relativedelta(months=month)).strftime('%Y-%m')
def get_hive_partition_key(source, data_set_type, year, month, s3_key):
return f'source={source}/data_set_type={data_set_type}/year={year}/month={month}/{s3_key}'
def get_data_set(data_set_types, start_month, end_month, destination_bucket_name):
for data_set in data_set_types:
for year_month in list(generate_months(start_month, end_month)):
filename = f'{data_set}_{year_month}.csv'
url = f'{BASE_URL}/{filename}'
year = year_month.split('-')[0]
month = year_month.split('-')[1]
hive_partition_key = get_hive_partition_key('new_york_taxi', data_set, year, month, filename)
save_to_s3(source_url=url, s3_bucket=destination_bucket_name, s3_key=hive_partition_key)
def create_argparser():
arg_parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter
)
arg_parser.add_argument('--start-month', required=True, help='Start month')
arg_parser.add_argument('--end-month', required=True, help='End month, included')
arg_parser.add_argument('--destination-bucket', required=True, help='AWS S3 destination bucket name')
return arg_parser
if __name__ == '__main__':
args = create_argparser().parse_args()
start_month_input = vars(args).get('start_month')
end_month_input = vars(args).get('end_month')
destination_bucket = vars(args).get('destination_bucket')
data_sets = ['fhv_tripdata', 'green_tripdata', 'yellow_tripdata']
get_data_set(data_sets, start_month_input, end_month_input, destination_bucket)
| 38.481818 | 140 | 0.725254 | import argparse
import sys
import boto3
from dateutil import parser, relativedelta
import requests
s3 = boto3.resource('s3')
BASE_URL = 'https://s3.amazonaws.com/nyc-tlc/trip+data'
def save_to_s3(*, source_url, s3_key, s3_bucket):
destination_bucket_resource = s3.Bucket(s3_bucket)
global transfer_size_bytes
transfer_size_bytes = 0
file_size_bytes = int(requests.head(source_url).headers.get('Content-Length'))
file_size_megabytes = round(file_size_bytes / (1024 * 1024), 2)
def _print_transferred_bytes(bytes_transferred):
global transfer_size_bytes
transfer_size_bytes += bytes_transferred
transfer_percentage = round((transfer_size_bytes/file_size_bytes) * 100, 2)
sys.stdout.write('\033[F')
sys.stdout.write('\033[K')
print(f'Transferred {transfer_size_bytes} out of {file_size_bytes} bytes - {transfer_percentage}%')
def _upload_to_s3():
destination_obj = destination_bucket_resource.Object(s3_key)
with requests.get(source_url, stream=True) as response:
destination_obj.upload_fileobj(response.raw, Callback=_print_transferred_bytes)
transfer_size_megabytes = round(transfer_size_bytes / (1024 * 1024), 2)
print(f's3://{s3_bucket}/{s3_key} imported successfully, total size: {transfer_size_bytes} bytes, {transfer_size_megabytes} MB')
print(f'File size {source_url} is {file_size_bytes} bytes, {file_size_megabytes} MB')
print(f'Starting the upload to s3://{s3_bucket}/{s3_key}')
_upload_to_s3()
def generate_months(start_month_str: str, end_month_str: str):
start_month = parser.parse(f'{start_month_str}-01')
end_month = parser.parse(f'{end_month_str}-01')
if start_month >= end_month:
raise Exception('Insert a start month bigger than the end month')
diff = relativedelta.relativedelta(start_month, end_month)
month_diff = abs(diff.months) + 1
for month in range(month_diff):
yield (start_month + relativedelta.relativedelta(months=month)).strftime('%Y-%m')
def get_hive_partition_key(source, data_set_type, year, month, s3_key):
return f'source={source}/data_set_type={data_set_type}/year={year}/month={month}/{s3_key}'
def get_data_set(data_set_types, start_month, end_month, destination_bucket_name):
for data_set in data_set_types:
for year_month in list(generate_months(start_month, end_month)):
filename = f'{data_set}_{year_month}.csv'
url = f'{BASE_URL}/{filename}'
year = year_month.split('-')[0]
month = year_month.split('-')[1]
hive_partition_key = get_hive_partition_key('new_york_taxi', data_set, year, month, filename)
save_to_s3(source_url=url, s3_bucket=destination_bucket_name, s3_key=hive_partition_key)
def create_argparser():
arg_parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter
)
arg_parser.add_argument('--start-month', required=True, help='Start month')
arg_parser.add_argument('--end-month', required=True, help='End month, included')
arg_parser.add_argument('--destination-bucket', required=True, help='AWS S3 destination bucket name')
return arg_parser
if __name__ == '__main__':
args = create_argparser().parse_args()
start_month_input = vars(args).get('start_month')
end_month_input = vars(args).get('end_month')
destination_bucket = vars(args).get('destination_bucket')
data_sets = ['fhv_tripdata', 'green_tripdata', 'yellow_tripdata']
get_data_set(data_sets, start_month_input, end_month_input, destination_bucket)
| true | true |
f73b7ebdcce8413f0b05b38edc2d5c459acd40a6 | 2,180 | py | Python | modules/test/npcore/layers/test_layer.py | tuantle/simple_nn_with_numpy | 4bf5ba23e2df7879030de85eb22b8e30ad9708de | [
"MIT"
] | 1 | 2019-01-31T20:24:34.000Z | 2019-01-31T20:24:34.000Z | modules/test/npcore/layers/test_layer.py | tuantle/simple_nn_with_numpy | 4bf5ba23e2df7879030de85eb22b8e30ad9708de | [
"MIT"
] | null | null | null | modules/test/npcore/layers/test_layer.py | tuantle/simple_nn_with_numpy | 4bf5ba23e2df7879030de85eb22b8e30ad9708de | [
"MIT"
] | null | null | null | #!/usr/bin/env python
#
# Copyright 2016-present Tuan Le.
#
# Licensed under the MIT License.
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://opensource.org/licenses/mit-license.html
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------
#
# Author Tuan Le (tuan.t.lei@gmail.com)
#
# ------------------------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import env
import unittest
from npcore.layer.layer import Layer
# ------------------------------------------------------------------------
class TestCoreLayerClass(unittest.TestCase):
def test_init(self):
print('Testing Core Layer.')
shape = (1, 2)
layer0 = Layer(shape=shape, name='l0')
layer1 = Layer(shape=shape, name='l1n')
layer2 = Layer(shape=shape, name='l2n')
layer3 = Layer(shape=shape, name='l3')
layer4 = Layer(shape=shape, name='l4')
layer5 = Layer(shape=shape, name='l5')
layerx = Layer(shape=shape, name='lx')
layery = Layer(shape=shape, name='ly')
layerz = Layer(shape=shape, name='lz')
layer0.connect(layer1).connect(layer2).connect(layer3).connect(layer4).connect(layer5)
layer0.from_index(2).connect(layerx, position='behind')
layer0.from_index(5).connect(layery, position='ahead')
layer0.from_index(4).disconnect()
layer0.from_index(1).replace_with(layerz)
layer = layer0.head
print(layerz.head.name)
while layer is not None:
print(layer.snapshot())
layer = layer.next
# ------------------------------------------------------------------------
if __name__ == '__main__':
unittest.main()
| 32.537313 | 94 | 0.588532 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import env
import unittest
from npcore.layer.layer import Layer
class TestCoreLayerClass(unittest.TestCase):
def test_init(self):
print('Testing Core Layer.')
shape = (1, 2)
layer0 = Layer(shape=shape, name='l0')
layer1 = Layer(shape=shape, name='l1n')
layer2 = Layer(shape=shape, name='l2n')
layer3 = Layer(shape=shape, name='l3')
layer4 = Layer(shape=shape, name='l4')
layer5 = Layer(shape=shape, name='l5')
layerx = Layer(shape=shape, name='lx')
layery = Layer(shape=shape, name='ly')
layerz = Layer(shape=shape, name='lz')
layer0.connect(layer1).connect(layer2).connect(layer3).connect(layer4).connect(layer5)
layer0.from_index(2).connect(layerx, position='behind')
layer0.from_index(5).connect(layery, position='ahead')
layer0.from_index(4).disconnect()
layer0.from_index(1).replace_with(layerz)
layer = layer0.head
print(layerz.head.name)
while layer is not None:
print(layer.snapshot())
layer = layer.next
if __name__ == '__main__':
unittest.main()
| true | true |
f73b7fb2430cdbeb17654b7f2b0f9f0760596f0e | 282 | py | Python | mesa_behaviors/history/base_history.py | tokesim/mesa_behaviors | 3f34c1227799b37880b123b0953d9311c32a5fd3 | [
"Apache-2.0"
] | 1 | 2021-08-19T23:44:52.000Z | 2021-08-19T23:44:52.000Z | mesa_behaviors/history/base_history.py | tokesim/mesa_behaviors | 3f34c1227799b37880b123b0953d9311c32a5fd3 | [
"Apache-2.0"
] | 5 | 2020-04-15T05:24:31.000Z | 2020-04-23T03:44:08.000Z | mesa_behaviors/history/base_history.py | tokesim/mesa_behaviors | 3f34c1227799b37880b123b0953d9311c32a5fd3 | [
"Apache-2.0"
] | 2 | 2020-04-14T02:21:55.000Z | 2020-09-16T03:22:22.000Z | from abc import ABC, abstractmethod
from typing import Generic, TypeVar
H = TypeVar("H")
T = TypeVar("T")
class BaseHistory(Generic[H, T], ABC):
@abstractmethod
def add(self, entry: T) -> None:
pass
@abstractmethod
def retrieve(self) -> H:
pass
| 16.588235 | 38 | 0.631206 | from abc import ABC, abstractmethod
from typing import Generic, TypeVar
H = TypeVar("H")
T = TypeVar("T")
class BaseHistory(Generic[H, T], ABC):
@abstractmethod
def add(self, entry: T) -> None:
pass
@abstractmethod
def retrieve(self) -> H:
pass
| true | true |
f73b80548356187472913852e6bad7c3fe661f47 | 6,598 | py | Python | train_script.py | zhlinup/Relay-FL | 3a64d75108295412ed438f95ef2cf0da6c87bdbd | [
"MIT"
] | null | null | null | train_script.py | zhlinup/Relay-FL | 3a64d75108295412ed438f95ef2cf0da6c87bdbd | [
"MIT"
] | null | null | null | train_script.py | zhlinup/Relay-FL | 3a64d75108295412ed438f95ef2cf0da6c87bdbd | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import numpy as np
np.set_printoptions(precision=6, threshold=1e3)
import torch
from torchvision import datasets, transforms
import copy
import torch.nn as nn
from torch.utils.data import DataLoader
def mnist_iid(dataset, K, M):
dict_users, all_idxs = {}, [i for i in range(len(dataset))]
for i in range(M):
dict_users[i] = set(np.random.choice(all_idxs, int(K[i]), replace=False))
all_idxs = list(set(all_idxs) - dict_users[i])
return dict_users
def load_fmnist_iid(K):
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
dataset_train = datasets.FashionMNIST('./data/FASHION_MNIST/', download=True, train=True, transform=transform)
dataset_test = datasets.FashionMNIST('./data/FASHION_MNIST/', download=True, train=False, transform=transform)
loader = DataLoader(dataset_train, batch_size=len(dataset_train), shuffle=False)
images, labels = next(enumerate(loader))[1]
images, labels = images.numpy(), labels.numpy()
D_k = int(len(labels) / K)
train_images = []
train_labels = []
dict_users = {i: np.array([], dtype='int64') for i in range(K)}
all_idxs = np.arange(len(labels))
D = np.zeros(K)
for i in range(K):
dict_users[i] = set(np.random.choice(all_idxs, int(D_k), replace=False))
all_idxs = list(set(all_idxs) - dict_users[i])
train_images.append(images[list(dict_users[i])])
train_labels.append(labels[list(dict_users[i])])
D[i] = len(dict_users[i])
test_loader = DataLoader(dataset_test, batch_size=len(dataset_test), shuffle=True)
test_images, test_labels = next(enumerate(test_loader))[1]
return train_images, train_labels, test_images.numpy(), test_labels.numpy(), D
def load_fmnist_noniid(K, NUM_SHARDS):
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
dataset_train = datasets.FashionMNIST('./data/FASHION_MNIST/', download=True, train=True, transform=transform)
dataset_test = datasets.FashionMNIST('./data/FASHION_MNIST/', download=True, train=False, transform=transform)
loader = DataLoader(dataset_train, batch_size=len(dataset_train), shuffle=False)
images, labels = next(enumerate(loader))[1]
images, labels = images.numpy(), labels.numpy()
train_images = []
train_labels = []
# PART = 10
PART = 1
num_shards = K * NUM_SHARDS * PART
num_imgs = int(len(images) / num_shards)
idx_shard = [i for i in range(num_shards)]
dict_users = {i: np.array([], dtype='int64') for i in range(K)}
all_idxs = np.arange(len(labels))
# sort labels
idxs_labels = np.vstack((all_idxs, labels))
idxs_labels = idxs_labels[:, idxs_labels[1, :].argsort()]
all_idxs = idxs_labels[0, :]
idx_shard = idx_shard[::PART]
D = np.zeros(K)
for i in range(K):
rand_set = set(np.random.choice(idx_shard, NUM_SHARDS, replace=False))
idx_shard = list(set(idx_shard) - rand_set)
for rand in rand_set:
dict_users[i] = np.concatenate((dict_users[i], all_idxs[rand * num_imgs:(rand + 1) * num_imgs]), axis=0)
train_images.append(images[dict_users[i]])
train_labels.append(labels[dict_users[i]])
D[i] = len(dict_users[i])
test_loader = DataLoader(dataset_test, batch_size=len(dataset_test), shuffle=True)
test_images, test_labels = next(enumerate(test_loader))[1]
return train_images, train_labels, test_images.numpy(), test_labels.numpy(), D
def local_update(setup, d, model1, train_images, train_labels, idx, batch_size):
initital_weight = copy.deepcopy(model1.state_dict())
model = copy.deepcopy(model1)
model.train()
loss_function = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=setup.lr, momentum=setup.momentum)
# optimizer = torch.optim.Adam(model.parameters(), lr=setup.lr)
epoch_loss = []
images = np.array_split(train_images[idx], len(train_images[idx]) // batch_size)
labels = np.array_split(train_labels[idx], len(train_labels[idx]) // batch_size)
for epoch in range(setup.local_ep):
batch_loss = []
for b_idx in range(len(images)):
model.zero_grad()
log_probs = model(torch.tensor(images[b_idx].copy(), device=setup.device))
local_loss = loss_function(log_probs, torch.tensor(labels[b_idx].copy(), device=setup.device))
local_loss.backward()
optimizer.step()
if setup.verbose == 2:
print('User: {}, Epoch: {}, Batch No: {}/{} Loss: {:.6f}'.format(idx,
epoch, b_idx + 1, len(images),
local_loss.item()))
batch_loss.append(local_loss.item())
epoch_loss.append(sum(batch_loss) / len(batch_loss))
copyw = copy.deepcopy(model.state_dict())
gradient2 = np.array([[]])
w2 = np.array([[]])
for item in copyw.keys():
gradient2 = np.hstack((gradient2, np.reshape((initital_weight[item] - copyw[item]).cpu().numpy(),
[1, -1]) / setup.lr))
w2 = np.hstack((w2, np.reshape((copyw[item] - initital_weight[item]).cpu().numpy(),
[1, -1])))
return w2, sum(epoch_loss) / len(epoch_loss), gradient2
def test_model(model, setup, test_images, test_labels):
model.eval()
loss, total, correct = 0.0, 0.0, 0.0
images = torch.tensor(test_images).to(setup.device)
labels = torch.tensor(test_labels).to(setup.device)
outputs = model(images).to(setup.device)
loss_function = nn.CrossEntropyLoss()
batch_loss = loss_function(outputs, labels)
loss += batch_loss.item()
_, pred_labels = torch.max(outputs, 1)
pred_labels = pred_labels.view(-1)
correct += torch.sum(torch.eq(pred_labels, labels)).item()
total += len(labels)
accuracy = correct / total
if setup.verbose:
print('Average loss: {:.4f} \nAccuracy: {}/{} ({:.2f}%)\n'.format(
loss, int(correct), int(total), 100.0 * accuracy))
return accuracy, loss
| 39.508982 | 117 | 0.608518 |
import numpy as np
np.set_printoptions(precision=6, threshold=1e3)
import torch
from torchvision import datasets, transforms
import copy
import torch.nn as nn
from torch.utils.data import DataLoader
def mnist_iid(dataset, K, M):
dict_users, all_idxs = {}, [i for i in range(len(dataset))]
for i in range(M):
dict_users[i] = set(np.random.choice(all_idxs, int(K[i]), replace=False))
all_idxs = list(set(all_idxs) - dict_users[i])
return dict_users
def load_fmnist_iid(K):
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
dataset_train = datasets.FashionMNIST('./data/FASHION_MNIST/', download=True, train=True, transform=transform)
dataset_test = datasets.FashionMNIST('./data/FASHION_MNIST/', download=True, train=False, transform=transform)
loader = DataLoader(dataset_train, batch_size=len(dataset_train), shuffle=False)
images, labels = next(enumerate(loader))[1]
images, labels = images.numpy(), labels.numpy()
D_k = int(len(labels) / K)
train_images = []
train_labels = []
dict_users = {i: np.array([], dtype='int64') for i in range(K)}
all_idxs = np.arange(len(labels))
D = np.zeros(K)
for i in range(K):
dict_users[i] = set(np.random.choice(all_idxs, int(D_k), replace=False))
all_idxs = list(set(all_idxs) - dict_users[i])
train_images.append(images[list(dict_users[i])])
train_labels.append(labels[list(dict_users[i])])
D[i] = len(dict_users[i])
test_loader = DataLoader(dataset_test, batch_size=len(dataset_test), shuffle=True)
test_images, test_labels = next(enumerate(test_loader))[1]
return train_images, train_labels, test_images.numpy(), test_labels.numpy(), D
def load_fmnist_noniid(K, NUM_SHARDS):
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
dataset_train = datasets.FashionMNIST('./data/FASHION_MNIST/', download=True, train=True, transform=transform)
dataset_test = datasets.FashionMNIST('./data/FASHION_MNIST/', download=True, train=False, transform=transform)
loader = DataLoader(dataset_train, batch_size=len(dataset_train), shuffle=False)
images, labels = next(enumerate(loader))[1]
images, labels = images.numpy(), labels.numpy()
train_images = []
train_labels = []
PART = 1
num_shards = K * NUM_SHARDS * PART
num_imgs = int(len(images) / num_shards)
idx_shard = [i for i in range(num_shards)]
dict_users = {i: np.array([], dtype='int64') for i in range(K)}
all_idxs = np.arange(len(labels))
idxs_labels = np.vstack((all_idxs, labels))
idxs_labels = idxs_labels[:, idxs_labels[1, :].argsort()]
all_idxs = idxs_labels[0, :]
idx_shard = idx_shard[::PART]
D = np.zeros(K)
for i in range(K):
rand_set = set(np.random.choice(idx_shard, NUM_SHARDS, replace=False))
idx_shard = list(set(idx_shard) - rand_set)
for rand in rand_set:
dict_users[i] = np.concatenate((dict_users[i], all_idxs[rand * num_imgs:(rand + 1) * num_imgs]), axis=0)
train_images.append(images[dict_users[i]])
train_labels.append(labels[dict_users[i]])
D[i] = len(dict_users[i])
test_loader = DataLoader(dataset_test, batch_size=len(dataset_test), shuffle=True)
test_images, test_labels = next(enumerate(test_loader))[1]
return train_images, train_labels, test_images.numpy(), test_labels.numpy(), D
def local_update(setup, d, model1, train_images, train_labels, idx, batch_size):
initital_weight = copy.deepcopy(model1.state_dict())
model = copy.deepcopy(model1)
model.train()
loss_function = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=setup.lr, momentum=setup.momentum)
epoch_loss = []
images = np.array_split(train_images[idx], len(train_images[idx]) // batch_size)
labels = np.array_split(train_labels[idx], len(train_labels[idx]) // batch_size)
for epoch in range(setup.local_ep):
batch_loss = []
for b_idx in range(len(images)):
model.zero_grad()
log_probs = model(torch.tensor(images[b_idx].copy(), device=setup.device))
local_loss = loss_function(log_probs, torch.tensor(labels[b_idx].copy(), device=setup.device))
local_loss.backward()
optimizer.step()
if setup.verbose == 2:
print('User: {}, Epoch: {}, Batch No: {}/{} Loss: {:.6f}'.format(idx,
epoch, b_idx + 1, len(images),
local_loss.item()))
batch_loss.append(local_loss.item())
epoch_loss.append(sum(batch_loss) / len(batch_loss))
copyw = copy.deepcopy(model.state_dict())
gradient2 = np.array([[]])
w2 = np.array([[]])
for item in copyw.keys():
gradient2 = np.hstack((gradient2, np.reshape((initital_weight[item] - copyw[item]).cpu().numpy(),
[1, -1]) / setup.lr))
w2 = np.hstack((w2, np.reshape((copyw[item] - initital_weight[item]).cpu().numpy(),
[1, -1])))
return w2, sum(epoch_loss) / len(epoch_loss), gradient2
def test_model(model, setup, test_images, test_labels):
model.eval()
loss, total, correct = 0.0, 0.0, 0.0
images = torch.tensor(test_images).to(setup.device)
labels = torch.tensor(test_labels).to(setup.device)
outputs = model(images).to(setup.device)
loss_function = nn.CrossEntropyLoss()
batch_loss = loss_function(outputs, labels)
loss += batch_loss.item()
_, pred_labels = torch.max(outputs, 1)
pred_labels = pred_labels.view(-1)
correct += torch.sum(torch.eq(pred_labels, labels)).item()
total += len(labels)
accuracy = correct / total
if setup.verbose:
print('Average loss: {:.4f} \nAccuracy: {}/{} ({:.2f}%)\n'.format(
loss, int(correct), int(total), 100.0 * accuracy))
return accuracy, loss
| true | true |
f73b8059a63758aeac0948d27b41ba7599e9741e | 17,308 | py | Python | allennlp/data/dataset_readers/dataset_utils/span_utils.py | MSLars/allennlp | 2cdb8742c8c8c3c38ace4bdfadbdc750a1aa2475 | [
"Apache-2.0"
] | 11,433 | 2017-06-27T03:08:46.000Z | 2022-03-31T18:14:33.000Z | allennlp/data/dataset_readers/dataset_utils/span_utils.py | MSLars/allennlp | 2cdb8742c8c8c3c38ace4bdfadbdc750a1aa2475 | [
"Apache-2.0"
] | 4,006 | 2017-06-26T21:45:43.000Z | 2022-03-31T02:11:10.000Z | allennlp/data/dataset_readers/dataset_utils/span_utils.py | MSLars/allennlp | 2cdb8742c8c8c3c38ace4bdfadbdc750a1aa2475 | [
"Apache-2.0"
] | 2,560 | 2017-06-26T21:16:53.000Z | 2022-03-30T07:55:46.000Z | from typing import Callable, List, Set, Tuple, TypeVar, Optional
import warnings
from allennlp.common.checks import ConfigurationError
from allennlp.data.tokenizers import Token
TypedSpan = Tuple[int, Tuple[int, int]]
TypedStringSpan = Tuple[str, Tuple[int, int]]
class InvalidTagSequence(Exception):
def __init__(self, tag_sequence=None):
super().__init__()
self.tag_sequence = tag_sequence
def __str__(self):
return " ".join(self.tag_sequence)
T = TypeVar("T", str, Token)
def enumerate_spans(
sentence: List[T],
offset: int = 0,
max_span_width: int = None,
min_span_width: int = 1,
filter_function: Callable[[List[T]], bool] = None,
) -> List[Tuple[int, int]]:
"""
Given a sentence, return all token spans within the sentence. Spans are `inclusive`.
Additionally, you can provide a maximum and minimum span width, which will be used
to exclude spans outside of this range.
Finally, you can provide a function mapping `List[T] -> bool`, which will
be applied to every span to decide whether that span should be included. This
allows filtering by length, regex matches, pos tags or any Spacy `Token`
attributes, for example.
# Parameters
sentence : `List[T]`, required.
The sentence to generate spans for. The type is generic, as this function
can be used with strings, or Spacy `Tokens` or other sequences.
offset : `int`, optional (default = `0`)
A numeric offset to add to all span start and end indices. This is helpful
if the sentence is part of a larger structure, such as a document, which
the indices need to respect.
max_span_width : `int`, optional (default = `None`)
The maximum length of spans which should be included. Defaults to len(sentence).
min_span_width : `int`, optional (default = `1`)
The minimum length of spans which should be included. Defaults to 1.
filter_function : `Callable[[List[T]], bool]`, optional (default = `None`)
A function mapping sequences of the passed type T to a boolean value.
If `True`, the span is included in the returned spans from the
sentence, otherwise it is excluded..
"""
max_span_width = max_span_width or len(sentence)
filter_function = filter_function or (lambda x: True)
spans: List[Tuple[int, int]] = []
for start_index in range(len(sentence)):
last_end_index = min(start_index + max_span_width, len(sentence))
first_end_index = min(start_index + min_span_width - 1, len(sentence))
for end_index in range(first_end_index, last_end_index):
start = offset + start_index
end = offset + end_index
# add 1 to end index because span indices are inclusive.
if filter_function(sentence[slice(start_index, end_index + 1)]):
spans.append((start, end))
return spans
def bio_tags_to_spans(
tag_sequence: List[str], classes_to_ignore: List[str] = None
) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to BIO tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also included (i.e those which do not start with a "B-LABEL"),
as otherwise it is possible to get a perfect precision score whilst still predicting
ill-formed spans in addition to the correct spans. This function works properly when
the spans are unlabeled (i.e., your labels are simply "B", "I", and "O").
# Parameters
tag_sequence : `List[str]`, required.
The integer class labels for a sequence.
classes_to_ignore : `List[str]`, optional (default = `None`).
A list of string class labels `excluding` the bio tag
which should be ignored when extracting spans.
# Returns
spans : `List[TypedStringSpan]`
The typed, extracted spans from the sequence, in the format (label, (span_start, span_end)).
Note that the label `does not` contain any BIO tag prefixes.
"""
classes_to_ignore = classes_to_ignore or []
spans: Set[Tuple[str, Tuple[int, int]]] = set()
span_start = 0
span_end = 0
active_conll_tag = None
for index, string_tag in enumerate(tag_sequence):
# Actual BIO tag.
bio_tag = string_tag[0]
if bio_tag not in ["B", "I", "O"]:
raise InvalidTagSequence(tag_sequence)
conll_tag = string_tag[2:]
if bio_tag == "O" or conll_tag in classes_to_ignore:
# The span has ended.
if active_conll_tag is not None:
spans.add((active_conll_tag, (span_start, span_end)))
active_conll_tag = None
# We don't care about tags we are
# told to ignore, so we do nothing.
continue
elif bio_tag == "B":
# We are entering a new span; reset indices
# and active tag to new span.
if active_conll_tag is not None:
spans.add((active_conll_tag, (span_start, span_end)))
active_conll_tag = conll_tag
span_start = index
span_end = index
elif bio_tag == "I" and conll_tag == active_conll_tag:
# We're inside a span.
span_end += 1
else:
# This is the case the bio label is an "I", but either:
# 1) the span hasn't started - i.e. an ill formed span.
# 2) The span is an I tag for a different conll annotation.
# We'll process the previous span if it exists, but also
# include this span. This is important, because otherwise,
# a model may get a perfect F1 score whilst still including
# false positive ill-formed spans.
if active_conll_tag is not None:
spans.add((active_conll_tag, (span_start, span_end)))
active_conll_tag = conll_tag
span_start = index
span_end = index
# Last token might have been a part of a valid span.
if active_conll_tag is not None:
spans.add((active_conll_tag, (span_start, span_end)))
return list(spans)
def iob1_tags_to_spans(
tag_sequence: List[str], classes_to_ignore: List[str] = None
) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to IOB1 tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also included (i.e., those where "B-LABEL" is not preceded
by "I-LABEL" or "B-LABEL").
# Parameters
tag_sequence : `List[str]`, required.
The integer class labels for a sequence.
classes_to_ignore : `List[str]`, optional (default = `None`).
A list of string class labels `excluding` the bio tag
which should be ignored when extracting spans.
# Returns
spans : `List[TypedStringSpan]`
The typed, extracted spans from the sequence, in the format (label, (span_start, span_end)).
Note that the label `does not` contain any BIO tag prefixes.
"""
classes_to_ignore = classes_to_ignore or []
spans: Set[Tuple[str, Tuple[int, int]]] = set()
span_start = 0
span_end = 0
active_conll_tag = None
prev_bio_tag = None
prev_conll_tag = None
for index, string_tag in enumerate(tag_sequence):
curr_bio_tag = string_tag[0]
curr_conll_tag = string_tag[2:]
if curr_bio_tag not in ["B", "I", "O"]:
raise InvalidTagSequence(tag_sequence)
if curr_bio_tag == "O" or curr_conll_tag in classes_to_ignore:
# The span has ended.
if active_conll_tag is not None:
spans.add((active_conll_tag, (span_start, span_end)))
active_conll_tag = None
elif _iob1_start_of_chunk(prev_bio_tag, prev_conll_tag, curr_bio_tag, curr_conll_tag):
# We are entering a new span; reset indices
# and active tag to new span.
if active_conll_tag is not None:
spans.add((active_conll_tag, (span_start, span_end)))
active_conll_tag = curr_conll_tag
span_start = index
span_end = index
else:
# bio_tag == "I" and curr_conll_tag == active_conll_tag
# We're continuing a span.
span_end += 1
prev_bio_tag = string_tag[0]
prev_conll_tag = string_tag[2:]
# Last token might have been a part of a valid span.
if active_conll_tag is not None:
spans.add((active_conll_tag, (span_start, span_end)))
return list(spans)
def _iob1_start_of_chunk(
prev_bio_tag: Optional[str],
prev_conll_tag: Optional[str],
curr_bio_tag: str,
curr_conll_tag: str,
) -> bool:
if curr_bio_tag == "B":
return True
if curr_bio_tag == "I" and prev_bio_tag == "O":
return True
if curr_bio_tag != "O" and prev_conll_tag != curr_conll_tag:
return True
return False
def bioul_tags_to_spans(
tag_sequence: List[str], classes_to_ignore: List[str] = None
) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to BIOUL tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are not allowed and will raise `InvalidTagSequence`.
This function works properly when the spans are unlabeled (i.e., your labels are
simply "B", "I", "O", "U", and "L").
# Parameters
tag_sequence : `List[str]`, required.
The tag sequence encoded in BIOUL, e.g. ["B-PER", "L-PER", "O"].
classes_to_ignore : `List[str]`, optional (default = `None`).
A list of string class labels `excluding` the bio tag
which should be ignored when extracting spans.
# Returns
spans : `List[TypedStringSpan]`
The typed, extracted spans from the sequence, in the format (label, (span_start, span_end)).
"""
spans = []
classes_to_ignore = classes_to_ignore or []
index = 0
while index < len(tag_sequence):
label = tag_sequence[index]
if label[0] == "U":
spans.append((label.partition("-")[2], (index, index)))
elif label[0] == "B":
start = index
while label[0] != "L":
index += 1
if index >= len(tag_sequence):
raise InvalidTagSequence(tag_sequence)
label = tag_sequence[index]
if not (label[0] == "I" or label[0] == "L"):
raise InvalidTagSequence(tag_sequence)
spans.append((label.partition("-")[2], (start, index)))
else:
if label != "O":
raise InvalidTagSequence(tag_sequence)
index += 1
return [span for span in spans if span[0] not in classes_to_ignore]
def iob1_to_bioul(tag_sequence: List[str]) -> List[str]:
warnings.warn(
"iob1_to_bioul has been replaced with 'to_bioul' to allow more encoding options.",
FutureWarning,
)
return to_bioul(tag_sequence)
def to_bioul(tag_sequence: List[str], encoding: str = "IOB1") -> List[str]:
"""
Given a tag sequence encoded with IOB1 labels, recode to BIOUL.
In the IOB1 scheme, I is a token inside a span, O is a token outside
a span and B is the beginning of span immediately following another
span of the same type.
In the BIO scheme, I is a token inside a span, O is a token outside
a span and B is the beginning of a span.
# Parameters
tag_sequence : `List[str]`, required.
The tag sequence encoded in IOB1, e.g. ["I-PER", "I-PER", "O"].
encoding : `str`, optional, (default = `"IOB1"`).
The encoding type to convert from. Must be either "IOB1" or "BIO".
# Returns
bioul_sequence : `List[str]`
The tag sequence encoded in IOB1, e.g. ["B-PER", "L-PER", "O"].
"""
if encoding not in {"IOB1", "BIO"}:
raise ConfigurationError(f"Invalid encoding {encoding} passed to 'to_bioul'.")
def replace_label(full_label, new_label):
# example: full_label = 'I-PER', new_label = 'U', returns 'U-PER'
parts = list(full_label.partition("-"))
parts[0] = new_label
return "".join(parts)
def pop_replace_append(in_stack, out_stack, new_label):
# pop the last element from in_stack, replace the label, append
# to out_stack
tag = in_stack.pop()
new_tag = replace_label(tag, new_label)
out_stack.append(new_tag)
def process_stack(stack, out_stack):
# process a stack of labels, add them to out_stack
if len(stack) == 1:
# just a U token
pop_replace_append(stack, out_stack, "U")
else:
# need to code as BIL
recoded_stack = []
pop_replace_append(stack, recoded_stack, "L")
while len(stack) >= 2:
pop_replace_append(stack, recoded_stack, "I")
pop_replace_append(stack, recoded_stack, "B")
recoded_stack.reverse()
out_stack.extend(recoded_stack)
# Process the tag_sequence one tag at a time, adding spans to a stack,
# then recode them.
bioul_sequence = []
stack: List[str] = []
for label in tag_sequence:
# need to make a dict like
# token = {'token': 'Matt', "labels": {'conll2003': "B-PER"}
# 'gold': 'I-PER'}
# where 'gold' is the raw value from the CoNLL data set
if label == "O" and len(stack) == 0:
bioul_sequence.append(label)
elif label == "O" and len(stack) > 0:
# need to process the entries on the stack plus this one
process_stack(stack, bioul_sequence)
bioul_sequence.append(label)
elif label[0] == "I":
# check if the previous type is the same as this one
# if it is then append to stack
# otherwise this start a new entity if the type
# is different
if len(stack) == 0:
if encoding == "BIO":
raise InvalidTagSequence(tag_sequence)
stack.append(label)
else:
# check if the previous type is the same as this one
this_type = label.partition("-")[2]
prev_type = stack[-1].partition("-")[2]
if this_type == prev_type:
stack.append(label)
else:
if encoding == "BIO":
raise InvalidTagSequence(tag_sequence)
# a new entity
process_stack(stack, bioul_sequence)
stack.append(label)
elif label[0] == "B":
if len(stack) > 0:
process_stack(stack, bioul_sequence)
stack.append(label)
else:
raise InvalidTagSequence(tag_sequence)
# process the stack
if len(stack) > 0:
process_stack(stack, bioul_sequence)
return bioul_sequence
def bmes_tags_to_spans(
tag_sequence: List[str], classes_to_ignore: List[str] = None
) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to BMES tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also included (i.e those which do not start with a "B-LABEL"),
as otherwise it is possible to get a perfect precision score whilst still predicting
ill-formed spans in addition to the correct spans.
This function works properly when the spans are unlabeled (i.e., your labels are
simply "B", "M", "E" and "S").
# Parameters
tag_sequence : `List[str]`, required.
The integer class labels for a sequence.
classes_to_ignore : `List[str]`, optional (default = `None`).
A list of string class labels `excluding` the bio tag
which should be ignored when extracting spans.
# Returns
spans : `List[TypedStringSpan]`
The typed, extracted spans from the sequence, in the format (label, (span_start, span_end)).
Note that the label `does not` contain any BIO tag prefixes.
"""
def extract_bmes_tag_label(text):
bmes_tag = text[0]
label = text[2:]
return bmes_tag, label
spans: List[Tuple[str, List[int]]] = []
prev_bmes_tag: Optional[str] = None
for index, tag in enumerate(tag_sequence):
bmes_tag, label = extract_bmes_tag_label(tag)
if bmes_tag in ("B", "S"):
# Regardless of tag, we start a new span when reaching B & S.
spans.append((label, [index, index]))
elif bmes_tag in ("M", "E") and prev_bmes_tag in ("B", "M") and spans[-1][0] == label:
# Only expand the span if
# 1. Valid transition: B/M -> M/E.
# 2. Matched label.
spans[-1][1][1] = index
else:
# Best effort split for invalid span.
spans.append((label, [index, index]))
# update previous BMES tag.
prev_bmes_tag = bmes_tag
classes_to_ignore = classes_to_ignore or []
return [
# to tuple.
(span[0], (span[1][0], span[1][1]))
for span in spans
if span[0] not in classes_to_ignore
]
| 38.981982 | 100 | 0.620349 | from typing import Callable, List, Set, Tuple, TypeVar, Optional
import warnings
from allennlp.common.checks import ConfigurationError
from allennlp.data.tokenizers import Token
TypedSpan = Tuple[int, Tuple[int, int]]
TypedStringSpan = Tuple[str, Tuple[int, int]]
class InvalidTagSequence(Exception):
def __init__(self, tag_sequence=None):
super().__init__()
self.tag_sequence = tag_sequence
def __str__(self):
return " ".join(self.tag_sequence)
T = TypeVar("T", str, Token)
def enumerate_spans(
sentence: List[T],
offset: int = 0,
max_span_width: int = None,
min_span_width: int = 1,
filter_function: Callable[[List[T]], bool] = None,
) -> List[Tuple[int, int]]:
max_span_width = max_span_width or len(sentence)
filter_function = filter_function or (lambda x: True)
spans: List[Tuple[int, int]] = []
for start_index in range(len(sentence)):
last_end_index = min(start_index + max_span_width, len(sentence))
first_end_index = min(start_index + min_span_width - 1, len(sentence))
for end_index in range(first_end_index, last_end_index):
start = offset + start_index
end = offset + end_index
if filter_function(sentence[slice(start_index, end_index + 1)]):
spans.append((start, end))
return spans
def bio_tags_to_spans(
tag_sequence: List[str], classes_to_ignore: List[str] = None
) -> List[TypedStringSpan]:
classes_to_ignore = classes_to_ignore or []
spans: Set[Tuple[str, Tuple[int, int]]] = set()
span_start = 0
span_end = 0
active_conll_tag = None
for index, string_tag in enumerate(tag_sequence):
bio_tag = string_tag[0]
if bio_tag not in ["B", "I", "O"]:
raise InvalidTagSequence(tag_sequence)
conll_tag = string_tag[2:]
if bio_tag == "O" or conll_tag in classes_to_ignore:
if active_conll_tag is not None:
spans.add((active_conll_tag, (span_start, span_end)))
active_conll_tag = None
# told to ignore, so we do nothing.
continue
elif bio_tag == "B":
# We are entering a new span; reset indices
# and active tag to new span.
if active_conll_tag is not None:
spans.add((active_conll_tag, (span_start, span_end)))
active_conll_tag = conll_tag
span_start = index
span_end = index
elif bio_tag == "I" and conll_tag == active_conll_tag:
# We're inside a span.
span_end += 1
else:
# 2) The span is an I tag for a different conll annotation.
# We'll process the previous span if it exists, but also
if active_conll_tag is not None:
spans.add((active_conll_tag, (span_start, span_end)))
active_conll_tag = conll_tag
span_start = index
span_end = index
if active_conll_tag is not None:
spans.add((active_conll_tag, (span_start, span_end)))
return list(spans)
def iob1_tags_to_spans(
tag_sequence: List[str], classes_to_ignore: List[str] = None
) -> List[TypedStringSpan]:
classes_to_ignore = classes_to_ignore or []
spans: Set[Tuple[str, Tuple[int, int]]] = set()
span_start = 0
span_end = 0
active_conll_tag = None
prev_bio_tag = None
prev_conll_tag = None
for index, string_tag in enumerate(tag_sequence):
curr_bio_tag = string_tag[0]
curr_conll_tag = string_tag[2:]
if curr_bio_tag not in ["B", "I", "O"]:
raise InvalidTagSequence(tag_sequence)
if curr_bio_tag == "O" or curr_conll_tag in classes_to_ignore:
if active_conll_tag is not None:
spans.add((active_conll_tag, (span_start, span_end)))
active_conll_tag = None
elif _iob1_start_of_chunk(prev_bio_tag, prev_conll_tag, curr_bio_tag, curr_conll_tag):
if active_conll_tag is not None:
spans.add((active_conll_tag, (span_start, span_end)))
active_conll_tag = curr_conll_tag
span_start = index
span_end = index
else:
span_end += 1
prev_bio_tag = string_tag[0]
prev_conll_tag = string_tag[2:]
# Last token might have been a part of a valid span.
if active_conll_tag is not None:
spans.add((active_conll_tag, (span_start, span_end)))
return list(spans)
def _iob1_start_of_chunk(
prev_bio_tag: Optional[str],
prev_conll_tag: Optional[str],
curr_bio_tag: str,
curr_conll_tag: str,
) -> bool:
if curr_bio_tag == "B":
return True
if curr_bio_tag == "I" and prev_bio_tag == "O":
return True
if curr_bio_tag != "O" and prev_conll_tag != curr_conll_tag:
return True
return False
def bioul_tags_to_spans(
tag_sequence: List[str], classes_to_ignore: List[str] = None
) -> List[TypedStringSpan]:
spans = []
classes_to_ignore = classes_to_ignore or []
index = 0
while index < len(tag_sequence):
label = tag_sequence[index]
if label[0] == "U":
spans.append((label.partition("-")[2], (index, index)))
elif label[0] == "B":
start = index
while label[0] != "L":
index += 1
if index >= len(tag_sequence):
raise InvalidTagSequence(tag_sequence)
label = tag_sequence[index]
if not (label[0] == "I" or label[0] == "L"):
raise InvalidTagSequence(tag_sequence)
spans.append((label.partition("-")[2], (start, index)))
else:
if label != "O":
raise InvalidTagSequence(tag_sequence)
index += 1
return [span for span in spans if span[0] not in classes_to_ignore]
def iob1_to_bioul(tag_sequence: List[str]) -> List[str]:
warnings.warn(
"iob1_to_bioul has been replaced with 'to_bioul' to allow more encoding options.",
FutureWarning,
)
return to_bioul(tag_sequence)
def to_bioul(tag_sequence: List[str], encoding: str = "IOB1") -> List[str]:
if encoding not in {"IOB1", "BIO"}:
raise ConfigurationError(f"Invalid encoding {encoding} passed to 'to_bioul'.")
def replace_label(full_label, new_label):
# example: full_label = 'I-PER', new_label = 'U', returns 'U-PER'
parts = list(full_label.partition("-"))
parts[0] = new_label
return "".join(parts)
def pop_replace_append(in_stack, out_stack, new_label):
# pop the last element from in_stack, replace the label, append
# to out_stack
tag = in_stack.pop()
new_tag = replace_label(tag, new_label)
out_stack.append(new_tag)
def process_stack(stack, out_stack):
# process a stack of labels, add them to out_stack
if len(stack) == 1:
# just a U token
pop_replace_append(stack, out_stack, "U")
else:
# need to code as BIL
recoded_stack = []
pop_replace_append(stack, recoded_stack, "L")
while len(stack) >= 2:
pop_replace_append(stack, recoded_stack, "I")
pop_replace_append(stack, recoded_stack, "B")
recoded_stack.reverse()
out_stack.extend(recoded_stack)
# Process the tag_sequence one tag at a time, adding spans to a stack,
# then recode them.
bioul_sequence = []
stack: List[str] = []
for label in tag_sequence:
# need to make a dict like
# token = {'token': 'Matt', "labels": {'conll2003': "B-PER"}
# 'gold': 'I-PER'}
# where 'gold' is the raw value from the CoNLL data set
if label == "O" and len(stack) == 0:
bioul_sequence.append(label)
elif label == "O" and len(stack) > 0:
# need to process the entries on the stack plus this one
process_stack(stack, bioul_sequence)
bioul_sequence.append(label)
elif label[0] == "I":
# check if the previous type is the same as this one
# if it is then append to stack
# otherwise this start a new entity if the type
# is different
if len(stack) == 0:
if encoding == "BIO":
raise InvalidTagSequence(tag_sequence)
stack.append(label)
else:
# check if the previous type is the same as this one
this_type = label.partition("-")[2]
prev_type = stack[-1].partition("-")[2]
if this_type == prev_type:
stack.append(label)
else:
if encoding == "BIO":
raise InvalidTagSequence(tag_sequence)
# a new entity
process_stack(stack, bioul_sequence)
stack.append(label)
elif label[0] == "B":
if len(stack) > 0:
process_stack(stack, bioul_sequence)
stack.append(label)
else:
raise InvalidTagSequence(tag_sequence)
# process the stack
if len(stack) > 0:
process_stack(stack, bioul_sequence)
return bioul_sequence
def bmes_tags_to_spans(
tag_sequence: List[str], classes_to_ignore: List[str] = None
) -> List[TypedStringSpan]:
def extract_bmes_tag_label(text):
bmes_tag = text[0]
label = text[2:]
return bmes_tag, label
spans: List[Tuple[str, List[int]]] = []
prev_bmes_tag: Optional[str] = None
for index, tag in enumerate(tag_sequence):
bmes_tag, label = extract_bmes_tag_label(tag)
if bmes_tag in ("B", "S"):
# Regardless of tag, we start a new span when reaching B & S.
spans.append((label, [index, index]))
elif bmes_tag in ("M", "E") and prev_bmes_tag in ("B", "M") and spans[-1][0] == label:
# Only expand the span if
# 1. Valid transition: B/M -> M/E.
# 2. Matched label.
spans[-1][1][1] = index
else:
# Best effort split for invalid span.
spans.append((label, [index, index]))
# update previous BMES tag.
prev_bmes_tag = bmes_tag
classes_to_ignore = classes_to_ignore or []
return [
# to tuple.
(span[0], (span[1][0], span[1][1]))
for span in spans
if span[0] not in classes_to_ignore
]
| true | true |
f73b806038319cb54561e5961d12b124b0058fcb | 1,268 | py | Python | test7-2.py | carolninganga/week7project | 9a114701371f653ffceb1555ab05d1161831cf78 | [
"Apache-2.0"
] | null | null | null | test7-2.py | carolninganga/week7project | 9a114701371f653ffceb1555ab05d1161831cf78 | [
"Apache-2.0"
] | null | null | null | test7-2.py | carolninganga/week7project | 9a114701371f653ffceb1555ab05d1161831cf78 | [
"Apache-2.0"
] | null | null | null | # Bruce Maxwell
# Fall 2020
# CS 5001 Project 7
# First L-system project
# Some test code
import turtle
import turtle_interpreter as ti
# useful goto function
def goto(x, y):
turtle.up()
turtle.goto(x, y)
turtle.down()
# main function that makes a small tree in a pot
def makeTree():
# set up the window and turn off tracing
turtle.setup(500, 500)
turtle.tracer(False)
# draw a small symmetric tree
turtle.setheading(90)
goto(0,0)
s = 'F[+F[+F][-F]][-F[+F][-F]]'
turtle.width(3)
ti.drawString( s, 50, 30 )
turtle.width(1)
# draw the pot and legs
turtle.setheading(0)
goto(-50, -100)
turtle.color('brown')
turtle.begin_fill()
ti.drawString( 'F+'*4, 100, 90 )
turtle.end_fill()
goto(-50, -100)
turtle.color('dark red')
turtle.begin_fill()
ti.drawString( 'F'*10+'+F+'+'F'*10+'+F+', 10, 90 )
turtle.end_fill()
goto(-60, -120)
turtle.begin_fill()
ti.drawString( 'F+'+'F'*12+'+F+'+'F'*12+'+', 10, 90 )
turtle.end_fill()
goto(50, -120)
turtle.begin_fill()
ti.drawString( 'F+'+'F'*12+'+F+'+'F'*12+'+', 10, 90 )
turtle.end_fill()
# update and hold
ti.hold()
return
if __name__ == "__main__":
makeTree()
| 19.8125 | 57 | 0.58123 |
import turtle
import turtle_interpreter as ti
def goto(x, y):
turtle.up()
turtle.goto(x, y)
turtle.down()
def makeTree():
turtle.setup(500, 500)
turtle.tracer(False)
turtle.setheading(90)
goto(0,0)
s = 'F[+F[+F][-F]][-F[+F][-F]]'
turtle.width(3)
ti.drawString( s, 50, 30 )
turtle.width(1)
turtle.setheading(0)
goto(-50, -100)
turtle.color('brown')
turtle.begin_fill()
ti.drawString( 'F+'*4, 100, 90 )
turtle.end_fill()
goto(-50, -100)
turtle.color('dark red')
turtle.begin_fill()
ti.drawString( 'F'*10+'+F+'+'F'*10+'+F+', 10, 90 )
turtle.end_fill()
goto(-60, -120)
turtle.begin_fill()
ti.drawString( 'F+'+'F'*12+'+F+'+'F'*12+'+', 10, 90 )
turtle.end_fill()
goto(50, -120)
turtle.begin_fill()
ti.drawString( 'F+'+'F'*12+'+F+'+'F'*12+'+', 10, 90 )
turtle.end_fill()
ti.hold()
return
if __name__ == "__main__":
makeTree()
| true | true |
f73b81858ce995d925555f906571c7538ded8f4d | 16,179 | py | Python | pyaxe/axesrc/axecommands.py | sosey/pyaxe | f57de55daf77de21d5868ace08b69090778d5975 | [
"BSD-3-Clause"
] | null | null | null | pyaxe/axesrc/axecommands.py | sosey/pyaxe | f57de55daf77de21d5868ace08b69090778d5975 | [
"BSD-3-Clause"
] | null | null | null | pyaxe/axesrc/axecommands.py | sosey/pyaxe | f57de55daf77de21d5868ace08b69090778d5975 | [
"BSD-3-Clause"
] | null | null | null | import sys
import shutil
import logging
from astropy.io import fits
from pyaxe import config as config_util
from . import axetasks
from .axeerror import aXeSIMError
# make sure there is a logger
_log = logging.getLogger(__name__)
"""
The following deal with axe simulations
"""
class DispImator(object):
"""Class to create a dispersed image"""
def __init__(self, dummyImages, configfile, simobjects, lambda_psf=None,
model_spectra=None, model_images=None):
"""
Parameters
----------
dummyImages: DummyImages()
dummy image structure
configfile: str
name of the aXe configuration file
simobjects: str
name of the model object table
lambda_psf: float
reference wavelength for the psf
model_spectra: str
name of the model spectra file
model_images: str
name of the model image file
"""
# save the naked name of the grism image
self.grismname = os.path.basename(dummyImages.griname)
# check whether there is a direct image
if dummyImages.dirname is not None:
# save the direct image name
self.dirname = os.path.basename(dummyImages.dirname)
else:
# set the direct image name to 'None'
self.dirname = None
# save all other input to class variables
self.configfile = configfile
self.iolname = simobjects
self.model_spectra = model_spectra
self.model_images = model_images
self.lambda_psf = lambda_psf
# check whether model images are given
# append the file name to the list
if self.model_images is not None:
self.cont_model = 'direct'
else:
self.cont_model = 'gauss'
def run(self, silent=True):
"""Generates a simulated dispersed image
The method executes the series of aXe tasks necessary to generate
a simulated dispersed image. The input from the class data is
supplemented with default values.
Parameters
----------
silent: boolean for silent mode
"""
# run SEX2GOL
_log.info('Running task "sex2gol" ...', end=' ')
sys.stdout.flush()
axetasks.sex2gol(grism=self.grismname,
config=self.configfile,
in_sex=self.iolname,
use_direct=True,
direct=self.dirname,
silent=silent)
_log.info(' Done')
# run GOL2AF
_log.info('Running task "gol2af" ...')
axetasks.gol2af(grism=self.grismname,
config=self.configfile,
orient=1,
slitless_geom=1,
silent=silent)
_log.info(' Done')
# run PETCONT
_log.info('Running task "petcont" ...', end=' ')
sys.stdout.flush()
axetasks.petcont(grism=self.grismname,
config=self.configfile,
cont_model=self.cont_model,
spec_models=self.model_spectra,
object_models=self.model_images,
lambda_psf=self.lambda_psf,
no_pet=True,
silent=silent)
_log.info(' Done')
def mopup(self):
"""Deleting GOL and OAF files"""
# get the root name of the dispersed image
pos = self.grismname.rfind('.fits')
root_name = self.grismname[:pos]
# delete the GOL, the OAF and the PET
result_cat = config_util.getOUTPUT(root_name + '_2.cat')
if os.path.isfile(result_cat):
os.unlink(result_cat)
result_oaf = config_util.getOUTPUT(root_name + '_2.OAF')
if os.path.isfile(result_oaf):
os.unlink(result_oaf)
class DirImator(object):
"""Class to create a direct image"""
def __init__(self, dummyImages, configfile, simobjects, tpass_direct,
model_spectra=None, model_images=None, tel_area=None):
"""
Parameters
----------
dummyImages: dDummyImages()
dummy image structure
configfile: str
name of the aXe configuration file
simobjects: str
name of the model object table
tpass_direct: str
name of the total passband file
model_spectra: str
name of the model spectra file
model_images: str
name of the model image file
tel_area: float
the collecting area of the telescope
"""
# save the naked name of the direct image
self.dirname = os.path.basename(dummyImages.dirname)
# save all other input to local variables
self.configfile = configfile
self.iolname = simobjects
self.tpass_direct = tpass_direct
self.model_spectra = model_spectra
self.model_images = model_images
self.tel_area = tel_area
def run(self, silent=False):
"""Generates a simulated direct image
The method executes the series of aXe tasks necessary to generate
a simulated direct image.
Parameters
----------
silent: bool
for silent mode
"""
# run SEX2GOL
_log.info('Running task "sex2gol" ...', end=' ')
sys.stdout.flush()
axetasks.sex2gol(grism=self.dirname,
config=self.configfile,
in_sex=self.iolname,
use_direct=False,
silent=silent)
_log.info(' Done')
# run GOL2AF
_log.info('Running task "gol2af" ...')
sys.stdout.flush()
axetasks.gol2af(grism=self.dirname,
config=self.configfile,
silent=silent)
_log.info(' Done')
# run DIRIMAGE
_log.info('Running task "dirimage" ...')
sys.stdout.flush()
axetasks.axedirim(dirname=self.dirname,
config=self.configfile,
tpass_direct=self.tpass_direct,
model_spectra=self.model_spectra,
model_images=self.model_images,
tel_area=self.tel_area,
silent=silent)
_log.info(' Done')
def mopup(self):
"""Deleting GOL and OAF files"""
# get the root name of the dispersed image
pos = self.dirname.rfind('.fits')
root_name = self.dirname[:pos]
# delete the GOL, the OAF and the PET
result_cat = config_util.getOUTPUT(root_name + '_2.cat')
if os.path.isfile(result_cat):
os.unlink(result_cat)
result_oaf = config_util.getOUTPUT(root_name + '_2.OAF')
if os.path.isfile(result_oaf):
os.unlink(result_oaf)
class DummyExtractor(object):
"""Class to make a dummy extraction"""
def __init__(self, dummyImages, grism_image, configfile, simobjects,
bck_flux, extrfwhm=3.0, orient=True, slitless_geom=True,
adj_sens=True, lambda_mark=None):
"""
Parameters
----------
dummyImages: DummyImages()
dummy image structure
grism_image: str
the simulated grism image name
configfile: str
name of the aXe configuration file
simobjects: str
name of the model object table
bck_flux: float or string
backround-flux or image
extrfwhm: float
multiplier for extraction width
orient: bool
flag for tilted extraction
slitless_geom: bool
flag for slitless optimized extraction
adj_sens: bool
flag for adjusted flux conversion
lambda_mark: float
wavelength to apply cutoff magnitudes
"""
# save the direct image name
self.direct_image = os.path.basename(dummyImages.dirname)
self.simul_grisim = os.path.basename(grism_image)
self.dispersed_image = None
# save all other input to local variables
self.configfile = configfile
self.iolname = simobjects
self.bck_flux = bck_flux
self.extrfwhm = extrfwhm
self.orient = orient
self.slitless_geom = slitless_geom
self.adj_sens = adj_sens
self.lambda_mark = lambda_mark
# check whether everything
# is where it is supposed to be
self._check_files()
def _check_files(self):
"""Checks the existence of the input files"""
# check the direct image
if not os.path.isfile(config_util.getDATA(self.direct_image)):
err_msg = ("\nThe direct image is not available: {0:s}"
.format(config_util.getDATA(self.direct_image)))
raise aXeSIMError(err_msg)
# check the configuration file
if not os.path.isfile(config_util.getCONF(self.configfile)):
err_msg = ("\nThe configuration file is not available: {0:s}"
.format(config_util.getCONF(self.configfile)))
raise aXeSIMError(err_msg)
# check the simulated grism image
if not os.path.isfile(config_util.getOUTSIM(self.simul_grisim)):
err_msg = ("\nThe grism image is not available: {0:s}"
.format(config_util.getOUTSIM(self.simul_grisim)))
raise aXeSIMError(err_msg)
# check the IOL
if not os.path.isfile(self.iolname):
err_msg = ("\nThe Input Object List is not available: {0:s}"
.format(self.iolname))
raise aXeSIMError(err_msg)
try:
float(self.bck_flux)
except ValueError:
# check the background image
if not os.path.isfile(config_util.getCONF(self.bck_flux)):
err_msg = ("\nThe background imagage is not available: {0:s}"
.format(config_util.getCONF(self.bck_flux)))
raise aXeSIMError(err_msg)
def _decorate_PET(self):
"""Write the 'CONTAM'-keyword into the PET
The method determines the name of the PET and
sets the contamination keyword in the zero-extension header
"""
# get the root name of the dispersed image
root_name = self.dispersed_image.split('.fits')[0]
# compose the name of the PET
result_pet = config_util.getOUTPUT(root_name + '_2.PET.fits')
# open the PET
pet_fits = fits.open(result_pet, mode='update')
# update the PET header
comment_str = 'dummy flag - no quantitative contamination'
pet_fits[0].header['CONTAM'] = ('GEOM', comment_str)
# close and out
pet_fits.close()
def prepare_extraction(self):
"""Prepares the aXe extraction
The module does some preparatory stuff before the extraction
can start. This includes copying the simulated dispersed image
to AXE_IMAGE_PATH and subtracting the background on this copy.
"""
# give brief feedback
_log.info('Dummy extraction on the dispersed image:')
sys.stdout.flush()
# get a random filenames
tmpfile1 = config_util.get_random_filename('t', '.fits')
# copy the grism image to AXE_IMAGE_PATH
shutil.copy(config_util.getOUTSIM(self.simul_grisim),
config_util.getDATA(tmpfile1))
# subtract the background from
# the grism image
# expression = "(a - b)"
# iraf.imexpr(expr=expression, output=tmpfile2,
# a=config_util.getDATA(tmpfile1)+'[SCI]', b=self.bck_flux, Stdout=1)
in_image = fits.open(config_util.getDATA(tmpfile1))
in_image['sci'].data -= self.bck_flux
in_image.close()
# store the name of the background
# subtracted grism image - this was tmpfile
self.dispersed_image = tmpfile1
def mopup(self):
"""Deleting tmp-files, copying SPC's, STP's"""
# get the root name of the dispersed image
root_name = self.dispersed_image.split('.fits')[0]
# get the root name of the simulated image
result_root = self.simul_grisim.split('.fits')[0]
# move and rename the SPC-file
out_spc = config_util.getOUTPUT(root_name + '_2.SPC.fits')
result_spc = config_util.getOUTSIM(result_root + '_2.SPC.fits')
shutil.move(out_spc, result_spc)
# move and rename the STP-file
out_stp = config_util.getOUTPUT(root_name + '_2.STP.fits')
result_stp = config_util.getOUTSIM(result_root + '_2.STP.fits')
shutil.move(out_stp, result_stp)
# delete the background subtracted
# grism image
os.unlink(config_util.getDATA(self.dispersed_image))
# delete the GOL, the OAF and the PET
result_cat = config_util.getOUTPUT(root_name + '_2.cat')
if os.path.isfile(result_cat):
os.unlink(result_cat)
result_oaf = config_util.getOUTPUT(root_name + '_2.OAF')
if os.path.isfile(result_oaf):
os.unlink(result_oaf)
result_pet = config_util.getOUTPUT(root_name + '_2.PET.fits')
if os.path.isfile(result_pet):
os.unlink(result_pet)
def run(self, silent=True):
"""Generates a simulated dispersed image
The method executes the series of aXe tasks necessary to generate
a simulated dispersed image. The input from the class data is
supplemented with default values.
Parameters
----------
silent: bool
boolean for silent mode
"""
# run SEX2GOL
_log.info('Running task "sex2gol" ...', end=' ')
sys.stdout.flush()
axetasks.sex2gol(grism=self.dispersed_image,
config=self.configfile,
in_sex=self.iolname,
use_direct=True,
direct=self.direct_image,
silent=silent)
_log.info(' Done')
# run GOL2AF
_log.info('Running task "gol2af" ...', end=' ')
sys.stdout.flush()
axetasks.gol2af(grism=self.dispersed_image,
config=self.configfile,
mfwhm=self.extrfwhm,
orient=self.orient,
slitless_geom=self.slitless_geom,
lambda_mark=self.lambda_mark,
ilent=silent)
_log.info(' Done')
# run AF2PET
_log.info('Running task "af2pet" ...', end=' ')
sys.stdout.flush()
axetasks.af2pet(grism=self.dispersed_image,
config=self.configfile,
silent=silent)
_log.info(' Done')
# -----------------------------------------------
# set the contamination keyword
#
# Running PECONT, is, since we are doing
# a simulation, not very reasonable.
# However PET2SPC complains if the contmaintion
# keyword is not set. A solution is just to set
# the geometrical contamination keyword to make
# the warning in PET2SPC disappear.
self._decorate_PET()
# -----------------------------------------------
# run PET2SPC
_log.info('Running task "pet2spc" ...', end=' ')
sys.stdout.flush()
axetasks.pet2spc(grism=self.dispersed_image,
config=self.configfile,
adj_sens=self.adj_sens,
silent=silent)
_log.info(' Done')
# run STAMPS
_log.info('Running task "stamps" ...', end=' ')
sys.stdout.flush()
axetasks.stamps(grism=self.dispersed_image,
config=self.configfile,
sampling='rectified',
silent=silent)
_log.info(' Done')
| 35.095445 | 80 | 0.570925 | import sys
import shutil
import logging
from astropy.io import fits
from pyaxe import config as config_util
from . import axetasks
from .axeerror import aXeSIMError
_log = logging.getLogger(__name__)
class DispImator(object):
def __init__(self, dummyImages, configfile, simobjects, lambda_psf=None,
model_spectra=None, model_images=None):
self.grismname = os.path.basename(dummyImages.griname)
if dummyImages.dirname is not None:
self.dirname = os.path.basename(dummyImages.dirname)
else:
self.dirname = None
self.configfile = configfile
self.iolname = simobjects
self.model_spectra = model_spectra
self.model_images = model_images
self.lambda_psf = lambda_psf
if self.model_images is not None:
self.cont_model = 'direct'
else:
self.cont_model = 'gauss'
def run(self, silent=True):
_log.info('Running task "sex2gol" ...', end=' ')
sys.stdout.flush()
axetasks.sex2gol(grism=self.grismname,
config=self.configfile,
in_sex=self.iolname,
use_direct=True,
direct=self.dirname,
silent=silent)
_log.info(' Done')
_log.info('Running task "gol2af" ...')
axetasks.gol2af(grism=self.grismname,
config=self.configfile,
orient=1,
slitless_geom=1,
silent=silent)
_log.info(' Done')
_log.info('Running task "petcont" ...', end=' ')
sys.stdout.flush()
axetasks.petcont(grism=self.grismname,
config=self.configfile,
cont_model=self.cont_model,
spec_models=self.model_spectra,
object_models=self.model_images,
lambda_psf=self.lambda_psf,
no_pet=True,
silent=silent)
_log.info(' Done')
def mopup(self):
pos = self.grismname.rfind('.fits')
root_name = self.grismname[:pos]
result_cat = config_util.getOUTPUT(root_name + '_2.cat')
if os.path.isfile(result_cat):
os.unlink(result_cat)
result_oaf = config_util.getOUTPUT(root_name + '_2.OAF')
if os.path.isfile(result_oaf):
os.unlink(result_oaf)
class DirImator(object):
def __init__(self, dummyImages, configfile, simobjects, tpass_direct,
model_spectra=None, model_images=None, tel_area=None):
self.dirname = os.path.basename(dummyImages.dirname)
self.configfile = configfile
self.iolname = simobjects
self.tpass_direct = tpass_direct
self.model_spectra = model_spectra
self.model_images = model_images
self.tel_area = tel_area
def run(self, silent=False):
_log.info('Running task "sex2gol" ...', end=' ')
sys.stdout.flush()
axetasks.sex2gol(grism=self.dirname,
config=self.configfile,
in_sex=self.iolname,
use_direct=False,
silent=silent)
_log.info(' Done')
_log.info('Running task "gol2af" ...')
sys.stdout.flush()
axetasks.gol2af(grism=self.dirname,
config=self.configfile,
silent=silent)
_log.info(' Done')
_log.info('Running task "dirimage" ...')
sys.stdout.flush()
axetasks.axedirim(dirname=self.dirname,
config=self.configfile,
tpass_direct=self.tpass_direct,
model_spectra=self.model_spectra,
model_images=self.model_images,
tel_area=self.tel_area,
silent=silent)
_log.info(' Done')
def mopup(self):
pos = self.dirname.rfind('.fits')
root_name = self.dirname[:pos]
result_cat = config_util.getOUTPUT(root_name + '_2.cat')
if os.path.isfile(result_cat):
os.unlink(result_cat)
result_oaf = config_util.getOUTPUT(root_name + '_2.OAF')
if os.path.isfile(result_oaf):
os.unlink(result_oaf)
class DummyExtractor(object):
def __init__(self, dummyImages, grism_image, configfile, simobjects,
bck_flux, extrfwhm=3.0, orient=True, slitless_geom=True,
adj_sens=True, lambda_mark=None):
self.direct_image = os.path.basename(dummyImages.dirname)
self.simul_grisim = os.path.basename(grism_image)
self.dispersed_image = None
self.configfile = configfile
self.iolname = simobjects
self.bck_flux = bck_flux
self.extrfwhm = extrfwhm
self.orient = orient
self.slitless_geom = slitless_geom
self.adj_sens = adj_sens
self.lambda_mark = lambda_mark
self._check_files()
def _check_files(self):
if not os.path.isfile(config_util.getDATA(self.direct_image)):
err_msg = ("\nThe direct image is not available: {0:s}"
.format(config_util.getDATA(self.direct_image)))
raise aXeSIMError(err_msg)
if not os.path.isfile(config_util.getCONF(self.configfile)):
err_msg = ("\nThe configuration file is not available: {0:s}"
.format(config_util.getCONF(self.configfile)))
raise aXeSIMError(err_msg)
if not os.path.isfile(config_util.getOUTSIM(self.simul_grisim)):
err_msg = ("\nThe grism image is not available: {0:s}"
.format(config_util.getOUTSIM(self.simul_grisim)))
raise aXeSIMError(err_msg)
if not os.path.isfile(self.iolname):
err_msg = ("\nThe Input Object List is not available: {0:s}"
.format(self.iolname))
raise aXeSIMError(err_msg)
try:
float(self.bck_flux)
except ValueError:
if not os.path.isfile(config_util.getCONF(self.bck_flux)):
err_msg = ("\nThe background imagage is not available: {0:s}"
.format(config_util.getCONF(self.bck_flux)))
raise aXeSIMError(err_msg)
def _decorate_PET(self):
root_name = self.dispersed_image.split('.fits')[0]
result_pet = config_util.getOUTPUT(root_name + '_2.PET.fits')
pet_fits = fits.open(result_pet, mode='update')
comment_str = 'dummy flag - no quantitative contamination'
pet_fits[0].header['CONTAM'] = ('GEOM', comment_str)
pet_fits.close()
def prepare_extraction(self):
_log.info('Dummy extraction on the dispersed image:')
sys.stdout.flush()
tmpfile1 = config_util.get_random_filename('t', '.fits')
shutil.copy(config_util.getOUTSIM(self.simul_grisim),
config_util.getDATA(tmpfile1))
in_image = fits.open(config_util.getDATA(tmpfile1))
in_image['sci'].data -= self.bck_flux
in_image.close()
self.dispersed_image = tmpfile1
def mopup(self):
root_name = self.dispersed_image.split('.fits')[0]
result_root = self.simul_grisim.split('.fits')[0]
out_spc = config_util.getOUTPUT(root_name + '_2.SPC.fits')
result_spc = config_util.getOUTSIM(result_root + '_2.SPC.fits')
shutil.move(out_spc, result_spc)
out_stp = config_util.getOUTPUT(root_name + '_2.STP.fits')
result_stp = config_util.getOUTSIM(result_root + '_2.STP.fits')
shutil.move(out_stp, result_stp)
os.unlink(config_util.getDATA(self.dispersed_image))
result_cat = config_util.getOUTPUT(root_name + '_2.cat')
if os.path.isfile(result_cat):
os.unlink(result_cat)
result_oaf = config_util.getOUTPUT(root_name + '_2.OAF')
if os.path.isfile(result_oaf):
os.unlink(result_oaf)
result_pet = config_util.getOUTPUT(root_name + '_2.PET.fits')
if os.path.isfile(result_pet):
os.unlink(result_pet)
def run(self, silent=True):
_log.info('Running task "sex2gol" ...', end=' ')
sys.stdout.flush()
axetasks.sex2gol(grism=self.dispersed_image,
config=self.configfile,
in_sex=self.iolname,
use_direct=True,
direct=self.direct_image,
silent=silent)
_log.info(' Done')
_log.info('Running task "gol2af" ...', end=' ')
sys.stdout.flush()
axetasks.gol2af(grism=self.dispersed_image,
config=self.configfile,
mfwhm=self.extrfwhm,
orient=self.orient,
slitless_geom=self.slitless_geom,
lambda_mark=self.lambda_mark,
ilent=silent)
_log.info(' Done')
_log.info('Running task "af2pet" ...', end=' ')
sys.stdout.flush()
axetasks.af2pet(grism=self.dispersed_image,
config=self.configfile,
silent=silent)
_log.info(' Done')
self._decorate_PET()
_log.info('Running task "pet2spc" ...', end=' ')
sys.stdout.flush()
axetasks.pet2spc(grism=self.dispersed_image,
config=self.configfile,
adj_sens=self.adj_sens,
silent=silent)
_log.info(' Done')
_log.info('Running task "stamps" ...', end=' ')
sys.stdout.flush()
axetasks.stamps(grism=self.dispersed_image,
config=self.configfile,
sampling='rectified',
silent=silent)
_log.info(' Done')
| true | true |
f73b830b90c647991499d0a0d7660ad41ed300da | 6,798 | py | Python | kubernetes/client/models/v1_service_list.py | pllsxyc/python | 442ebc019056c2dc246be94f85cf61f1e1d26a88 | [
"Apache-2.0"
] | 1 | 2019-10-07T13:54:36.000Z | 2019-10-07T13:54:36.000Z | kubernetes/client/models/v1_service_list.py | pllsxyc/python | 442ebc019056c2dc246be94f85cf61f1e1d26a88 | [
"Apache-2.0"
] | 8 | 2020-12-21T03:18:50.000Z | 2022-03-02T03:06:30.000Z | kubernetes/client/models/v1_service_list.py | pllsxyc/python | 442ebc019056c2dc246be94f85cf61f1e1d26a88 | [
"Apache-2.0"
] | 1 | 2021-03-16T16:05:33.000Z | 2021-03-16T16:05:33.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.16
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from kubernetes.client.configuration import Configuration
class V1ServiceList(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 = {
'api_version': 'str',
'items': 'list[V1Service]',
'kind': 'str',
'metadata': 'V1ListMeta'
}
attribute_map = {
'api_version': 'apiVersion',
'items': 'items',
'kind': 'kind',
'metadata': 'metadata'
}
def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501
"""V1ServiceList - 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._api_version = None
self._items = None
self._kind = None
self._metadata = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
self.items = items
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
@property
def api_version(self):
"""Gets the api_version of this V1ServiceList. # noqa: E501
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:return: The api_version of this V1ServiceList. # noqa: E501
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""Sets the api_version of this V1ServiceList.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:param api_version: The api_version of this V1ServiceList. # noqa: E501
:type: str
"""
self._api_version = api_version
@property
def items(self):
"""Gets the items of this V1ServiceList. # noqa: E501
List of services # noqa: E501
:return: The items of this V1ServiceList. # noqa: E501
:rtype: list[V1Service]
"""
return self._items
@items.setter
def items(self, items):
"""Sets the items of this V1ServiceList.
List of services # noqa: E501
:param items: The items of this V1ServiceList. # noqa: E501
:type: list[V1Service]
"""
if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501
raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501
self._items = items
@property
def kind(self):
"""Gets the kind of this V1ServiceList. # noqa: E501
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:return: The kind of this V1ServiceList. # noqa: E501
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""Sets the kind of this V1ServiceList.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this V1ServiceList. # noqa: E501
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""Gets the metadata of this V1ServiceList. # noqa: E501
:return: The metadata of this V1ServiceList. # noqa: E501
:rtype: V1ListMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this V1ServiceList.
:param metadata: The metadata of this V1ServiceList. # noqa: E501
:type: V1ListMeta
"""
self._metadata = metadata
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, V1ServiceList):
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, V1ServiceList):
return True
return self.to_dict() != other.to_dict()
| 33 | 312 | 0.619594 |
import pprint
import re
import six
from kubernetes.client.configuration import Configuration
class V1ServiceList(object):
openapi_types = {
'api_version': 'str',
'items': 'list[V1Service]',
'kind': 'str',
'metadata': 'V1ListMeta'
}
attribute_map = {
'api_version': 'apiVersion',
'items': 'items',
'kind': 'kind',
'metadata': 'metadata'
}
def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None):
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._api_version = None
self._items = None
self._kind = None
self._metadata = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
self.items = items
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
@property
def api_version(self):
return self._api_version
@api_version.setter
def api_version(self, api_version):
self._api_version = api_version
@property
def items(self):
return self._items
@items.setter
def items(self, items):
if self.local_vars_configuration.client_side_validation and items is None:
raise ValueError("Invalid value for `items`, must not be `None`")
self._items = items
@property
def kind(self):
return self._kind
@kind.setter
def kind(self, kind):
self._kind = kind
@property
def metadata(self):
return self._metadata
@metadata.setter
def metadata(self, metadata):
self._metadata = metadata
def to_dict(self):
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):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, V1ServiceList):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
if not isinstance(other, V1ServiceList):
return True
return self.to_dict() != other.to_dict()
| true | true |
f73b84aebb0ba5336bdcf4ec5c5f044e640e835e | 6,136 | py | Python | mystic/__init__.py | RykerCohen/mystic | 5f60e43642e21f13068cc9a755712f240038fa48 | [
"MIT"
] | 2 | 2020-11-06T02:27:57.000Z | 2020-11-06T08:22:06.000Z | mystic/__init__.py | RykerCohen/mystic | 5f60e43642e21f13068cc9a755712f240038fa48 | [
"MIT"
] | 16 | 2020-11-06T05:13:39.000Z | 2020-11-08T03:23:29.000Z | mystic/__init__.py | RykerCohen/mystic | 5f60e43642e21f13068cc9a755712f240038fa48 | [
"MIT"
] | 3 | 2020-11-06T17:13:29.000Z | 2020-11-25T16:17:30.000Z | import asyncio
import importlib
import logging
import pkgutil
from abc import ABC, abstractmethod
from collections import OrderedDict
from types import FunctionType
def get_package_modules(package):
package_modules = []
for importer, module_name, is_package in pkgutil.iter_modules(package.__path__):
full_module_name = f'{package.__name__}.{module_name}'
subpackage_object = importlib.import_module(full_module_name, package=package.__path__)
if is_package:
sub_package_modules = get_package_modules(subpackage_object)
package_modules = package_modules + sub_package_modules
package_modules.append(subpackage_object)
return package_modules
class _AbstractManager(dict):
def __init__(self, server):
self.server = server
self.logger = logging.getLogger('mystic')
super().__init__()
@abstractmethod
async def setup(self, module):
"""Setup manager class"""
@abstractmethod
async def load(self, module):
"""Loads entries from module"""
class ITable(ABC):
"""
All table game logic classes must implement this interface.
"""
@abstractmethod
def make_move(self, *args):
"""Tells logic a move has been made."""
@abstractmethod
def is_valid_move(self, *args):
"""Returns true if the move is valid."""
@abstractmethod
def get_string(self):
"""Returns string representation of the game."""
class IWaddle(ABC):
"""
All waddle game logic classes must implement this interface.
"""
@property
@abstractmethod
def room_id(self):
"""External ID of waddle game room."""
def __init__(self, waddle):
self.penguins = list(waddle.penguins)
self.seats = waddle.seats
async def start(self):
room_id = type(self).room_id
for penguin in self.penguins:
penguin.waddle = self
await penguin.join_room(penguin.server.rooms[room_id])
async def remove_penguin(self, p):
self.penguins[self.penguins.index(p)] = None
p.waddle = None
async def send_xt(self, *data, f=None):
for penguin in filter(f, self.penguins):
if penguin is not None:
await penguin.send_xt(*data)
def get_seat_id(self, p):
return self.penguins.index(p)
class PenguinStringCompiler(OrderedDict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __setitem__(self, key, compiler_method):
assert type(compiler_method) == FunctionType
super().__setitem__(key, compiler_method)
async def compile(self, p):
compiler_method_results = []
for compiler_method in self.values():
if asyncio.iscoroutinefunction(compiler_method):
compiler_method_result = await compiler_method(p)
else:
compiler_method_result = compiler_method(p)
compiler_method_results.append(str(compiler_method_result))
compiler_result = '|'.join(compiler_method_results)
return compiler_result
@classmethod
def attribute_by_name(cls, attribute_name):
async def attribute_method(p):
return getattr(p, attribute_name) or 0
return attribute_method
@classmethod
def custom_attribute_by_name(cls, attribute_name):
async def attribute_method(p):
return p.get_custom_attribute(attribute_name, '')
return attribute_method
@classmethod
def setup_default_builder(cls, string_builder):
string_builder.update({
'ID': PenguinStringCompiler.attribute_by_name('id'),
'Nickname': PenguinStringCompiler.attribute_by_name('nickname'),
'Approval': PenguinStringCompiler.attribute_by_name('approval'),
'Color': PenguinStringCompiler.attribute_by_name('color'),
'Head': PenguinStringCompiler.attribute_by_name('head'),
'Face': PenguinStringCompiler.attribute_by_name('face'),
'Neck': PenguinStringCompiler.attribute_by_name('neck'),
'Body': PenguinStringCompiler.attribute_by_name('body'),
'Hand': PenguinStringCompiler.attribute_by_name('hand'),
'Feet': PenguinStringCompiler.attribute_by_name('feet'),
'Flag': PenguinStringCompiler.attribute_by_name('flag'),
'Photo': PenguinStringCompiler.attribute_by_name('photo'),
'X': PenguinStringCompiler.attribute_by_name('x'),
'Y': PenguinStringCompiler.attribute_by_name('y'),
'Frame': PenguinStringCompiler.attribute_by_name('frame'),
'Member': PenguinStringCompiler.attribute_by_name('member'),
'MemberDays': PenguinStringCompiler.attribute_by_name('membership_days_total'),
'Avatar': PenguinStringCompiler.attribute_by_name('avatar'),
'PenguinState': PenguinStringCompiler.attribute_by_name('penguin_state'),
'PartyState': PenguinStringCompiler.attribute_by_name('party_state'),
'PuffleState': PenguinStringCompiler.attribute_by_name('puffle_state')
})
@classmethod
def setup_anonymous_default_builder(cls, string_builder):
string_builder.update({
'ID': PenguinStringCompiler.attribute_by_name('id'),
'Nickname': PenguinStringCompiler.attribute_by_name('nickname'),
'Approval': PenguinStringCompiler.attribute_by_name('approval'),
'Color': PenguinStringCompiler.attribute_by_name('color'),
'Head': PenguinStringCompiler.attribute_by_name('head'),
'Face': PenguinStringCompiler.attribute_by_name('face'),
'Neck': PenguinStringCompiler.attribute_by_name('neck'),
'Body': PenguinStringCompiler.attribute_by_name('body'),
'Hand': PenguinStringCompiler.attribute_by_name('hand'),
'Feet': PenguinStringCompiler.attribute_by_name('feet'),
'Flag': PenguinStringCompiler.attribute_by_name('flag'),
'Photo': PenguinStringCompiler.attribute_by_name('photo')
})
| 36.963855 | 95 | 0.670469 | import asyncio
import importlib
import logging
import pkgutil
from abc import ABC, abstractmethod
from collections import OrderedDict
from types import FunctionType
def get_package_modules(package):
package_modules = []
for importer, module_name, is_package in pkgutil.iter_modules(package.__path__):
full_module_name = f'{package.__name__}.{module_name}'
subpackage_object = importlib.import_module(full_module_name, package=package.__path__)
if is_package:
sub_package_modules = get_package_modules(subpackage_object)
package_modules = package_modules + sub_package_modules
package_modules.append(subpackage_object)
return package_modules
class _AbstractManager(dict):
def __init__(self, server):
self.server = server
self.logger = logging.getLogger('mystic')
super().__init__()
@abstractmethod
async def setup(self, module):
@abstractmethod
async def load(self, module):
class ITable(ABC):
@abstractmethod
def make_move(self, *args):
@abstractmethod
def is_valid_move(self, *args):
@abstractmethod
def get_string(self):
class IWaddle(ABC):
@property
@abstractmethod
def room_id(self):
def __init__(self, waddle):
self.penguins = list(waddle.penguins)
self.seats = waddle.seats
async def start(self):
room_id = type(self).room_id
for penguin in self.penguins:
penguin.waddle = self
await penguin.join_room(penguin.server.rooms[room_id])
async def remove_penguin(self, p):
self.penguins[self.penguins.index(p)] = None
p.waddle = None
async def send_xt(self, *data, f=None):
for penguin in filter(f, self.penguins):
if penguin is not None:
await penguin.send_xt(*data)
def get_seat_id(self, p):
return self.penguins.index(p)
class PenguinStringCompiler(OrderedDict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __setitem__(self, key, compiler_method):
assert type(compiler_method) == FunctionType
super().__setitem__(key, compiler_method)
async def compile(self, p):
compiler_method_results = []
for compiler_method in self.values():
if asyncio.iscoroutinefunction(compiler_method):
compiler_method_result = await compiler_method(p)
else:
compiler_method_result = compiler_method(p)
compiler_method_results.append(str(compiler_method_result))
compiler_result = '|'.join(compiler_method_results)
return compiler_result
@classmethod
def attribute_by_name(cls, attribute_name):
async def attribute_method(p):
return getattr(p, attribute_name) or 0
return attribute_method
@classmethod
def custom_attribute_by_name(cls, attribute_name):
async def attribute_method(p):
return p.get_custom_attribute(attribute_name, '')
return attribute_method
@classmethod
def setup_default_builder(cls, string_builder):
string_builder.update({
'ID': PenguinStringCompiler.attribute_by_name('id'),
'Nickname': PenguinStringCompiler.attribute_by_name('nickname'),
'Approval': PenguinStringCompiler.attribute_by_name('approval'),
'Color': PenguinStringCompiler.attribute_by_name('color'),
'Head': PenguinStringCompiler.attribute_by_name('head'),
'Face': PenguinStringCompiler.attribute_by_name('face'),
'Neck': PenguinStringCompiler.attribute_by_name('neck'),
'Body': PenguinStringCompiler.attribute_by_name('body'),
'Hand': PenguinStringCompiler.attribute_by_name('hand'),
'Feet': PenguinStringCompiler.attribute_by_name('feet'),
'Flag': PenguinStringCompiler.attribute_by_name('flag'),
'Photo': PenguinStringCompiler.attribute_by_name('photo'),
'X': PenguinStringCompiler.attribute_by_name('x'),
'Y': PenguinStringCompiler.attribute_by_name('y'),
'Frame': PenguinStringCompiler.attribute_by_name('frame'),
'Member': PenguinStringCompiler.attribute_by_name('member'),
'MemberDays': PenguinStringCompiler.attribute_by_name('membership_days_total'),
'Avatar': PenguinStringCompiler.attribute_by_name('avatar'),
'PenguinState': PenguinStringCompiler.attribute_by_name('penguin_state'),
'PartyState': PenguinStringCompiler.attribute_by_name('party_state'),
'PuffleState': PenguinStringCompiler.attribute_by_name('puffle_state')
})
@classmethod
def setup_anonymous_default_builder(cls, string_builder):
string_builder.update({
'ID': PenguinStringCompiler.attribute_by_name('id'),
'Nickname': PenguinStringCompiler.attribute_by_name('nickname'),
'Approval': PenguinStringCompiler.attribute_by_name('approval'),
'Color': PenguinStringCompiler.attribute_by_name('color'),
'Head': PenguinStringCompiler.attribute_by_name('head'),
'Face': PenguinStringCompiler.attribute_by_name('face'),
'Neck': PenguinStringCompiler.attribute_by_name('neck'),
'Body': PenguinStringCompiler.attribute_by_name('body'),
'Hand': PenguinStringCompiler.attribute_by_name('hand'),
'Feet': PenguinStringCompiler.attribute_by_name('feet'),
'Flag': PenguinStringCompiler.attribute_by_name('flag'),
'Photo': PenguinStringCompiler.attribute_by_name('photo')
})
| true | true |
f73b8567300bcad64d1eefbaf7a24b0223b81b9b | 8,972 | py | Python | sentry_sdk/integrations/asgi.py | simonschmidt/sentry-python | cad2f65316bab4ee5792b1b788c32c57293eea5e | [
"BSD-2-Clause"
] | 1,213 | 2018-06-19T00:51:01.000Z | 2022-03-31T06:37:16.000Z | sentry_sdk/integrations/asgi.py | maltalk/sentry-python | 4e346acbabb1fd5592663bf9acd580835236fcf0 | [
"BSD-2-Clause"
] | 1,020 | 2018-07-16T12:50:36.000Z | 2022-03-31T20:42:49.000Z | sentry_sdk/integrations/asgi.py | maltalk/sentry-python | 4e346acbabb1fd5592663bf9acd580835236fcf0 | [
"BSD-2-Clause"
] | 340 | 2018-07-16T12:47:27.000Z | 2022-03-22T10:13:21.000Z | """
An ASGI middleware.
Based on Tom Christie's `sentry-asgi <https://github.com/encode/sentry-asgi>`_.
"""
import asyncio
import inspect
import urllib
from sentry_sdk._functools import partial
from sentry_sdk._types import MYPY
from sentry_sdk.hub import Hub, _should_send_default_pii
from sentry_sdk.integrations._wsgi_common import _filter_headers
from sentry_sdk.utils import (
ContextVar,
event_from_exception,
transaction_from_function,
HAS_REAL_CONTEXTVARS,
CONTEXTVARS_ERROR_MESSAGE,
)
from sentry_sdk.tracing import Transaction
if MYPY:
from typing import Dict
from typing import Any
from typing import Optional
from typing import Callable
from typing_extensions import Literal
from sentry_sdk._types import Event, Hint
_asgi_middleware_applied = ContextVar("sentry_asgi_middleware_applied")
_DEFAULT_TRANSACTION_NAME = "generic ASGI request"
def _capture_exception(hub, exc):
# type: (Hub, Any) -> None
# Check client here as it might have been unset while streaming response
if hub.client is not None:
event, hint = event_from_exception(
exc,
client_options=hub.client.options,
mechanism={"type": "asgi", "handled": False},
)
hub.capture_event(event, hint=hint)
def _looks_like_asgi3(app):
# type: (Any) -> bool
"""
Try to figure out if an application object supports ASGI3.
This is how uvicorn figures out the application version as well.
"""
if inspect.isclass(app):
return hasattr(app, "__await__")
elif inspect.isfunction(app):
return asyncio.iscoroutinefunction(app)
else:
call = getattr(app, "__call__", None) # noqa
return asyncio.iscoroutinefunction(call)
class SentryAsgiMiddleware:
__slots__ = ("app", "__call__")
def __init__(self, app, unsafe_context_data=False):
# type: (Any, bool) -> None
"""
Instrument an ASGI application with Sentry. Provides HTTP/websocket
data to sent events and basic handling for exceptions bubbling up
through the middleware.
:param unsafe_context_data: Disable errors when a proper contextvars installation could not be found. We do not recommend changing this from the default.
"""
if not unsafe_context_data and not HAS_REAL_CONTEXTVARS:
# We better have contextvars or we're going to leak state between
# requests.
raise RuntimeError(
"The ASGI middleware for Sentry requires Python 3.7+ "
"or the aiocontextvars package." + CONTEXTVARS_ERROR_MESSAGE
)
self.app = app
if _looks_like_asgi3(app):
self.__call__ = self._run_asgi3 # type: Callable[..., Any]
else:
self.__call__ = self._run_asgi2
def _run_asgi2(self, scope):
# type: (Any) -> Any
async def inner(receive, send):
# type: (Any, Any) -> Any
return await self._run_app(scope, lambda: self.app(scope)(receive, send))
return inner
async def _run_asgi3(self, scope, receive, send):
# type: (Any, Any, Any) -> Any
return await self._run_app(scope, lambda: self.app(scope, receive, send))
async def _run_app(self, scope, callback):
# type: (Any, Any) -> Any
is_recursive_asgi_middleware = _asgi_middleware_applied.get(False)
if is_recursive_asgi_middleware:
try:
return await callback()
except Exception as exc:
_capture_exception(Hub.current, exc)
raise exc from None
_asgi_middleware_applied.set(True)
try:
hub = Hub(Hub.current)
with hub:
with hub.configure_scope() as sentry_scope:
sentry_scope.clear_breadcrumbs()
sentry_scope._name = "asgi"
processor = partial(self.event_processor, asgi_scope=scope)
sentry_scope.add_event_processor(processor)
ty = scope["type"]
if ty in ("http", "websocket"):
transaction = Transaction.continue_from_headers(
self._get_headers(scope),
op="{}.server".format(ty),
)
else:
transaction = Transaction(op="asgi.server")
transaction.name = _DEFAULT_TRANSACTION_NAME
transaction.set_tag("asgi.type", ty)
with hub.start_transaction(
transaction, custom_sampling_context={"asgi_scope": scope}
):
# XXX: Would be cool to have correct span status, but we
# would have to wrap send(). That is a bit hard to do with
# the current abstraction over ASGI 2/3.
try:
return await callback()
except Exception as exc:
_capture_exception(hub, exc)
raise exc from None
finally:
_asgi_middleware_applied.set(False)
def event_processor(self, event, hint, asgi_scope):
# type: (Event, Hint, Any) -> Optional[Event]
request_info = event.get("request", {})
ty = asgi_scope["type"]
if ty in ("http", "websocket"):
request_info["method"] = asgi_scope.get("method")
request_info["headers"] = headers = _filter_headers(
self._get_headers(asgi_scope)
)
request_info["query_string"] = self._get_query(asgi_scope)
request_info["url"] = self._get_url(
asgi_scope, "http" if ty == "http" else "ws", headers.get("host")
)
client = asgi_scope.get("client")
if client and _should_send_default_pii():
request_info["env"] = {"REMOTE_ADDR": self._get_ip(asgi_scope)}
if (
event.get("transaction", _DEFAULT_TRANSACTION_NAME)
== _DEFAULT_TRANSACTION_NAME
):
endpoint = asgi_scope.get("endpoint")
# Webframeworks like Starlette mutate the ASGI env once routing is
# done, which is sometime after the request has started. If we have
# an endpoint, overwrite our generic transaction name.
if endpoint:
event["transaction"] = transaction_from_function(endpoint)
event["request"] = request_info
return event
# Helper functions for extracting request data.
#
# Note: Those functions are not public API. If you want to mutate request
# data to your liking it's recommended to use the `before_send` callback
# for that.
def _get_url(self, scope, default_scheme, host):
# type: (Dict[str, Any], Literal["ws", "http"], Optional[str]) -> str
"""
Extract URL from the ASGI scope, without also including the querystring.
"""
scheme = scope.get("scheme", default_scheme)
server = scope.get("server", None)
path = scope.get("root_path", "") + scope.get("path", "")
if host:
return "%s://%s%s" % (scheme, host, path)
if server is not None:
host, port = server
default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}[scheme]
if port != default_port:
return "%s://%s:%s%s" % (scheme, host, port, path)
return "%s://%s%s" % (scheme, host, path)
return path
def _get_query(self, scope):
# type: (Any) -> Any
"""
Extract querystring from the ASGI scope, in the format that the Sentry protocol expects.
"""
qs = scope.get("query_string")
if not qs:
return None
return urllib.parse.unquote(qs.decode("latin-1"))
def _get_ip(self, scope):
# type: (Any) -> str
"""
Extract IP Address from the ASGI scope based on request headers with fallback to scope client.
"""
headers = self._get_headers(scope)
try:
return headers["x-forwarded-for"].split(",")[0].strip()
except (KeyError, IndexError):
pass
try:
return headers["x-real-ip"]
except KeyError:
pass
return scope.get("client")[0]
def _get_headers(self, scope):
# type: (Any) -> Dict[str, str]
"""
Extract headers from the ASGI scope, in the format that the Sentry protocol expects.
"""
headers = {} # type: Dict[str, str]
for raw_key, raw_value in scope["headers"]:
key = raw_key.decode("latin-1")
value = raw_value.decode("latin-1")
if key in headers:
headers[key] = headers[key] + ", " + value
else:
headers[key] = value
return headers
| 34.507692 | 161 | 0.589835 |
import asyncio
import inspect
import urllib
from sentry_sdk._functools import partial
from sentry_sdk._types import MYPY
from sentry_sdk.hub import Hub, _should_send_default_pii
from sentry_sdk.integrations._wsgi_common import _filter_headers
from sentry_sdk.utils import (
ContextVar,
event_from_exception,
transaction_from_function,
HAS_REAL_CONTEXTVARS,
CONTEXTVARS_ERROR_MESSAGE,
)
from sentry_sdk.tracing import Transaction
if MYPY:
from typing import Dict
from typing import Any
from typing import Optional
from typing import Callable
from typing_extensions import Literal
from sentry_sdk._types import Event, Hint
_asgi_middleware_applied = ContextVar("sentry_asgi_middleware_applied")
_DEFAULT_TRANSACTION_NAME = "generic ASGI request"
def _capture_exception(hub, exc):
if hub.client is not None:
event, hint = event_from_exception(
exc,
client_options=hub.client.options,
mechanism={"type": "asgi", "handled": False},
)
hub.capture_event(event, hint=hint)
def _looks_like_asgi3(app):
if inspect.isclass(app):
return hasattr(app, "__await__")
elif inspect.isfunction(app):
return asyncio.iscoroutinefunction(app)
else:
call = getattr(app, "__call__", None)
return asyncio.iscoroutinefunction(call)
class SentryAsgiMiddleware:
__slots__ = ("app", "__call__")
def __init__(self, app, unsafe_context_data=False):
if not unsafe_context_data and not HAS_REAL_CONTEXTVARS:
# requests.
raise RuntimeError(
"The ASGI middleware for Sentry requires Python 3.7+ "
"or the aiocontextvars package." + CONTEXTVARS_ERROR_MESSAGE
)
self.app = app
if _looks_like_asgi3(app):
self.__call__ = self._run_asgi3 # type: Callable[..., Any]
else:
self.__call__ = self._run_asgi2
def _run_asgi2(self, scope):
# type: (Any) -> Any
async def inner(receive, send):
# type: (Any, Any) -> Any
return await self._run_app(scope, lambda: self.app(scope)(receive, send))
return inner
async def _run_asgi3(self, scope, receive, send):
# type: (Any, Any, Any) -> Any
return await self._run_app(scope, lambda: self.app(scope, receive, send))
async def _run_app(self, scope, callback):
# type: (Any, Any) -> Any
is_recursive_asgi_middleware = _asgi_middleware_applied.get(False)
if is_recursive_asgi_middleware:
try:
return await callback()
except Exception as exc:
_capture_exception(Hub.current, exc)
raise exc from None
_asgi_middleware_applied.set(True)
try:
hub = Hub(Hub.current)
with hub:
with hub.configure_scope() as sentry_scope:
sentry_scope.clear_breadcrumbs()
sentry_scope._name = "asgi"
processor = partial(self.event_processor, asgi_scope=scope)
sentry_scope.add_event_processor(processor)
ty = scope["type"]
if ty in ("http", "websocket"):
transaction = Transaction.continue_from_headers(
self._get_headers(scope),
op="{}.server".format(ty),
)
else:
transaction = Transaction(op="asgi.server")
transaction.name = _DEFAULT_TRANSACTION_NAME
transaction.set_tag("asgi.type", ty)
with hub.start_transaction(
transaction, custom_sampling_context={"asgi_scope": scope}
):
# XXX: Would be cool to have correct span status, but we
# would have to wrap send(). That is a bit hard to do with
# the current abstraction over ASGI 2/3.
try:
return await callback()
except Exception as exc:
_capture_exception(hub, exc)
raise exc from None
finally:
_asgi_middleware_applied.set(False)
def event_processor(self, event, hint, asgi_scope):
# type: (Event, Hint, Any) -> Optional[Event]
request_info = event.get("request", {})
ty = asgi_scope["type"]
if ty in ("http", "websocket"):
request_info["method"] = asgi_scope.get("method")
request_info["headers"] = headers = _filter_headers(
self._get_headers(asgi_scope)
)
request_info["query_string"] = self._get_query(asgi_scope)
request_info["url"] = self._get_url(
asgi_scope, "http" if ty == "http" else "ws", headers.get("host")
)
client = asgi_scope.get("client")
if client and _should_send_default_pii():
request_info["env"] = {"REMOTE_ADDR": self._get_ip(asgi_scope)}
if (
event.get("transaction", _DEFAULT_TRANSACTION_NAME)
== _DEFAULT_TRANSACTION_NAME
):
endpoint = asgi_scope.get("endpoint")
# Webframeworks like Starlette mutate the ASGI env once routing is
# done, which is sometime after the request has started. If we have
# an endpoint, overwrite our generic transaction name.
if endpoint:
event["transaction"] = transaction_from_function(endpoint)
event["request"] = request_info
return event
# Helper functions for extracting request data.
#
# Note: Those functions are not public API. If you want to mutate request
# data to your liking it's recommended to use the `before_send` callback
def _get_url(self, scope, default_scheme, host):
scheme = scope.get("scheme", default_scheme)
server = scope.get("server", None)
path = scope.get("root_path", "") + scope.get("path", "")
if host:
return "%s://%s%s" % (scheme, host, path)
if server is not None:
host, port = server
default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}[scheme]
if port != default_port:
return "%s://%s:%s%s" % (scheme, host, port, path)
return "%s://%s%s" % (scheme, host, path)
return path
def _get_query(self, scope):
qs = scope.get("query_string")
if not qs:
return None
return urllib.parse.unquote(qs.decode("latin-1"))
def _get_ip(self, scope):
headers = self._get_headers(scope)
try:
return headers["x-forwarded-for"].split(",")[0].strip()
except (KeyError, IndexError):
pass
try:
return headers["x-real-ip"]
except KeyError:
pass
return scope.get("client")[0]
def _get_headers(self, scope):
headers = {}
for raw_key, raw_value in scope["headers"]:
key = raw_key.decode("latin-1")
value = raw_value.decode("latin-1")
if key in headers:
headers[key] = headers[key] + ", " + value
else:
headers[key] = value
return headers
| true | true |
f73b85f193f4842955a6156528b9f7c2b37048ca | 1,618 | py | Python | dataPipelines/gc_db_utils/web/utils.py | Wildertrek/gamechanger-data | d087044594c722bd373cce1a48293d1a6da5d24e | [
"MIT"
] | 18 | 2021-04-20T20:34:01.000Z | 2021-11-08T10:28:17.000Z | dataPipelines/gc_db_utils/web/utils.py | Wildertrek/gamechanger-data | d087044594c722bd373cce1a48293d1a6da5d24e | [
"MIT"
] | 15 | 2021-04-20T20:31:33.000Z | 2022-03-18T16:00:44.000Z | dataPipelines/gc_db_utils/web/utils.py | dod-advana/gamechanger-data | 1cdba2a3dbc1072f5991dcfe1daea6310c8ae42b | [
"MIT"
] | 8 | 2021-04-23T11:38:26.000Z | 2021-11-17T22:42:38.000Z | from .models import DeferredWebReflectedBase
from . import PACKAGE_PATH
from pathlib import Path
from typing import Union
import sqlalchemy
def run_sql_file(sql_subpath: Union[str, Path], engine: sqlalchemy.engine.Engine) -> None:
sql_path = Path(PACKAGE_PATH, 'sql', sql_subpath).resolve()
if not sql_path.is_file():
raise ValueError(f"There is no file at path {sql_path!s}")
with sql_path.open("r") as fd:
sql = fd.read()
engine.execute(sql)
def drop_views(engine: sqlalchemy.engine.Engine) -> None:
run_sql_file('drop_views.sql', engine=engine)
def drop_tables(engine: sqlalchemy.engine.Engine) -> None:
run_sql_file('drop_tables.sql', engine=engine)
def create_tables(engine: sqlalchemy.engine.Engine) -> None:
run_sql_file('create_tables.sql', engine=engine)
def create_views(engine: sqlalchemy.engine.Engine) -> None:
run_sql_file('create_views.sql', engine=engine)
def seed_dafa_charter_map(engine: sqlalchemy.engine.Engine) -> None:
run_sql_file('adhoc/seed_dafa_charter_map.sql', engine=engine)
def init_db_bindings(engine: sqlalchemy.engine.Engine) -> None:
DeferredWebReflectedBase.prepare(engine=engine)
def create_tables_and_views(engine: sqlalchemy.engine.Engine) -> None:
create_tables(engine=engine)
create_views(engine=engine)
def drop_tables_and_views(engine: sqlalchemy.engine.Engine) -> None:
drop_tables(engine=engine)
drop_views(engine=engine)
def recreate_tables_and_views(engine: sqlalchemy.engine.Engine) -> None:
drop_tables_and_views(engine=engine)
create_tables_and_views(engine=engine)
| 28.385965 | 90 | 0.756489 | from .models import DeferredWebReflectedBase
from . import PACKAGE_PATH
from pathlib import Path
from typing import Union
import sqlalchemy
def run_sql_file(sql_subpath: Union[str, Path], engine: sqlalchemy.engine.Engine) -> None:
sql_path = Path(PACKAGE_PATH, 'sql', sql_subpath).resolve()
if not sql_path.is_file():
raise ValueError(f"There is no file at path {sql_path!s}")
with sql_path.open("r") as fd:
sql = fd.read()
engine.execute(sql)
def drop_views(engine: sqlalchemy.engine.Engine) -> None:
run_sql_file('drop_views.sql', engine=engine)
def drop_tables(engine: sqlalchemy.engine.Engine) -> None:
run_sql_file('drop_tables.sql', engine=engine)
def create_tables(engine: sqlalchemy.engine.Engine) -> None:
run_sql_file('create_tables.sql', engine=engine)
def create_views(engine: sqlalchemy.engine.Engine) -> None:
run_sql_file('create_views.sql', engine=engine)
def seed_dafa_charter_map(engine: sqlalchemy.engine.Engine) -> None:
run_sql_file('adhoc/seed_dafa_charter_map.sql', engine=engine)
def init_db_bindings(engine: sqlalchemy.engine.Engine) -> None:
DeferredWebReflectedBase.prepare(engine=engine)
def create_tables_and_views(engine: sqlalchemy.engine.Engine) -> None:
create_tables(engine=engine)
create_views(engine=engine)
def drop_tables_and_views(engine: sqlalchemy.engine.Engine) -> None:
drop_tables(engine=engine)
drop_views(engine=engine)
def recreate_tables_and_views(engine: sqlalchemy.engine.Engine) -> None:
drop_tables_and_views(engine=engine)
create_tables_and_views(engine=engine)
| true | true |
f73b86f9e4cc03edff393d41811d7d010c0f56c4 | 14,530 | py | Python | env/Lib/site-packages/plotly/validators/scatter/marker/_symbol.py | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | 8a4707301d19c3826c31026c4077930bcd6a8182 | [
"MIT"
] | 11,750 | 2015-10-12T07:03:39.000Z | 2022-03-31T20:43:15.000Z | env/Lib/site-packages/plotly/validators/scatter/marker/_symbol.py | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | 8a4707301d19c3826c31026c4077930bcd6a8182 | [
"MIT"
] | 2,951 | 2015-10-12T00:41:25.000Z | 2022-03-31T22:19:26.000Z | env/Lib/site-packages/plotly/validators/scatter/marker/_symbol.py | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | 8a4707301d19c3826c31026c4077930bcd6a8182 | [
"MIT"
] | 2,623 | 2015-10-15T14:40:27.000Z | 2022-03-28T16:05:50.000Z | import _plotly_utils.basevalidators
class SymbolValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="symbol", parent_name="scatter.marker", **kwargs):
super(SymbolValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.pop("edit_type", "style"),
values=kwargs.pop(
"values",
[
0,
"0",
"circle",
100,
"100",
"circle-open",
200,
"200",
"circle-dot",
300,
"300",
"circle-open-dot",
1,
"1",
"square",
101,
"101",
"square-open",
201,
"201",
"square-dot",
301,
"301",
"square-open-dot",
2,
"2",
"diamond",
102,
"102",
"diamond-open",
202,
"202",
"diamond-dot",
302,
"302",
"diamond-open-dot",
3,
"3",
"cross",
103,
"103",
"cross-open",
203,
"203",
"cross-dot",
303,
"303",
"cross-open-dot",
4,
"4",
"x",
104,
"104",
"x-open",
204,
"204",
"x-dot",
304,
"304",
"x-open-dot",
5,
"5",
"triangle-up",
105,
"105",
"triangle-up-open",
205,
"205",
"triangle-up-dot",
305,
"305",
"triangle-up-open-dot",
6,
"6",
"triangle-down",
106,
"106",
"triangle-down-open",
206,
"206",
"triangle-down-dot",
306,
"306",
"triangle-down-open-dot",
7,
"7",
"triangle-left",
107,
"107",
"triangle-left-open",
207,
"207",
"triangle-left-dot",
307,
"307",
"triangle-left-open-dot",
8,
"8",
"triangle-right",
108,
"108",
"triangle-right-open",
208,
"208",
"triangle-right-dot",
308,
"308",
"triangle-right-open-dot",
9,
"9",
"triangle-ne",
109,
"109",
"triangle-ne-open",
209,
"209",
"triangle-ne-dot",
309,
"309",
"triangle-ne-open-dot",
10,
"10",
"triangle-se",
110,
"110",
"triangle-se-open",
210,
"210",
"triangle-se-dot",
310,
"310",
"triangle-se-open-dot",
11,
"11",
"triangle-sw",
111,
"111",
"triangle-sw-open",
211,
"211",
"triangle-sw-dot",
311,
"311",
"triangle-sw-open-dot",
12,
"12",
"triangle-nw",
112,
"112",
"triangle-nw-open",
212,
"212",
"triangle-nw-dot",
312,
"312",
"triangle-nw-open-dot",
13,
"13",
"pentagon",
113,
"113",
"pentagon-open",
213,
"213",
"pentagon-dot",
313,
"313",
"pentagon-open-dot",
14,
"14",
"hexagon",
114,
"114",
"hexagon-open",
214,
"214",
"hexagon-dot",
314,
"314",
"hexagon-open-dot",
15,
"15",
"hexagon2",
115,
"115",
"hexagon2-open",
215,
"215",
"hexagon2-dot",
315,
"315",
"hexagon2-open-dot",
16,
"16",
"octagon",
116,
"116",
"octagon-open",
216,
"216",
"octagon-dot",
316,
"316",
"octagon-open-dot",
17,
"17",
"star",
117,
"117",
"star-open",
217,
"217",
"star-dot",
317,
"317",
"star-open-dot",
18,
"18",
"hexagram",
118,
"118",
"hexagram-open",
218,
"218",
"hexagram-dot",
318,
"318",
"hexagram-open-dot",
19,
"19",
"star-triangle-up",
119,
"119",
"star-triangle-up-open",
219,
"219",
"star-triangle-up-dot",
319,
"319",
"star-triangle-up-open-dot",
20,
"20",
"star-triangle-down",
120,
"120",
"star-triangle-down-open",
220,
"220",
"star-triangle-down-dot",
320,
"320",
"star-triangle-down-open-dot",
21,
"21",
"star-square",
121,
"121",
"star-square-open",
221,
"221",
"star-square-dot",
321,
"321",
"star-square-open-dot",
22,
"22",
"star-diamond",
122,
"122",
"star-diamond-open",
222,
"222",
"star-diamond-dot",
322,
"322",
"star-diamond-open-dot",
23,
"23",
"diamond-tall",
123,
"123",
"diamond-tall-open",
223,
"223",
"diamond-tall-dot",
323,
"323",
"diamond-tall-open-dot",
24,
"24",
"diamond-wide",
124,
"124",
"diamond-wide-open",
224,
"224",
"diamond-wide-dot",
324,
"324",
"diamond-wide-open-dot",
25,
"25",
"hourglass",
125,
"125",
"hourglass-open",
26,
"26",
"bowtie",
126,
"126",
"bowtie-open",
27,
"27",
"circle-cross",
127,
"127",
"circle-cross-open",
28,
"28",
"circle-x",
128,
"128",
"circle-x-open",
29,
"29",
"square-cross",
129,
"129",
"square-cross-open",
30,
"30",
"square-x",
130,
"130",
"square-x-open",
31,
"31",
"diamond-cross",
131,
"131",
"diamond-cross-open",
32,
"32",
"diamond-x",
132,
"132",
"diamond-x-open",
33,
"33",
"cross-thin",
133,
"133",
"cross-thin-open",
34,
"34",
"x-thin",
134,
"134",
"x-thin-open",
35,
"35",
"asterisk",
135,
"135",
"asterisk-open",
36,
"36",
"hash",
136,
"136",
"hash-open",
236,
"236",
"hash-dot",
336,
"336",
"hash-open-dot",
37,
"37",
"y-up",
137,
"137",
"y-up-open",
38,
"38",
"y-down",
138,
"138",
"y-down-open",
39,
"39",
"y-left",
139,
"139",
"y-left-open",
40,
"40",
"y-right",
140,
"140",
"y-right-open",
41,
"41",
"line-ew",
141,
"141",
"line-ew-open",
42,
"42",
"line-ns",
142,
"142",
"line-ns-open",
43,
"43",
"line-ne",
143,
"143",
"line-ne-open",
44,
"44",
"line-nw",
144,
"144",
"line-nw-open",
45,
"45",
"arrow-up",
145,
"145",
"arrow-up-open",
46,
"46",
"arrow-down",
146,
"146",
"arrow-down-open",
47,
"47",
"arrow-left",
147,
"147",
"arrow-left-open",
48,
"48",
"arrow-right",
148,
"148",
"arrow-right-open",
49,
"49",
"arrow-bar-up",
149,
"149",
"arrow-bar-up-open",
50,
"50",
"arrow-bar-down",
150,
"150",
"arrow-bar-down-open",
51,
"51",
"arrow-bar-left",
151,
"151",
"arrow-bar-left-open",
52,
"52",
"arrow-bar-right",
152,
"152",
"arrow-bar-right-open",
],
),
**kwargs
)
| 29.53252 | 85 | 0.205024 | import _plotly_utils.basevalidators
class SymbolValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="symbol", parent_name="scatter.marker", **kwargs):
super(SymbolValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.pop("edit_type", "style"),
values=kwargs.pop(
"values",
[
0,
"0",
"circle",
100,
"100",
"circle-open",
200,
"200",
"circle-dot",
300,
"300",
"circle-open-dot",
1,
"1",
"square",
101,
"101",
"square-open",
201,
"201",
"square-dot",
301,
"301",
"square-open-dot",
2,
"2",
"diamond",
102,
"102",
"diamond-open",
202,
"202",
"diamond-dot",
302,
"302",
"diamond-open-dot",
3,
"3",
"cross",
103,
"103",
"cross-open",
203,
"203",
"cross-dot",
303,
"303",
"cross-open-dot",
4,
"4",
"x",
104,
"104",
"x-open",
204,
"204",
"x-dot",
304,
"304",
"x-open-dot",
5,
"5",
"triangle-up",
105,
"105",
"triangle-up-open",
205,
"205",
"triangle-up-dot",
305,
"305",
"triangle-up-open-dot",
6,
"6",
"triangle-down",
106,
"106",
"triangle-down-open",
206,
"206",
"triangle-down-dot",
306,
"306",
"triangle-down-open-dot",
7,
"7",
"triangle-left",
107,
"107",
"triangle-left-open",
207,
"207",
"triangle-left-dot",
307,
"307",
"triangle-left-open-dot",
8,
"8",
"triangle-right",
108,
"108",
"triangle-right-open",
208,
"208",
"triangle-right-dot",
308,
"308",
"triangle-right-open-dot",
9,
"9",
"triangle-ne",
109,
"109",
"triangle-ne-open",
209,
"209",
"triangle-ne-dot",
309,
"309",
"triangle-ne-open-dot",
10,
"10",
"triangle-se",
110,
"110",
"triangle-se-open",
210,
"210",
"triangle-se-dot",
310,
"310",
"triangle-se-open-dot",
11,
"11",
"triangle-sw",
111,
"111",
"triangle-sw-open",
211,
"211",
"triangle-sw-dot",
311,
"311",
"triangle-sw-open-dot",
12,
"12",
"triangle-nw",
112,
"112",
"triangle-nw-open",
212,
"212",
"triangle-nw-dot",
312,
"312",
"triangle-nw-open-dot",
13,
"13",
"pentagon",
113,
"113",
"pentagon-open",
213,
"213",
"pentagon-dot",
313,
"313",
"pentagon-open-dot",
14,
"14",
"hexagon",
114,
"114",
"hexagon-open",
214,
"214",
"hexagon-dot",
314,
"314",
"hexagon-open-dot",
15,
"15",
"hexagon2",
115,
"115",
"hexagon2-open",
215,
"215",
"hexagon2-dot",
315,
"315",
"hexagon2-open-dot",
16,
"16",
"octagon",
116,
"116",
"octagon-open",
216,
"216",
"octagon-dot",
316,
"316",
"octagon-open-dot",
17,
"17",
"star",
117,
"117",
"star-open",
217,
"217",
"star-dot",
317,
"317",
"star-open-dot",
18,
"18",
"hexagram",
118,
"118",
"hexagram-open",
218,
"218",
"hexagram-dot",
318,
"318",
"hexagram-open-dot",
19,
"19",
"star-triangle-up",
119,
"119",
"star-triangle-up-open",
219,
"219",
"star-triangle-up-dot",
319,
"319",
"star-triangle-up-open-dot",
20,
"20",
"star-triangle-down",
120,
"120",
"star-triangle-down-open",
220,
"220",
"star-triangle-down-dot",
320,
"320",
"star-triangle-down-open-dot",
21,
"21",
"star-square",
121,
"121",
"star-square-open",
221,
"221",
"star-square-dot",
321,
"321",
"star-square-open-dot",
22,
"22",
"star-diamond",
122,
"122",
"star-diamond-open",
222,
"222",
"star-diamond-dot",
322,
"322",
"star-diamond-open-dot",
23,
"23",
"diamond-tall",
123,
"123",
"diamond-tall-open",
223,
"223",
"diamond-tall-dot",
323,
"323",
"diamond-tall-open-dot",
24,
"24",
"diamond-wide",
124,
"124",
"diamond-wide-open",
224,
"224",
"diamond-wide-dot",
324,
"324",
"diamond-wide-open-dot",
25,
"25",
"hourglass",
125,
"125",
"hourglass-open",
26,
"26",
"bowtie",
126,
"126",
"bowtie-open",
27,
"27",
"circle-cross",
127,
"127",
"circle-cross-open",
28,
"28",
"circle-x",
128,
"128",
"circle-x-open",
29,
"29",
"square-cross",
129,
"129",
"square-cross-open",
30,
"30",
"square-x",
130,
"130",
"square-x-open",
31,
"31",
"diamond-cross",
131,
"131",
"diamond-cross-open",
32,
"32",
"diamond-x",
132,
"132",
"diamond-x-open",
33,
"33",
"cross-thin",
133,
"133",
"cross-thin-open",
34,
"34",
"x-thin",
134,
"134",
"x-thin-open",
35,
"35",
"asterisk",
135,
"135",
"asterisk-open",
36,
"36",
"hash",
136,
"136",
"hash-open",
236,
"236",
"hash-dot",
336,
"336",
"hash-open-dot",
37,
"37",
"y-up",
137,
"137",
"y-up-open",
38,
"38",
"y-down",
138,
"138",
"y-down-open",
39,
"39",
"y-left",
139,
"139",
"y-left-open",
40,
"40",
"y-right",
140,
"140",
"y-right-open",
41,
"41",
"line-ew",
141,
"141",
"line-ew-open",
42,
"42",
"line-ns",
142,
"142",
"line-ns-open",
43,
"43",
"line-ne",
143,
"143",
"line-ne-open",
44,
"44",
"line-nw",
144,
"144",
"line-nw-open",
45,
"45",
"arrow-up",
145,
"145",
"arrow-up-open",
46,
"46",
"arrow-down",
146,
"146",
"arrow-down-open",
47,
"47",
"arrow-left",
147,
"147",
"arrow-left-open",
48,
"48",
"arrow-right",
148,
"148",
"arrow-right-open",
49,
"49",
"arrow-bar-up",
149,
"149",
"arrow-bar-up-open",
50,
"50",
"arrow-bar-down",
150,
"150",
"arrow-bar-down-open",
51,
"51",
"arrow-bar-left",
151,
"151",
"arrow-bar-left-open",
52,
"52",
"arrow-bar-right",
152,
"152",
"arrow-bar-right-open",
],
),
**kwargs
)
| true | true |
f73b87003f1f33b5c18fe3c26ca7dde6b9e2dc4f | 488 | py | Python | fluent_contents/plugins/text/__init__.py | django-fluent/django-fluent-contents | 5577567303d29b56fd48128c22c7dc5d8b2c7476 | [
"Apache-2.0"
] | 82 | 2016-07-21T08:43:47.000Z | 2021-12-21T09:23:42.000Z | fluent_contents/plugins/text/__init__.py | edoburu/django-fluent-contents | 5577567303d29b56fd48128c22c7dc5d8b2c7476 | [
"Apache-2.0"
] | 47 | 2015-01-30T22:08:12.000Z | 2016-05-30T16:18:17.000Z | fluent_contents/plugins/text/__init__.py | django-fluent/django-fluent-contents | 5577567303d29b56fd48128c22c7dc5d8b2c7476 | [
"Apache-2.0"
] | 17 | 2016-09-03T05:38:52.000Z | 2020-10-04T03:19:16.000Z | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
VERSION = (0, 1)
backendapp = "django_wysiwyg"
# Do some settings checks.
if backendapp not in settings.INSTALLED_APPS:
raise ImproperlyConfigured(
"The '{}' application is required to use the '{}' plugin.".format(backendapp, "text")
)
try:
import django_wysiwyg
except ImportError:
raise ImportError("The 'django-wysiwyg' package is required to use the 'text' plugin.")
| 27.111111 | 93 | 0.737705 | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
VERSION = (0, 1)
backendapp = "django_wysiwyg"
if backendapp not in settings.INSTALLED_APPS:
raise ImproperlyConfigured(
"The '{}' application is required to use the '{}' plugin.".format(backendapp, "text")
)
try:
import django_wysiwyg
except ImportError:
raise ImportError("The 'django-wysiwyg' package is required to use the 'text' plugin.")
| true | true |
f73b8744aad621c83bc30689bd82deaa31835a32 | 1,614 | py | Python | ZeroMQ/filecode/examples/Python/lvcache.py | JailbreakFox/LightWeightRepository | 710dc8cacf934930b8f91b2cfe93cba0f1765094 | [
"BSD-2-Clause"
] | null | null | null | ZeroMQ/filecode/examples/Python/lvcache.py | JailbreakFox/LightWeightRepository | 710dc8cacf934930b8f91b2cfe93cba0f1765094 | [
"BSD-2-Clause"
] | null | null | null | ZeroMQ/filecode/examples/Python/lvcache.py | JailbreakFox/LightWeightRepository | 710dc8cacf934930b8f91b2cfe93cba0f1765094 | [
"BSD-2-Clause"
] | null | null | null | #
# Last value cache
# Uses XPUB subscription messages to re-send data
#
import zmq
def main():
ctx = zmq.Context.instance()
frontend = ctx.socket(zmq.SUB)
frontend.connect("tcp://*:5557")
backend = ctx.socket(zmq.XPUB)
backend.bind("tcp://*:5558")
# Subscribe to every single topic from publisher
frontend.setsockopt(zmq.SUBSCRIBE, b"")
# Store last instance of each topic in a cache
cache = {}
# main poll loop
# We route topic updates from frontend to backend, and
# we handle subscriptions by sending whatever we cached,
# if anything:
poller = zmq.Poller()
poller.register(frontend, zmq.POLLIN)
poller.register(backend, zmq.POLLIN)
while True:
try:
events = dict(poller.poll(1000))
except KeyboardInterrupt:
print("interrupted")
break
# Any new topic data we cache and then forward
if frontend in events:
msg = frontend.recv_multipart()
topic, current = msg
cache[topic] = current
backend.send_multipart(msg)
# handle subscriptions
# When we get a new subscription we pull data from the cache:
if backend in events:
event = backend.recv()
# Event is one byte 0=unsub or 1=sub, followed by topic
if event[0] == b'\x01':
topic = event[1:]
if topic in cache:
print ("Sending cached topic %s" % topic)
backend.send_multipart([ topic, cache[topic] ])
if __name__ == '__main__':
main()
| 28.821429 | 69 | 0.591698 |
import zmq
def main():
ctx = zmq.Context.instance()
frontend = ctx.socket(zmq.SUB)
frontend.connect("tcp://*:5557")
backend = ctx.socket(zmq.XPUB)
backend.bind("tcp://*:5558")
frontend.setsockopt(zmq.SUBSCRIBE, b"")
cache = {}
poller = zmq.Poller()
poller.register(frontend, zmq.POLLIN)
poller.register(backend, zmq.POLLIN)
while True:
try:
events = dict(poller.poll(1000))
except KeyboardInterrupt:
print("interrupted")
break
if frontend in events:
msg = frontend.recv_multipart()
topic, current = msg
cache[topic] = current
backend.send_multipart(msg)
if backend in events:
event = backend.recv()
if event[0] == b'\x01':
topic = event[1:]
if topic in cache:
print ("Sending cached topic %s" % topic)
backend.send_multipart([ topic, cache[topic] ])
if __name__ == '__main__':
main()
| true | true |
f73b88263949c93addcd12986f8a49907e56b18c | 4,850 | py | Python | vibe-scraper/vibedb.py | floflo2607/anidb-anime-scraper | de9898069b4cfa51b6e231104a1f283d42130ad5 | [
"Apache-2.0"
] | null | null | null | vibe-scraper/vibedb.py | floflo2607/anidb-anime-scraper | de9898069b4cfa51b6e231104a1f283d42130ad5 | [
"Apache-2.0"
] | null | null | null | vibe-scraper/vibedb.py | floflo2607/anidb-anime-scraper | de9898069b4cfa51b6e231104a1f283d42130ad5 | [
"Apache-2.0"
] | null | null | null | # ####################################################################################################################################################
# ______ _______ _______ _ _______ _______ _ _______ _______ ______ _____
# ( __ \ ( ___ ) ( ____ ) | \ /\ ( ____ \ ( ___ ) |\ /| ( \ / ___ ) ( __ ) / ____ \ / ___ \
# | ( \ ) | ( ) | | ( )| | \ / / | ( \/ | ( ) | | ) ( | | ( \/ ) | | ( ) | ( ( \/ ( ( ) )
# | | ) | | (___) | | (____)| | (_/ / | (_____ | | | | | | | | | | / ) | | / | | (____ ( (___) |
# | | | | | ___ | | __) | _ ( (_____ ) | | | | | | | | | | _/ / | (/ /) | | ___ \ \____ |
# | | ) | | ( ) | | (\ ( | ( \ \ ) | | | | | | | | | | | / _/ | / | | | ( ) ) ) |
# | (__/ ) | ) ( | | ) \ \__ | / \ \ /\____) | | (___) | | (___) | | (____/\ ( (__/\ | (__) | ( (___) ) /\____) )
# (______/ |/ \| |/ \__/ |_/ \/ \_______) (_______) (_______) (_______/ \_______/ (_______) \_____/ \______/
# ################################### VIBE SCRAPER - (ANIDB.NET SCRAPER) BY (darksoul2069@gmail.com) ##########################################
import requests
import re
from bs4 import BeautifulSoup
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} #User Agent cuz we are trynna scrape a site and the site will automatically block bots n stuff so u need this to bypass any kinda of blocked response
print('==============================================' + '\n' + 'This Anime Scraper [for AniDB.net (http://anidb.net)] (Project/Scraper) was made by darksoul2069 if you face any problem you can mail me- "darksoul2069@gmail.com"' + '\n' + 'Hope you loved this python program/scraper!' + '\n' + 'Check out my anime site http://AnimeVibe.ml' + '\n' + '==============================================' + '\n')
url = input("Enter AniDB.net URL of the Anime you want to scrape/crawl (Example : https://anidb.net/perl-bin/animedb.pl?show=anime&aid=69) : " )
source_code = requests.get(url, headers=headers) #requesting the site's page source...
plain_text = source_code.text #turning the source code to a readable format :P
soup = BeautifulSoup(plain_text, "html.parser") #parsing the page source code...
anime_name = soup.find("h1", {"class": "anime"}) #fetching the anime title
anime_desc = soup.find("div", {"itemprop": "description"}) # fetching the summary/description.
episodes = soup.find_all("td", {"class": "title name episode"}) # getting the place where the episode titles are kept (here the episode titles are in a table)
image = soup.find_all('div',{"class": "g_section info"}) #getting div for getting the image source
img = soup.find('img',{"itemprop": "image"}) # getting the precise location of the animes cover.
lol = img.get('src') # getting the animes image url
# well everything is pretty easy to grasp and understandable until now xD
anim = anime_name.text.strip() # Getting the text as a string out of the html tag we grabbed as a whole
print(anim)
anim = input("Give The File Name where you want to store the Anime Information (Anime Name): ") #Taking File name from the user as input
anim_desc = anime_desc.text.strip() # Stripping out the text from the html tags
max_num = int(input('Total or Number of Episodes to Fetch (Should be a number): ')) #letting user input the number of episodes to grab (titles only)
for i in range(max_num): #Setting a range to grab the lists of episode titles
episode = episodes[i].find("label", {"itemprop": "name"}) #Grabbing the Episode Titles
print(f'Fetched- Episode {i+1}')
with open(anim+".txt", "w") as f: #Writing it to a text file
f.write('==============================================================' + '\n' + '|||Vibe Scraper|||darksoul2069|||AniDB.net|||'+'\n'+'Thank you for using Vibe Scraper for AniDB.net'+'\n'+'||| http://AnimeVibe.xyz |||' + '\n' + '==============================================================' + "\n" + 'Anime Name - ' + anim + "\n" + 'Poster/Image URL of ' + anim + ' - ' + lol + '\n')
f.write('------------------' + "\n")
f.write('Anime Description: ' + '\n' + '------------------' + "\n" + "\n" + anim_desc+"\n"+"\n")
f.write('------------' + "\n" + 'Episode List' + "\n" + '------------' + "\n")
for i in range(max_num):
episode = episodes[i].find("label", {"itemprop": "name"})
f.write('Episode ' + str(i+1) + ':' + ' ' + episode.text.strip() + "\n")
print('\n' + '============================' + '\n' + 'Anime Information/Episodes is stored in ||"' + str(anim) + '.txt"||' + '\n' + '============================')
# AND YOU ARE DONE xD | ENJOY :/
| 97 | 404 | 0.499175 | true | true | |
f73b88fb9618004b2fd6a77b32afeafff1b37b33 | 3,334 | py | Python | sdk/python/pulumi_aws/get_billing_service_account.py | sibuthomasmathew/pulumi-aws | 6351f2182eb6f693d4e09e4136c385adfa0ab674 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_aws/get_billing_service_account.py | sibuthomasmathew/pulumi-aws | 6351f2182eb6f693d4e09e4136c385adfa0ab674 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_aws/get_billing_service_account.py | sibuthomasmathew/pulumi-aws | 6351f2182eb6f693d4e09e4136c385adfa0ab674 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from . import _utilities, _tables
__all__ = [
'GetBillingServiceAccountResult',
'AwaitableGetBillingServiceAccountResult',
'get_billing_service_account',
]
@pulumi.output_type
class GetBillingServiceAccountResult:
"""
A collection of values returned by getBillingServiceAccount.
"""
def __init__(__self__, arn=None, id=None):
if arn and not isinstance(arn, str):
raise TypeError("Expected argument 'arn' to be a str")
pulumi.set(__self__, "arn", arn)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
@property
@pulumi.getter
def arn(self) -> str:
"""
The ARN of the AWS billing service account.
"""
return pulumi.get(self, "arn")
@property
@pulumi.getter
def id(self) -> str:
"""
The provider-assigned unique ID for this managed resource.
"""
return pulumi.get(self, "id")
class AwaitableGetBillingServiceAccountResult(GetBillingServiceAccountResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetBillingServiceAccountResult(
arn=self.arn,
id=self.id)
def get_billing_service_account(opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetBillingServiceAccountResult:
"""
Use this data source to get the Account ID of the [AWS Billing and Cost Management Service Account](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-getting-started.html#step-2) for the purpose of permitting in S3 bucket policy.
## Example Usage
```python
import pulumi
import pulumi_aws as aws
main = aws.get_billing_service_account()
billing_logs = aws.s3.Bucket("billingLogs",
acl="private",
policy=f\"\"\"{{
"Id": "Policy",
"Version": "2012-10-17",
"Statement": [
{{
"Action": [
"s3:GetBucketAcl", "s3:GetBucketPolicy"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::my-billing-tf-test-bucket",
"Principal": {{
"AWS": [
"{main.arn}"
]
}}
}},
{{
"Action": [
"s3:PutObject"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::my-billing-tf-test-bucket/*",
"Principal": {{
"AWS": [
"{main.arn}"
]
}}
}}
]
}}
\"\"\")
```
"""
__args__ = dict()
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('aws:index/getBillingServiceAccount:getBillingServiceAccount', __args__, opts=opts, typ=GetBillingServiceAccountResult).value
return AwaitableGetBillingServiceAccountResult(
arn=__ret__.arn,
id=__ret__.id)
| 29.245614 | 251 | 0.602579 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from . import _utilities, _tables
__all__ = [
'GetBillingServiceAccountResult',
'AwaitableGetBillingServiceAccountResult',
'get_billing_service_account',
]
@pulumi.output_type
class GetBillingServiceAccountResult:
def __init__(__self__, arn=None, id=None):
if arn and not isinstance(arn, str):
raise TypeError("Expected argument 'arn' to be a str")
pulumi.set(__self__, "arn", arn)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
@property
@pulumi.getter
def arn(self) -> str:
return pulumi.get(self, "arn")
@property
@pulumi.getter
def id(self) -> str:
return pulumi.get(self, "id")
class AwaitableGetBillingServiceAccountResult(GetBillingServiceAccountResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetBillingServiceAccountResult(
arn=self.arn,
id=self.id)
def get_billing_service_account(opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetBillingServiceAccountResult:
__args__ = dict()
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('aws:index/getBillingServiceAccount:getBillingServiceAccount', __args__, opts=opts, typ=GetBillingServiceAccountResult).value
return AwaitableGetBillingServiceAccountResult(
arn=__ret__.arn,
id=__ret__.id)
| true | true |
f73b8afeaec08209fb9a1f4a90a2f80e291bc648 | 6,359 | py | Python | datatableview/views/xeditable.py | gregneagle/sal | 74c583fb1c1b33d3201b308b147376b3dcaca33f | [
"Apache-2.0"
] | 2 | 2019-11-01T20:50:35.000Z | 2021-01-13T22:02:55.000Z | datatableview/views/xeditable.py | gregneagle/sal | 74c583fb1c1b33d3201b308b147376b3dcaca33f | [
"Apache-2.0"
] | null | null | null | datatableview/views/xeditable.py | gregneagle/sal | 74c583fb1c1b33d3201b308b147376b3dcaca33f | [
"Apache-2.0"
] | null | null | null | # -*- encoding: utf-8 -*-
import json
import re
import operator
import logging
from ..forms import XEditableUpdateForm
from .base import DatatableView
from django import get_version
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import ensure_csrf_cookie
from django.db.models import ForeignKey
log = logging.getLogger(__name__)
CAN_UPDATE_FIELDS = get_version().split('.') >= ['1', '5']
class XEditableMixin(object):
xeditable_form_class = XEditableUpdateForm
xeditable_fieldname_param = 'xeditable_field' # GET parameter name used for choices ajax
def get(self, request, *args, **kwargs):
""" Introduces the ``ensure_csrf_cookie`` decorator and handles xeditable choices ajax. """
if request.GET.get(self.xeditable_fieldname_param):
return self.get_ajax_xeditable_choices(request, *args, **kwargs)
# Doing this in the method body at runtime instead of at declaration-time helps prevent
# collisions of other subclasses also trying to decorate their own get() methods.
method = super(XEditableMixin, self).get
method = ensure_csrf_cookie(method)
return method(request, *args, **kwargs)
def get_ajax_xeditable_choices(self, request, *args, **kwargs):
""" AJAX GET handler for xeditable queries asking for field choice lists. """
field_name = request.GET.get(self.xeditable_fieldname_param)
if not field_name:
return HttpResponseBadRequest("Field name must be given")
queryset = self.get_queryset()
if not self.model:
self.model = queryset.model
# Sanitize the requested field name by limiting valid names to the datatable_options columns
from datatableview.views import legacy
if isinstance(self, legacy.LegacyDatatableMixin):
columns = self._get_datatable_options()['columns']
for name in columns:
if isinstance(name, (list, tuple)):
name = name[1]
if name == field_name:
break
else:
return HttpResponseBadRequest("Invalid field name")
else:
if field_name not in self.get_datatable().config['columns']:
return HttpResponseBadRequest("Invalid field name")
field = self.model._meta.get_field_by_name(field_name)[0]
choices = self.get_field_choices(field, field_name)
return HttpResponse(json.dumps(choices))
def post(self, request, *args, **kwargs):
"""
Builds a dynamic form that targets only the field in question, and saves the modification.
"""
self.object_list = None
form = self.get_xeditable_form(self.get_xeditable_form_class())
if form.is_valid():
obj = self.get_update_object(form)
if obj is None:
data = json.dumps({
'status': 'error',
'message': "Object does not exist."
})
return HttpResponse(data, content_type="application/json", status=404)
return self.update_object(form, obj)
else:
data = json.dumps({
'status': 'error',
'message': "Invalid request",
'form_errors': form.errors,
})
return HttpResponse(data, content_type="application/json", status=400)
def get_xeditable_form_class(self):
""" Returns ``self.xeditable_form_class``. """
return self.xeditable_form_class
def get_xeditable_form_kwargs(self):
""" Returns a dict of keyword arguments to be sent to the xeditable form class. """
kwargs = {
'model': self.get_queryset().model,
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.request.POST,
})
return kwargs
def get_xeditable_form(self, form_class):
""" Builds xeditable form computed from :py:meth:`.get_xeditable_form_class`. """
return form_class(**self.get_xeditable_form_kwargs())
def get_update_object(self, form):
"""
Retrieves the target object based on the update form's ``pk`` and the table's queryset.
"""
pk = form.cleaned_data['pk']
queryset = self.get_queryset()
try:
obj = queryset.get(pk=pk)
except queryset.model.DoesNotExist:
obj = None
return obj
def update_object(self, form, obj):
""" Saves the new value to the target object. """
field_name = form.cleaned_data['name']
value = form.cleaned_data['value']
setattr(obj, field_name, value)
save_kwargs = {}
if CAN_UPDATE_FIELDS:
save_kwargs['update_fields'] = [field_name]
obj.save(**save_kwargs)
data = json.dumps({
'status': 'success',
})
return HttpResponse(data, content_type="application/json")
def get_field_choices(self, field, field_name):
"""
Returns the valid choices for ``field``. The ``field_name`` argument is given for
convenience.
"""
if self.request.GET.get('select2'):
names = ['id', 'text']
else:
names = ['value', 'text']
choices_getter = getattr(self, 'get_field_%s_choices', None)
if choices_getter is None:
if isinstance(field, ForeignKey):
choices_getter = self._get_foreignkey_choices
else:
choices_getter = self._get_default_choices
return [dict(zip(names, choice)) for choice in choices_getter(field, field_name)]
def _get_foreignkey_choices(self, field, field_name):
formfield_kwargs = {}
if not field.blank:
# Explicitly remove empty choice, since formfield isn't working with instance data and
# will consequently try to assume initial=None, forcing the blank option to appear.
formfield_kwargs['empty_label'] = None
formfield = field.formfield(**formfield_kwargs)
return formfield.choices
def _get_default_choices(self, field, field_name):
return field.choices
class XEditableDatatableView(XEditableMixin, DatatableView):
pass
| 37.627219 | 100 | 0.626356 |
import json
import re
import operator
import logging
from ..forms import XEditableUpdateForm
from .base import DatatableView
from django import get_version
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import ensure_csrf_cookie
from django.db.models import ForeignKey
log = logging.getLogger(__name__)
CAN_UPDATE_FIELDS = get_version().split('.') >= ['1', '5']
class XEditableMixin(object):
xeditable_form_class = XEditableUpdateForm
xeditable_fieldname_param = 'xeditable_field'
def get(self, request, *args, **kwargs):
if request.GET.get(self.xeditable_fieldname_param):
return self.get_ajax_xeditable_choices(request, *args, **kwargs)
method = super(XEditableMixin, self).get
method = ensure_csrf_cookie(method)
return method(request, *args, **kwargs)
def get_ajax_xeditable_choices(self, request, *args, **kwargs):
field_name = request.GET.get(self.xeditable_fieldname_param)
if not field_name:
return HttpResponseBadRequest("Field name must be given")
queryset = self.get_queryset()
if not self.model:
self.model = queryset.model
from datatableview.views import legacy
if isinstance(self, legacy.LegacyDatatableMixin):
columns = self._get_datatable_options()['columns']
for name in columns:
if isinstance(name, (list, tuple)):
name = name[1]
if name == field_name:
break
else:
return HttpResponseBadRequest("Invalid field name")
else:
if field_name not in self.get_datatable().config['columns']:
return HttpResponseBadRequest("Invalid field name")
field = self.model._meta.get_field_by_name(field_name)[0]
choices = self.get_field_choices(field, field_name)
return HttpResponse(json.dumps(choices))
def post(self, request, *args, **kwargs):
self.object_list = None
form = self.get_xeditable_form(self.get_xeditable_form_class())
if form.is_valid():
obj = self.get_update_object(form)
if obj is None:
data = json.dumps({
'status': 'error',
'message': "Object does not exist."
})
return HttpResponse(data, content_type="application/json", status=404)
return self.update_object(form, obj)
else:
data = json.dumps({
'status': 'error',
'message': "Invalid request",
'form_errors': form.errors,
})
return HttpResponse(data, content_type="application/json", status=400)
def get_xeditable_form_class(self):
return self.xeditable_form_class
def get_xeditable_form_kwargs(self):
kwargs = {
'model': self.get_queryset().model,
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.request.POST,
})
return kwargs
def get_xeditable_form(self, form_class):
return form_class(**self.get_xeditable_form_kwargs())
def get_update_object(self, form):
pk = form.cleaned_data['pk']
queryset = self.get_queryset()
try:
obj = queryset.get(pk=pk)
except queryset.model.DoesNotExist:
obj = None
return obj
def update_object(self, form, obj):
field_name = form.cleaned_data['name']
value = form.cleaned_data['value']
setattr(obj, field_name, value)
save_kwargs = {}
if CAN_UPDATE_FIELDS:
save_kwargs['update_fields'] = [field_name]
obj.save(**save_kwargs)
data = json.dumps({
'status': 'success',
})
return HttpResponse(data, content_type="application/json")
def get_field_choices(self, field, field_name):
if self.request.GET.get('select2'):
names = ['id', 'text']
else:
names = ['value', 'text']
choices_getter = getattr(self, 'get_field_%s_choices', None)
if choices_getter is None:
if isinstance(field, ForeignKey):
choices_getter = self._get_foreignkey_choices
else:
choices_getter = self._get_default_choices
return [dict(zip(names, choice)) for choice in choices_getter(field, field_name)]
def _get_foreignkey_choices(self, field, field_name):
formfield_kwargs = {}
if not field.blank:
# will consequently try to assume initial=None, forcing the blank option to appear.
formfield_kwargs['empty_label'] = None
formfield = field.formfield(**formfield_kwargs)
return formfield.choices
def _get_default_choices(self, field, field_name):
return field.choices
class XEditableDatatableView(XEditableMixin, DatatableView):
pass
| true | true |
f73b8b2b5932fa5f64fba445978b37c4d46ad40d | 2,276 | py | Python | gae/settings.py | ibagrak/algae | a11230cb41653c74e0fe9764eb8ec2c42bee1f52 | [
"MIT"
] | 3 | 2015-03-11T17:59:45.000Z | 2016-12-02T15:53:15.000Z | gae/settings.py | ibagrak/algae | a11230cb41653c74e0fe9764eb8ec2c42bee1f52 | [
"MIT"
] | null | null | null | gae/settings.py | ibagrak/algae | a11230cb41653c74e0fe9764eb8ec2c42bee1f52 | [
"MIT"
] | null | null | null | import os
from google.appengine.api.app_identity import get_default_version_hostname, get_application_id
from secrets import SESSION_KEY
if 'SERVER_SOFTWARE' in os.environ and os.environ['SERVER_SOFTWARE'].startswith('Dev'):
DEBUG = True
HOME_URL = 'http://localhost' + ':8085'
else:
DEBUG = False
HOME_URL = 'http://' + get_default_version_hostname()
# webapp2 config
app_config = {
'webapp2_extras.sessions': {
'cookie_name': '_simpleauth_sess',
'secret_key': SESSION_KEY
},
'webapp2_extras.auth': {
'user_attributes': []
}
}
# i18n config
AVAILABLE_LOCALES = ['en_US', 'de_DE']
# List of valid APIs
APIS = frozenset({'signup_mailing_list', 'change_email_addr'})
#200 OK - Everything worked as expected.
#400 Bad Request - Often missing a required parameter.
#401 Unauthorized - No valid API key provided.
#402 Request Failed - Parameters were valid but request failed.
#404 Not Found - The requested item doesn't exist.
#500, 502, 503, 504 Server errors - something went wrong on Stripe's end.
API_CODES = { 200 : 'Success',
400 : {'email' : 'Invalid email address',
'password' : 'Invalid password',
'email_password' : 'Invalid email or password',
'unsupported' : 'Unsupported API',
'missing' : 'Not all parameter present',
'noemail' : 'Email not valid'},
401 : 'Unauthorized',
402 : {'unconfirmed' : 'Email has not been confirmed.',
'duplicate' : 'User already exists.'},
404 : 'Does not exist',
500 : {'generic' : 'Server error',
'admin_required' : 'Please contact application administrator for support'}}
# URLs
APP_ID = get_application_id()
COOKIE_TEMPLATE = { 'id' : 0, #session id
'pageviews' : 0,
'authed' : False,
'active' : True }
DATE_FORMAT_HTML = "dd-mm-yyyy"
DATE_FORMAT = "%d-%m-%Y"
# Email Authentication
EMAIL_CONFIRM_BODY = """
Hello, %s!
Please click the link below to confirm your email address:
%s
Thank you.
"""
EMAIL_SENDER = "ilya.bagrak@gmail.com"
| 30.756757 | 97 | 0.600615 | import os
from google.appengine.api.app_identity import get_default_version_hostname, get_application_id
from secrets import SESSION_KEY
if 'SERVER_SOFTWARE' in os.environ and os.environ['SERVER_SOFTWARE'].startswith('Dev'):
DEBUG = True
HOME_URL = 'http://localhost' + ':8085'
else:
DEBUG = False
HOME_URL = 'http://' + get_default_version_hostname()
app_config = {
'webapp2_extras.sessions': {
'cookie_name': '_simpleauth_sess',
'secret_key': SESSION_KEY
},
'webapp2_extras.auth': {
'user_attributes': []
}
}
AVAILABLE_LOCALES = ['en_US', 'de_DE']
APIS = frozenset({'signup_mailing_list', 'change_email_addr'})
#500, 502, 503, 504 Server errors - something went wrong on Stripe's end.
API_CODES = { 200 : 'Success',
400 : {'email' : 'Invalid email address',
'password' : 'Invalid password',
'email_password' : 'Invalid email or password',
'unsupported' : 'Unsupported API',
'missing' : 'Not all parameter present',
'noemail' : 'Email not valid'},
401 : 'Unauthorized',
402 : {'unconfirmed' : 'Email has not been confirmed.',
'duplicate' : 'User already exists.'},
404 : 'Does not exist',
500 : {'generic' : 'Server error',
'admin_required' : 'Please contact application administrator for support'}}
APP_ID = get_application_id()
COOKIE_TEMPLATE = { 'id' : 0,
'pageviews' : 0,
'authed' : False,
'active' : True }
DATE_FORMAT_HTML = "dd-mm-yyyy"
DATE_FORMAT = "%d-%m-%Y"
EMAIL_CONFIRM_BODY = """
Hello, %s!
Please click the link below to confirm your email address:
%s
Thank you.
"""
EMAIL_SENDER = "ilya.bagrak@gmail.com"
| true | true |
f73b8c8b9a207572d1e32a32e294041c56147a7d | 1,054 | py | Python | python/scrapy-spider/tutorial/middleware/uaagent.py | yc19890920/Learn | 3990e75b469225ba7b430539ef9a16abe89eb863 | [
"Apache-2.0"
] | 1 | 2021-01-11T06:30:44.000Z | 2021-01-11T06:30:44.000Z | python/scrapy-spider/tutorial/middleware/uaagent.py | yc19890920/Learn | 3990e75b469225ba7b430539ef9a16abe89eb863 | [
"Apache-2.0"
] | 23 | 2020-02-12T02:35:49.000Z | 2022-02-11T03:45:40.000Z | python/scrapy-spider/tutorial/middleware/uaagent.py | yc19890920/Learn | 3990e75b469225ba7b430539ef9a16abe89eb863 | [
"Apache-2.0"
] | 2 | 2020-04-08T15:39:46.000Z | 2020-10-10T10:13:09.000Z | # -*- coding: utf-8 -*-
import random
import logging
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware
logger = logging.getLogger(__name__)
class RotateUserAgentMiddleware(UserAgentMiddleware):
"""避免被ban策略之一:使用useragent池。
使用注意:需在settings.py中进行相应的设置。
更好的方式是使用:
pip install scrapy-fake-useragent
DOWNLOADER_MIDDLEWARES = {
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
'scrapy_fake_useragent.middleware.RandomUserAgentMiddleware': 400,
}
"""
"""Randomly rotate user agents based on a list of predefined ones"""
def __init__(self, agents):
super(RotateUserAgentMiddleware, self).__init__()
self.agents = agents
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.settings.getlist('USER_AGENTS'))
def process_request(self, request, spider):
ua = random.choice(self.agents)
request.headers.setdefault('User-Agent', ua)
logger.debug('Current UserAgent: ' + ua) | 35.133333 | 76 | 0.696395 |
import random
import logging
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware
logger = logging.getLogger(__name__)
class RotateUserAgentMiddleware(UserAgentMiddleware):
def __init__(self, agents):
super(RotateUserAgentMiddleware, self).__init__()
self.agents = agents
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.settings.getlist('USER_AGENTS'))
def process_request(self, request, spider):
ua = random.choice(self.agents)
request.headers.setdefault('User-Agent', ua)
logger.debug('Current UserAgent: ' + ua) | true | true |
f73b8d0e7a8172c2979c10a918c906cbf88ce04b | 6,117 | py | Python | deprecated/converters/nist_xray_tran_en_db_converter.py | materials-data-facility/connect | 9ec5b61750bf6fa579bf3ec122f31880d3c049b8 | [
"Apache-2.0"
] | 1 | 2019-09-13T18:35:56.000Z | 2019-09-13T18:35:56.000Z | deprecated/converters/nist_xray_tran_en_db_converter.py | materials-data-facility/connect_server | 9ec5b61750bf6fa579bf3ec122f31880d3c049b8 | [
"Apache-2.0"
] | 15 | 2018-11-01T18:08:11.000Z | 2021-12-06T17:55:03.000Z | deprecated/converters/nist_xray_tran_en_db_converter.py | materials-data-facility/connect | 9ec5b61750bf6fa579bf3ec122f31880d3c049b8 | [
"Apache-2.0"
] | 1 | 2020-11-30T17:02:41.000Z | 2020-11-30T17:02:41.000Z | import json
import sys
import os
from tqdm import tqdm
from mdf_refinery.validator import Validator
from mdf_refinery.parsers.tab_parser import parse_tab
# VERSION 0.3.0
# This is the converter for the NIST X-Ray Transition Energies Database
# Arguments:
# input_path (string): The file or directory where the data resides.
# NOTE: Do not hard-code the path to the data in the converter. The converter should be portable.
# metadata (string or dict): The path to the JSON dataset metadata file, a dict or json.dumps string containing the dataset metadata, or None to specify the metadata here. Default None.
# verbose (bool): Should the script print status messages to standard output? Default False.
# NOTE: The converter should have NO output if verbose is False, unless there is an error.
def convert(input_path, metadata=None, verbose=False):
if verbose:
print("Begin converting")
# Collect the metadata
if not metadata:
dataset_metadata = {
"mdf": {
"title": "NIST X-Ray Transition Energies Database",
"acl": ["public"],
"source_name": "nist_xray_tran_en_db",
"citation": ["http://physics.nist.gov/PhysRefData/XrayTrans/Html/refs.html"],
"data_contact": {
"given_name": "Lawrence",
"family_name": "Hudson",
"email": "lawrence.hudson@nist.gov",
"institution": "National Institute of Standards and Technology"
},
# "author": ,
# "license": ,
"collection": "NIST X-Ray Transition Energies",
"tags": ["Radiation", "Spectroscopy", "Reference data"],
"description": "This x-ray transition table provides the energies for K transitions connecting the K shell (n = 1) to the shells with principal quantum numbers n = 2 to 4 and L transitions connecting the L1, L2, and L3 shells (n = 2) to the shells with principal quantum numbers n = 3 and 4. The elements covered include Z = 10, neon to Z = 100, fermium. There are two unique features of this database: (1) all experimental values are on a scale consistent with the International System of measurement (the SI) and the numerical values are determined using constants from the Recommended Values of the Fundamental Physical Constants: 1998 [115] and (2) accurate theoretical estimates are included for all transitions. The user will find that for many of the transitions, the experimental and theoretical values are very consistent. It is our hope that the theoretical values will provide a useful estimate for missing or poorly measured experimental values.",
"year": 2003,
"links": {
"landing_page": "https://www.nist.gov/pml/x-ray-transition-energies-database",
# "publication": ,
# "dataset_doi": ,
# "related_id": ,
# data links: {
#"globus_endpoint": ,
#"http_host": ,
#"path": ,
#}
},
# "mrr": ,
"data_contributor": {
"given_name": "Jonathon",
"family_name": "Gaff",
"email": "jgaff@uchicago.edu",
"institution": "The University of Chicago",
"github": "jgaff"
}
}
}
elif type(metadata) is str:
try:
dataset_metadata = json.loads(metadata)
except Exception:
try:
with open(metadata, 'r') as metadata_file:
dataset_metadata = json.load(metadata_file)
except Exception as e:
sys.exit("Error: Unable to read metadata: " + repr(e))
elif type(metadata) is dict:
dataset_metadata = metadata
else:
sys.exit("Error: Invalid metadata parameter")
dataset_validator = Validator(dataset_metadata)
# Get the data
headers = ['element', 'A', 'transition', 'theory_(eV)', 'theory_uncertainty_(eV)', 'direct_(eV)', 'direct_uncertainty_(eV)', 'combined_(eV)', 'combined_uncertainty_(eV)', 'vapor_(eV)', 'vapor_uncertainty_(eV)', 'blend', 'reference']
with open(os.path.join(input_path, "xray_tran_en_db.txt")) as in_file:
raw_data = in_file.read()
for record in tqdm(parse_tab(raw_data, sep="\t", headers=headers), desc="Processing data", disable= not verbose):
record_metadata = {
"mdf": {
"title": "X-Ray Transition - " + record["element"],
"acl": ["public"],
# "tags": ,
# "description": ,
"composition": record["element"],
"raw": json.dumps(record),
"links": {
"landing_page": "http://physics.nist.gov/PhysRefData/XrayTrans/Html/search.html",
# "publication": ,
# "dataset_doi": ,
# "related_id": ,
# data links: {
#"globus_endpoint": ,
#"http_host": ,
#"path": ,
#},
},
# "citation": ,
# "data_contact": {
# "given_name": ,
# "family_name": ,
# "email": ,
# "institution":,
# IDs
# },
# "author": ,
# "license": ,
# "collection": ,
# "data_format": ,
# "data_type": ,
# "year": ,
# "mrr":
# "processing": ,
# "structure":,
}
}
# Pass each individual record to the Validator
result = dataset_validator.write_record(record_metadata)
# Check if the Validator accepted the record, and print a message if it didn't
# If the Validator returns "success" == True, the record was written successfully
if result["success"] is not True:
print("Error:", result["message"])
if verbose:
print("Finished converting")
| 36.195266 | 971 | 0.564329 | import json
import sys
import os
from tqdm import tqdm
from mdf_refinery.validator import Validator
from mdf_refinery.parsers.tab_parser import parse_tab
def convert(input_path, metadata=None, verbose=False):
if verbose:
print("Begin converting")
if not metadata:
dataset_metadata = {
"mdf": {
"title": "NIST X-Ray Transition Energies Database",
"acl": ["public"],
"source_name": "nist_xray_tran_en_db",
"citation": ["http://physics.nist.gov/PhysRefData/XrayTrans/Html/refs.html"],
"data_contact": {
"given_name": "Lawrence",
"family_name": "Hudson",
"email": "lawrence.hudson@nist.gov",
"institution": "National Institute of Standards and Technology"
},
"collection": "NIST X-Ray Transition Energies",
"tags": ["Radiation", "Spectroscopy", "Reference data"],
"description": "This x-ray transition table provides the energies for K transitions connecting the K shell (n = 1) to the shells with principal quantum numbers n = 2 to 4 and L transitions connecting the L1, L2, and L3 shells (n = 2) to the shells with principal quantum numbers n = 3 and 4. The elements covered include Z = 10, neon to Z = 100, fermium. There are two unique features of this database: (1) all experimental values are on a scale consistent with the International System of measurement (the SI) and the numerical values are determined using constants from the Recommended Values of the Fundamental Physical Constants: 1998 [115] and (2) accurate theoretical estimates are included for all transitions. The user will find that for many of the transitions, the experimental and theoretical values are very consistent. It is our hope that the theoretical values will provide a useful estimate for missing or poorly measured experimental values.",
"year": 2003,
"links": {
"landing_page": "https://www.nist.gov/pml/x-ray-transition-energies-database",
},
"data_contributor": {
"given_name": "Jonathon",
"family_name": "Gaff",
"email": "jgaff@uchicago.edu",
"institution": "The University of Chicago",
"github": "jgaff"
}
}
}
elif type(metadata) is str:
try:
dataset_metadata = json.loads(metadata)
except Exception:
try:
with open(metadata, 'r') as metadata_file:
dataset_metadata = json.load(metadata_file)
except Exception as e:
sys.exit("Error: Unable to read metadata: " + repr(e))
elif type(metadata) is dict:
dataset_metadata = metadata
else:
sys.exit("Error: Invalid metadata parameter")
dataset_validator = Validator(dataset_metadata)
headers = ['element', 'A', 'transition', 'theory_(eV)', 'theory_uncertainty_(eV)', 'direct_(eV)', 'direct_uncertainty_(eV)', 'combined_(eV)', 'combined_uncertainty_(eV)', 'vapor_(eV)', 'vapor_uncertainty_(eV)', 'blend', 'reference']
with open(os.path.join(input_path, "xray_tran_en_db.txt")) as in_file:
raw_data = in_file.read()
for record in tqdm(parse_tab(raw_data, sep="\t", headers=headers), desc="Processing data", disable= not verbose):
record_metadata = {
"mdf": {
"title": "X-Ray Transition - " + record["element"],
"acl": ["public"],
"composition": record["element"],
"raw": json.dumps(record),
"links": {
"landing_page": "http://physics.nist.gov/PhysRefData/XrayTrans/Html/search.html",
},
}
}
result = dataset_validator.write_record(record_metadata)
# If the Validator returns "success" == True, the record was written successfully
if result["success"] is not True:
print("Error:", result["message"])
if verbose:
print("Finished converting")
| true | true |
f73b8f287469e22057eda5b4367a4587ca687649 | 3,260 | py | Python | powerdns_recursor/tests/test_powerdns.py | andersenleo/integrations-core | e521b88e32820a286a70c7797a663d4f9ba41110 | [
"BSD-3-Clause"
] | 2 | 2019-05-28T03:48:29.000Z | 2019-07-05T07:05:58.000Z | powerdns_recursor/tests/test_powerdns.py | andersenleo/integrations-core | e521b88e32820a286a70c7797a663d4f9ba41110 | [
"BSD-3-Clause"
] | 4 | 2019-07-03T02:53:19.000Z | 2019-07-10T14:52:14.000Z | powerdns_recursor/tests/test_powerdns.py | andersenleo/integrations-core | e521b88e32820a286a70c7797a663d4f9ba41110 | [
"BSD-3-Clause"
] | 1 | 2020-01-15T16:58:51.000Z | 2020-01-15T16:58:51.000Z | # (C) Datadog, Inc. 2010-2018
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
import pytest
from . import common, metrics
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("dd_environment")]
def test_check(aggregator, check):
service_check_tags = common._config_sc_tags(common.CONFIG)
# get version and test v3 first.
version = common._get_pdns_version()
if version == 3:
check.check(common.CONFIG)
# Assert metrics
for metric in metrics.GAUGE_METRICS:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=[], count=1)
for metric in metrics.RATE_METRICS:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=[], count=1)
aggregator.assert_service_check('powerdns.recursor.can_connect', status=check.OK, tags=service_check_tags)
aggregator.assert_all_metrics_covered()
elif version == 4:
check.check(common.CONFIG_V4)
# Assert metrics
for metric in metrics.GAUGE_METRICS + metrics.GAUGE_METRICS_V4:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=[], count=1)
for metric in metrics.RATE_METRICS + metrics.RATE_METRICS_V4:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=[], count=1)
aggregator.assert_service_check('powerdns.recursor.can_connect', status=check.OK, tags=service_check_tags)
aggregator.assert_all_metrics_covered()
else:
aggregator.assert_service_check('powerdns.recursor.can_connect', status=check.CRITICAL, tags=service_check_tags)
def test_tags(aggregator, check):
version = common._get_pdns_version()
tags = ['foo:bar']
if version == 3:
config = common.CONFIG.copy()
config['tags'] = ['foo:bar']
check.check(config)
# Assert metrics v3
for metric in metrics.GAUGE_METRICS:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=tags, count=1)
for metric in metrics.RATE_METRICS:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=tags, count=1)
elif version == 4:
config = common.CONFIG_V4.copy()
config['tags'] = ['foo:bar']
check.check(config)
# Assert metrics v3
for metric in metrics.GAUGE_METRICS + metrics.GAUGE_METRICS_V4:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=tags, count=1)
for metric in metrics.RATE_METRICS + metrics.RATE_METRICS_V4:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=tags, count=1)
service_check_tags = common._config_sc_tags(common.CONFIG)
aggregator.assert_service_check('powerdns.recursor.can_connect', status=check.OK, tags=service_check_tags + tags)
aggregator.assert_all_metrics_covered()
def test_bad_api_key(aggregator, check):
with pytest.raises(Exception):
check.check(common.BAD_API_KEY_CONFIG)
service_check_tags = common._config_sc_tags(common.BAD_API_KEY_CONFIG)
aggregator.assert_service_check('powerdns.recursor.can_connect', status=check.CRITICAL, tags=service_check_tags)
assert len(aggregator._metrics) == 0
| 37.471264 | 120 | 0.715031 |
import pytest
from . import common, metrics
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("dd_environment")]
def test_check(aggregator, check):
service_check_tags = common._config_sc_tags(common.CONFIG)
version = common._get_pdns_version()
if version == 3:
check.check(common.CONFIG)
for metric in metrics.GAUGE_METRICS:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=[], count=1)
for metric in metrics.RATE_METRICS:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=[], count=1)
aggregator.assert_service_check('powerdns.recursor.can_connect', status=check.OK, tags=service_check_tags)
aggregator.assert_all_metrics_covered()
elif version == 4:
check.check(common.CONFIG_V4)
for metric in metrics.GAUGE_METRICS + metrics.GAUGE_METRICS_V4:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=[], count=1)
for metric in metrics.RATE_METRICS + metrics.RATE_METRICS_V4:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=[], count=1)
aggregator.assert_service_check('powerdns.recursor.can_connect', status=check.OK, tags=service_check_tags)
aggregator.assert_all_metrics_covered()
else:
aggregator.assert_service_check('powerdns.recursor.can_connect', status=check.CRITICAL, tags=service_check_tags)
def test_tags(aggregator, check):
version = common._get_pdns_version()
tags = ['foo:bar']
if version == 3:
config = common.CONFIG.copy()
config['tags'] = ['foo:bar']
check.check(config)
for metric in metrics.GAUGE_METRICS:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=tags, count=1)
for metric in metrics.RATE_METRICS:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=tags, count=1)
elif version == 4:
config = common.CONFIG_V4.copy()
config['tags'] = ['foo:bar']
check.check(config)
for metric in metrics.GAUGE_METRICS + metrics.GAUGE_METRICS_V4:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=tags, count=1)
for metric in metrics.RATE_METRICS + metrics.RATE_METRICS_V4:
aggregator.assert_metric(metrics.METRIC_FORMAT.format(metric), tags=tags, count=1)
service_check_tags = common._config_sc_tags(common.CONFIG)
aggregator.assert_service_check('powerdns.recursor.can_connect', status=check.OK, tags=service_check_tags + tags)
aggregator.assert_all_metrics_covered()
def test_bad_api_key(aggregator, check):
with pytest.raises(Exception):
check.check(common.BAD_API_KEY_CONFIG)
service_check_tags = common._config_sc_tags(common.BAD_API_KEY_CONFIG)
aggregator.assert_service_check('powerdns.recursor.can_connect', status=check.CRITICAL, tags=service_check_tags)
assert len(aggregator._metrics) == 0
| true | true |
f73b9086549b2aab459f315497f818e84b7f645f | 274 | py | Python | python/nxp_imu/__init__.py | MomsFriendlyRobotCompany/adafruit-precision-nxp-9-dof- | b8c39f37e0b77181d23c7095b4dc93bcd5b83a14 | [
"MIT"
] | 8 | 2018-02-25T07:39:10.000Z | 2022-02-02T01:43:52.000Z | python/nxp_imu/__init__.py | MomsFriendlyRobotCompany/adafruit-precision-nxp-9-dof- | b8c39f37e0b77181d23c7095b4dc93bcd5b83a14 | [
"MIT"
] | 5 | 2017-07-19T12:49:38.000Z | 2018-10-26T03:08:50.000Z | python/nxp_imu/__init__.py | MomsFriendlyRobotCompany/adafruit-precision-nxp-9-dof- | b8c39f37e0b77181d23c7095b4dc93bcd5b83a14 | [
"MIT"
] | 4 | 2017-11-07T17:14:38.000Z | 2021-08-17T18:15:41.000Z | from nxp_imu.I2C import I2C
from nxp_imu.IMU import IMU
# class Namespace(object):
# def __init__(self, **kwds):
# self.__dict__.update(kwds)
__version__ = '0.6.1'
__author__ = 'Kevin J. Walchko'
__license__ = 'MIT'
__copyright__ = '2017 Kevin J. Walchko'
| 21.076923 | 40 | 0.686131 | from nxp_imu.I2C import I2C
from nxp_imu.IMU import IMU
__version__ = '0.6.1'
__author__ = 'Kevin J. Walchko'
__license__ = 'MIT'
__copyright__ = '2017 Kevin J. Walchko'
| true | true |
f73b90cd360da438221b08f0e61102773f2b5a86 | 21,273 | py | Python | sdk/python/pulumi_aws/lambda_/outputs.py | sibuthomasmathew/pulumi-aws | 6351f2182eb6f693d4e09e4136c385adfa0ab674 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_aws/lambda_/outputs.py | sibuthomasmathew/pulumi-aws | 6351f2182eb6f693d4e09e4136c385adfa0ab674 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_aws/lambda_/outputs.py | sibuthomasmathew/pulumi-aws | 6351f2182eb6f693d4e09e4136c385adfa0ab674 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from . import outputs
from ._enums import *
__all__ = [
'AliasRoutingConfig',
'CodeSigningConfigAllowedPublishers',
'CodeSigningConfigPolicies',
'EventSourceMappingDestinationConfig',
'EventSourceMappingDestinationConfigOnFailure',
'FunctionDeadLetterConfig',
'FunctionEnvironment',
'FunctionEventInvokeConfigDestinationConfig',
'FunctionEventInvokeConfigDestinationConfigOnFailure',
'FunctionEventInvokeConfigDestinationConfigOnSuccess',
'FunctionFileSystemConfig',
'FunctionImageConfig',
'FunctionTracingConfig',
'FunctionVpcConfig',
'GetCodeSigningConfigAllowedPublisherResult',
'GetCodeSigningConfigPolicyResult',
'GetFunctionDeadLetterConfigResult',
'GetFunctionEnvironmentResult',
'GetFunctionFileSystemConfigResult',
'GetFunctionTracingConfigResult',
'GetFunctionVpcConfigResult',
]
@pulumi.output_type
class AliasRoutingConfig(dict):
def __init__(__self__, *,
additional_version_weights: Optional[Mapping[str, float]] = None):
"""
:param Mapping[str, float] additional_version_weights: A map that defines the proportion of events that should be sent to different versions of a lambda function.
"""
if additional_version_weights is not None:
pulumi.set(__self__, "additional_version_weights", additional_version_weights)
@property
@pulumi.getter(name="additionalVersionWeights")
def additional_version_weights(self) -> Optional[Mapping[str, float]]:
"""
A map that defines the proportion of events that should be sent to different versions of a lambda function.
"""
return pulumi.get(self, "additional_version_weights")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class CodeSigningConfigAllowedPublishers(dict):
def __init__(__self__, *,
signing_profile_version_arns: Sequence[str]):
"""
:param Sequence[str] signing_profile_version_arns: The Amazon Resource Name (ARN) for each of the signing profiles. A signing profile defines a trusted user who can sign a code package.
"""
pulumi.set(__self__, "signing_profile_version_arns", signing_profile_version_arns)
@property
@pulumi.getter(name="signingProfileVersionArns")
def signing_profile_version_arns(self) -> Sequence[str]:
"""
The Amazon Resource Name (ARN) for each of the signing profiles. A signing profile defines a trusted user who can sign a code package.
"""
return pulumi.get(self, "signing_profile_version_arns")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class CodeSigningConfigPolicies(dict):
def __init__(__self__, *,
untrusted_artifact_on_deployment: str):
"""
:param str untrusted_artifact_on_deployment: Code signing configuration policy for deployment validation failure. If you set the policy to Enforce, Lambda blocks the deployment request if code-signing validation checks fail. If you set the policy to Warn, Lambda allows the deployment and creates a CloudWatch log. Valid values: `Warn`, `Enforce`. Default value: `Warn`.
"""
pulumi.set(__self__, "untrusted_artifact_on_deployment", untrusted_artifact_on_deployment)
@property
@pulumi.getter(name="untrustedArtifactOnDeployment")
def untrusted_artifact_on_deployment(self) -> str:
"""
Code signing configuration policy for deployment validation failure. If you set the policy to Enforce, Lambda blocks the deployment request if code-signing validation checks fail. If you set the policy to Warn, Lambda allows the deployment and creates a CloudWatch log. Valid values: `Warn`, `Enforce`. Default value: `Warn`.
"""
return pulumi.get(self, "untrusted_artifact_on_deployment")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class EventSourceMappingDestinationConfig(dict):
def __init__(__self__, *,
on_failure: Optional['outputs.EventSourceMappingDestinationConfigOnFailure'] = None):
"""
:param 'EventSourceMappingDestinationConfigOnFailureArgs' on_failure: The destination configuration for failed invocations. Detailed below.
"""
if on_failure is not None:
pulumi.set(__self__, "on_failure", on_failure)
@property
@pulumi.getter(name="onFailure")
def on_failure(self) -> Optional['outputs.EventSourceMappingDestinationConfigOnFailure']:
"""
The destination configuration for failed invocations. Detailed below.
"""
return pulumi.get(self, "on_failure")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class EventSourceMappingDestinationConfigOnFailure(dict):
def __init__(__self__, *,
destination_arn: str):
"""
:param str destination_arn: The Amazon Resource Name (ARN) of the destination resource.
"""
pulumi.set(__self__, "destination_arn", destination_arn)
@property
@pulumi.getter(name="destinationArn")
def destination_arn(self) -> str:
"""
The Amazon Resource Name (ARN) of the destination resource.
"""
return pulumi.get(self, "destination_arn")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionDeadLetterConfig(dict):
def __init__(__self__, *,
target_arn: str):
"""
:param str target_arn: ARN of an SNS topic or SQS queue to notify when an invocation fails. If this option is used, the function's IAM role must be granted suitable access to write to the target object, which means allowing either the `sns:Publish` or `sqs:SendMessage` action on this ARN, depending on which service is targeted.
"""
pulumi.set(__self__, "target_arn", target_arn)
@property
@pulumi.getter(name="targetArn")
def target_arn(self) -> str:
"""
ARN of an SNS topic or SQS queue to notify when an invocation fails. If this option is used, the function's IAM role must be granted suitable access to write to the target object, which means allowing either the `sns:Publish` or `sqs:SendMessage` action on this ARN, depending on which service is targeted.
"""
return pulumi.get(self, "target_arn")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionEnvironment(dict):
def __init__(__self__, *,
variables: Optional[Mapping[str, str]] = None):
"""
:param Mapping[str, str] variables: Map of environment variables that are accessible from the function code during execution.
"""
if variables is not None:
pulumi.set(__self__, "variables", variables)
@property
@pulumi.getter
def variables(self) -> Optional[Mapping[str, str]]:
"""
Map of environment variables that are accessible from the function code during execution.
"""
return pulumi.get(self, "variables")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionEventInvokeConfigDestinationConfig(dict):
def __init__(__self__, *,
on_failure: Optional['outputs.FunctionEventInvokeConfigDestinationConfigOnFailure'] = None,
on_success: Optional['outputs.FunctionEventInvokeConfigDestinationConfigOnSuccess'] = None):
"""
:param 'FunctionEventInvokeConfigDestinationConfigOnFailureArgs' on_failure: Configuration block with destination configuration for failed asynchronous invocations. See below for details.
:param 'FunctionEventInvokeConfigDestinationConfigOnSuccessArgs' on_success: Configuration block with destination configuration for successful asynchronous invocations. See below for details.
"""
if on_failure is not None:
pulumi.set(__self__, "on_failure", on_failure)
if on_success is not None:
pulumi.set(__self__, "on_success", on_success)
@property
@pulumi.getter(name="onFailure")
def on_failure(self) -> Optional['outputs.FunctionEventInvokeConfigDestinationConfigOnFailure']:
"""
Configuration block with destination configuration for failed asynchronous invocations. See below for details.
"""
return pulumi.get(self, "on_failure")
@property
@pulumi.getter(name="onSuccess")
def on_success(self) -> Optional['outputs.FunctionEventInvokeConfigDestinationConfigOnSuccess']:
"""
Configuration block with destination configuration for successful asynchronous invocations. See below for details.
"""
return pulumi.get(self, "on_success")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionEventInvokeConfigDestinationConfigOnFailure(dict):
def __init__(__self__, *,
destination: str):
"""
:param str destination: Amazon Resource Name (ARN) of the destination resource. See the [Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations) for acceptable resource types and associated IAM permissions.
"""
pulumi.set(__self__, "destination", destination)
@property
@pulumi.getter
def destination(self) -> str:
"""
Amazon Resource Name (ARN) of the destination resource. See the [Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations) for acceptable resource types and associated IAM permissions.
"""
return pulumi.get(self, "destination")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionEventInvokeConfigDestinationConfigOnSuccess(dict):
def __init__(__self__, *,
destination: str):
"""
:param str destination: Amazon Resource Name (ARN) of the destination resource. See the [Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations) for acceptable resource types and associated IAM permissions.
"""
pulumi.set(__self__, "destination", destination)
@property
@pulumi.getter
def destination(self) -> str:
"""
Amazon Resource Name (ARN) of the destination resource. See the [Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations) for acceptable resource types and associated IAM permissions.
"""
return pulumi.get(self, "destination")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionFileSystemConfig(dict):
def __init__(__self__, *,
arn: str,
local_mount_path: str):
"""
:param str arn: Amazon Resource Name (ARN) of the Amazon EFS Access Point that provides access to the file system.
:param str local_mount_path: Path where the function can access the file system, starting with /mnt/.
"""
pulumi.set(__self__, "arn", arn)
pulumi.set(__self__, "local_mount_path", local_mount_path)
@property
@pulumi.getter
def arn(self) -> str:
"""
Amazon Resource Name (ARN) of the Amazon EFS Access Point that provides access to the file system.
"""
return pulumi.get(self, "arn")
@property
@pulumi.getter(name="localMountPath")
def local_mount_path(self) -> str:
"""
Path where the function can access the file system, starting with /mnt/.
"""
return pulumi.get(self, "local_mount_path")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionImageConfig(dict):
def __init__(__self__, *,
commands: Optional[Sequence[str]] = None,
entry_points: Optional[Sequence[str]] = None,
working_directory: Optional[str] = None):
"""
:param Sequence[str] commands: Parameters that you want to pass in with `entry_point`.
:param Sequence[str] entry_points: Entry point to your application, which is typically the location of the runtime executable.
:param str working_directory: Working directory.
"""
if commands is not None:
pulumi.set(__self__, "commands", commands)
if entry_points is not None:
pulumi.set(__self__, "entry_points", entry_points)
if working_directory is not None:
pulumi.set(__self__, "working_directory", working_directory)
@property
@pulumi.getter
def commands(self) -> Optional[Sequence[str]]:
"""
Parameters that you want to pass in with `entry_point`.
"""
return pulumi.get(self, "commands")
@property
@pulumi.getter(name="entryPoints")
def entry_points(self) -> Optional[Sequence[str]]:
"""
Entry point to your application, which is typically the location of the runtime executable.
"""
return pulumi.get(self, "entry_points")
@property
@pulumi.getter(name="workingDirectory")
def working_directory(self) -> Optional[str]:
"""
Working directory.
"""
return pulumi.get(self, "working_directory")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionTracingConfig(dict):
def __init__(__self__, *,
mode: str):
"""
:param str mode: Whether to to sample and trace a subset of incoming requests with AWS X-Ray. Valid values are `PassThrough` and `Active`. If `PassThrough`, Lambda will only trace the request from an upstream service if it contains a tracing header with "sampled=1". If `Active`, Lambda will respect any tracing header it receives from an upstream service. If no tracing header is received, Lambda will call X-Ray for a tracing decision.
"""
pulumi.set(__self__, "mode", mode)
@property
@pulumi.getter
def mode(self) -> str:
"""
Whether to to sample and trace a subset of incoming requests with AWS X-Ray. Valid values are `PassThrough` and `Active`. If `PassThrough`, Lambda will only trace the request from an upstream service if it contains a tracing header with "sampled=1". If `Active`, Lambda will respect any tracing header it receives from an upstream service. If no tracing header is received, Lambda will call X-Ray for a tracing decision.
"""
return pulumi.get(self, "mode")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionVpcConfig(dict):
def __init__(__self__, *,
security_group_ids: Sequence[str],
subnet_ids: Sequence[str],
vpc_id: Optional[str] = None):
"""
:param Sequence[str] security_group_ids: List of security group IDs associated with the Lambda function.
:param Sequence[str] subnet_ids: List of subnet IDs associated with the Lambda function.
"""
pulumi.set(__self__, "security_group_ids", security_group_ids)
pulumi.set(__self__, "subnet_ids", subnet_ids)
if vpc_id is not None:
pulumi.set(__self__, "vpc_id", vpc_id)
@property
@pulumi.getter(name="securityGroupIds")
def security_group_ids(self) -> Sequence[str]:
"""
List of security group IDs associated with the Lambda function.
"""
return pulumi.get(self, "security_group_ids")
@property
@pulumi.getter(name="subnetIds")
def subnet_ids(self) -> Sequence[str]:
"""
List of subnet IDs associated with the Lambda function.
"""
return pulumi.get(self, "subnet_ids")
@property
@pulumi.getter(name="vpcId")
def vpc_id(self) -> Optional[str]:
return pulumi.get(self, "vpc_id")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class GetCodeSigningConfigAllowedPublisherResult(dict):
def __init__(__self__, *,
signing_profile_version_arns: Sequence[str]):
"""
:param Sequence[str] signing_profile_version_arns: The Amazon Resource Name (ARN) for each of the signing profiles. A signing profile defines a trusted user who can sign a code package.
"""
pulumi.set(__self__, "signing_profile_version_arns", signing_profile_version_arns)
@property
@pulumi.getter(name="signingProfileVersionArns")
def signing_profile_version_arns(self) -> Sequence[str]:
"""
The Amazon Resource Name (ARN) for each of the signing profiles. A signing profile defines a trusted user who can sign a code package.
"""
return pulumi.get(self, "signing_profile_version_arns")
@pulumi.output_type
class GetCodeSigningConfigPolicyResult(dict):
def __init__(__self__, *,
untrusted_artifact_on_deployment: str):
"""
:param str untrusted_artifact_on_deployment: Code signing configuration policy for deployment validation failure.
"""
pulumi.set(__self__, "untrusted_artifact_on_deployment", untrusted_artifact_on_deployment)
@property
@pulumi.getter(name="untrustedArtifactOnDeployment")
def untrusted_artifact_on_deployment(self) -> str:
"""
Code signing configuration policy for deployment validation failure.
"""
return pulumi.get(self, "untrusted_artifact_on_deployment")
@pulumi.output_type
class GetFunctionDeadLetterConfigResult(dict):
def __init__(__self__, *,
target_arn: str):
pulumi.set(__self__, "target_arn", target_arn)
@property
@pulumi.getter(name="targetArn")
def target_arn(self) -> str:
return pulumi.get(self, "target_arn")
@pulumi.output_type
class GetFunctionEnvironmentResult(dict):
def __init__(__self__, *,
variables: Mapping[str, str]):
pulumi.set(__self__, "variables", variables)
@property
@pulumi.getter
def variables(self) -> Mapping[str, str]:
return pulumi.get(self, "variables")
@pulumi.output_type
class GetFunctionFileSystemConfigResult(dict):
def __init__(__self__, *,
arn: str,
local_mount_path: str):
"""
:param str arn: Unqualified (no `:QUALIFIER` or `:VERSION` suffix) Amazon Resource Name (ARN) identifying your Lambda Function. See also `qualified_arn`.
"""
pulumi.set(__self__, "arn", arn)
pulumi.set(__self__, "local_mount_path", local_mount_path)
@property
@pulumi.getter
def arn(self) -> str:
"""
Unqualified (no `:QUALIFIER` or `:VERSION` suffix) Amazon Resource Name (ARN) identifying your Lambda Function. See also `qualified_arn`.
"""
return pulumi.get(self, "arn")
@property
@pulumi.getter(name="localMountPath")
def local_mount_path(self) -> str:
return pulumi.get(self, "local_mount_path")
@pulumi.output_type
class GetFunctionTracingConfigResult(dict):
def __init__(__self__, *,
mode: str):
pulumi.set(__self__, "mode", mode)
@property
@pulumi.getter
def mode(self) -> str:
return pulumi.get(self, "mode")
@pulumi.output_type
class GetFunctionVpcConfigResult(dict):
def __init__(__self__, *,
security_group_ids: Sequence[str],
subnet_ids: Sequence[str],
vpc_id: str):
pulumi.set(__self__, "security_group_ids", security_group_ids)
pulumi.set(__self__, "subnet_ids", subnet_ids)
pulumi.set(__self__, "vpc_id", vpc_id)
@property
@pulumi.getter(name="securityGroupIds")
def security_group_ids(self) -> Sequence[str]:
return pulumi.get(self, "security_group_ids")
@property
@pulumi.getter(name="subnetIds")
def subnet_ids(self) -> Sequence[str]:
return pulumi.get(self, "subnet_ids")
@property
@pulumi.getter(name="vpcId")
def vpc_id(self) -> str:
return pulumi.get(self, "vpc_id")
| 40.52 | 445 | 0.689889 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from . import outputs
from ._enums import *
__all__ = [
'AliasRoutingConfig',
'CodeSigningConfigAllowedPublishers',
'CodeSigningConfigPolicies',
'EventSourceMappingDestinationConfig',
'EventSourceMappingDestinationConfigOnFailure',
'FunctionDeadLetterConfig',
'FunctionEnvironment',
'FunctionEventInvokeConfigDestinationConfig',
'FunctionEventInvokeConfigDestinationConfigOnFailure',
'FunctionEventInvokeConfigDestinationConfigOnSuccess',
'FunctionFileSystemConfig',
'FunctionImageConfig',
'FunctionTracingConfig',
'FunctionVpcConfig',
'GetCodeSigningConfigAllowedPublisherResult',
'GetCodeSigningConfigPolicyResult',
'GetFunctionDeadLetterConfigResult',
'GetFunctionEnvironmentResult',
'GetFunctionFileSystemConfigResult',
'GetFunctionTracingConfigResult',
'GetFunctionVpcConfigResult',
]
@pulumi.output_type
class AliasRoutingConfig(dict):
def __init__(__self__, *,
additional_version_weights: Optional[Mapping[str, float]] = None):
if additional_version_weights is not None:
pulumi.set(__self__, "additional_version_weights", additional_version_weights)
@property
@pulumi.getter(name="additionalVersionWeights")
def additional_version_weights(self) -> Optional[Mapping[str, float]]:
return pulumi.get(self, "additional_version_weights")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class CodeSigningConfigAllowedPublishers(dict):
def __init__(__self__, *,
signing_profile_version_arns: Sequence[str]):
pulumi.set(__self__, "signing_profile_version_arns", signing_profile_version_arns)
@property
@pulumi.getter(name="signingProfileVersionArns")
def signing_profile_version_arns(self) -> Sequence[str]:
return pulumi.get(self, "signing_profile_version_arns")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class CodeSigningConfigPolicies(dict):
def __init__(__self__, *,
untrusted_artifact_on_deployment: str):
pulumi.set(__self__, "untrusted_artifact_on_deployment", untrusted_artifact_on_deployment)
@property
@pulumi.getter(name="untrustedArtifactOnDeployment")
def untrusted_artifact_on_deployment(self) -> str:
return pulumi.get(self, "untrusted_artifact_on_deployment")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class EventSourceMappingDestinationConfig(dict):
def __init__(__self__, *,
on_failure: Optional['outputs.EventSourceMappingDestinationConfigOnFailure'] = None):
if on_failure is not None:
pulumi.set(__self__, "on_failure", on_failure)
@property
@pulumi.getter(name="onFailure")
def on_failure(self) -> Optional['outputs.EventSourceMappingDestinationConfigOnFailure']:
return pulumi.get(self, "on_failure")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class EventSourceMappingDestinationConfigOnFailure(dict):
def __init__(__self__, *,
destination_arn: str):
pulumi.set(__self__, "destination_arn", destination_arn)
@property
@pulumi.getter(name="destinationArn")
def destination_arn(self) -> str:
return pulumi.get(self, "destination_arn")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionDeadLetterConfig(dict):
def __init__(__self__, *,
target_arn: str):
pulumi.set(__self__, "target_arn", target_arn)
@property
@pulumi.getter(name="targetArn")
def target_arn(self) -> str:
return pulumi.get(self, "target_arn")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionEnvironment(dict):
def __init__(__self__, *,
variables: Optional[Mapping[str, str]] = None):
if variables is not None:
pulumi.set(__self__, "variables", variables)
@property
@pulumi.getter
def variables(self) -> Optional[Mapping[str, str]]:
return pulumi.get(self, "variables")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionEventInvokeConfigDestinationConfig(dict):
def __init__(__self__, *,
on_failure: Optional['outputs.FunctionEventInvokeConfigDestinationConfigOnFailure'] = None,
on_success: Optional['outputs.FunctionEventInvokeConfigDestinationConfigOnSuccess'] = None):
if on_failure is not None:
pulumi.set(__self__, "on_failure", on_failure)
if on_success is not None:
pulumi.set(__self__, "on_success", on_success)
@property
@pulumi.getter(name="onFailure")
def on_failure(self) -> Optional['outputs.FunctionEventInvokeConfigDestinationConfigOnFailure']:
return pulumi.get(self, "on_failure")
@property
@pulumi.getter(name="onSuccess")
def on_success(self) -> Optional['outputs.FunctionEventInvokeConfigDestinationConfigOnSuccess']:
return pulumi.get(self, "on_success")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionEventInvokeConfigDestinationConfigOnFailure(dict):
def __init__(__self__, *,
destination: str):
pulumi.set(__self__, "destination", destination)
@property
@pulumi.getter
def destination(self) -> str:
return pulumi.get(self, "destination")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionEventInvokeConfigDestinationConfigOnSuccess(dict):
def __init__(__self__, *,
destination: str):
pulumi.set(__self__, "destination", destination)
@property
@pulumi.getter
def destination(self) -> str:
return pulumi.get(self, "destination")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionFileSystemConfig(dict):
def __init__(__self__, *,
arn: str,
local_mount_path: str):
pulumi.set(__self__, "arn", arn)
pulumi.set(__self__, "local_mount_path", local_mount_path)
@property
@pulumi.getter
def arn(self) -> str:
return pulumi.get(self, "arn")
@property
@pulumi.getter(name="localMountPath")
def local_mount_path(self) -> str:
return pulumi.get(self, "local_mount_path")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionImageConfig(dict):
def __init__(__self__, *,
commands: Optional[Sequence[str]] = None,
entry_points: Optional[Sequence[str]] = None,
working_directory: Optional[str] = None):
if commands is not None:
pulumi.set(__self__, "commands", commands)
if entry_points is not None:
pulumi.set(__self__, "entry_points", entry_points)
if working_directory is not None:
pulumi.set(__self__, "working_directory", working_directory)
@property
@pulumi.getter
def commands(self) -> Optional[Sequence[str]]:
return pulumi.get(self, "commands")
@property
@pulumi.getter(name="entryPoints")
def entry_points(self) -> Optional[Sequence[str]]:
return pulumi.get(self, "entry_points")
@property
@pulumi.getter(name="workingDirectory")
def working_directory(self) -> Optional[str]:
return pulumi.get(self, "working_directory")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionTracingConfig(dict):
def __init__(__self__, *,
mode: str):
pulumi.set(__self__, "mode", mode)
@property
@pulumi.getter
def mode(self) -> str:
return pulumi.get(self, "mode")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class FunctionVpcConfig(dict):
def __init__(__self__, *,
security_group_ids: Sequence[str],
subnet_ids: Sequence[str],
vpc_id: Optional[str] = None):
pulumi.set(__self__, "security_group_ids", security_group_ids)
pulumi.set(__self__, "subnet_ids", subnet_ids)
if vpc_id is not None:
pulumi.set(__self__, "vpc_id", vpc_id)
@property
@pulumi.getter(name="securityGroupIds")
def security_group_ids(self) -> Sequence[str]:
return pulumi.get(self, "security_group_ids")
@property
@pulumi.getter(name="subnetIds")
def subnet_ids(self) -> Sequence[str]:
return pulumi.get(self, "subnet_ids")
@property
@pulumi.getter(name="vpcId")
def vpc_id(self) -> Optional[str]:
return pulumi.get(self, "vpc_id")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class GetCodeSigningConfigAllowedPublisherResult(dict):
def __init__(__self__, *,
signing_profile_version_arns: Sequence[str]):
pulumi.set(__self__, "signing_profile_version_arns", signing_profile_version_arns)
@property
@pulumi.getter(name="signingProfileVersionArns")
def signing_profile_version_arns(self) -> Sequence[str]:
return pulumi.get(self, "signing_profile_version_arns")
@pulumi.output_type
class GetCodeSigningConfigPolicyResult(dict):
def __init__(__self__, *,
untrusted_artifact_on_deployment: str):
pulumi.set(__self__, "untrusted_artifact_on_deployment", untrusted_artifact_on_deployment)
@property
@pulumi.getter(name="untrustedArtifactOnDeployment")
def untrusted_artifact_on_deployment(self) -> str:
return pulumi.get(self, "untrusted_artifact_on_deployment")
@pulumi.output_type
class GetFunctionDeadLetterConfigResult(dict):
def __init__(__self__, *,
target_arn: str):
pulumi.set(__self__, "target_arn", target_arn)
@property
@pulumi.getter(name="targetArn")
def target_arn(self) -> str:
return pulumi.get(self, "target_arn")
@pulumi.output_type
class GetFunctionEnvironmentResult(dict):
def __init__(__self__, *,
variables: Mapping[str, str]):
pulumi.set(__self__, "variables", variables)
@property
@pulumi.getter
def variables(self) -> Mapping[str, str]:
return pulumi.get(self, "variables")
@pulumi.output_type
class GetFunctionFileSystemConfigResult(dict):
def __init__(__self__, *,
arn: str,
local_mount_path: str):
pulumi.set(__self__, "arn", arn)
pulumi.set(__self__, "local_mount_path", local_mount_path)
@property
@pulumi.getter
def arn(self) -> str:
return pulumi.get(self, "arn")
@property
@pulumi.getter(name="localMountPath")
def local_mount_path(self) -> str:
return pulumi.get(self, "local_mount_path")
@pulumi.output_type
class GetFunctionTracingConfigResult(dict):
def __init__(__self__, *,
mode: str):
pulumi.set(__self__, "mode", mode)
@property
@pulumi.getter
def mode(self) -> str:
return pulumi.get(self, "mode")
@pulumi.output_type
class GetFunctionVpcConfigResult(dict):
def __init__(__self__, *,
security_group_ids: Sequence[str],
subnet_ids: Sequence[str],
vpc_id: str):
pulumi.set(__self__, "security_group_ids", security_group_ids)
pulumi.set(__self__, "subnet_ids", subnet_ids)
pulumi.set(__self__, "vpc_id", vpc_id)
@property
@pulumi.getter(name="securityGroupIds")
def security_group_ids(self) -> Sequence[str]:
return pulumi.get(self, "security_group_ids")
@property
@pulumi.getter(name="subnetIds")
def subnet_ids(self) -> Sequence[str]:
return pulumi.get(self, "subnet_ids")
@property
@pulumi.getter(name="vpcId")
def vpc_id(self) -> str:
return pulumi.get(self, "vpc_id")
| true | true |
f73b90e155e1f948a2cdbad982d75178c343f236 | 2,581 | py | Python | impurity/impurity_tester.py | kevaundray/research | 16f20848c614b580071fed3d2ff1dc69688fa4f4 | [
"MIT"
] | 1,351 | 2015-09-22T08:17:10.000Z | 2022-03-31T22:48:07.000Z | impurity/impurity_tester.py | kevaundray/research | 16f20848c614b580071fed3d2ff1dc69688fa4f4 | [
"MIT"
] | 42 | 2016-08-31T14:43:29.000Z | 2021-12-05T23:10:31.000Z | impurity/impurity_tester.py | LaudateCorpus1/research | 6e8b7b367e7f1b18b4b92151df01dfeaa0774a23 | [
"MIT"
] | 334 | 2015-09-20T10:15:23.000Z | 2022-03-28T17:46:57.000Z | from ethereum import tester as t
from ethereum import utils
from ethereum import transactions
import rlp
import serpent
s = t.state()
c = s.abi_contract('check_for_impurity.se')
#from ethereum.slogging import LogRecorder, configure_logging, set_level
#config_string = ':info,eth.vm.log:trace,eth.vm.op:trace,eth.vm.stack:trace,eth.vm.exit:trace,eth.pb.msg:trace,eth.pb.tx:debug'
#configure_logging(config_string=config_string)
test1 = s.abi_contract("""
data horse
def foo():
return self.horse
""")
try:
c.submit(test1.address)
success = True
except:
success = False
assert not success
failedtest_addr = "0x"+utils.encode_hex(test1.address)
test2 = s.abi_contract("""
def foo():
return block.number
""")
try:
c.submit(test2.address)
success = True
except:
success = False
assert not success
test3 = s.abi_contract("""
def foo(x):
return x * 2
""")
c.submit(test3.address)
test4 = s.abi_contract("""
def modexp(b: uint256, e: uint256, m: uint256):
if e == 0:
return 1
elif e == 1:
return b
elif e % 2 == 0:
return self.modexp(~mulmod(b, b, m), ~div(e, 2), m)
elif e % 2 == 1:
return ~mulmod(self.modexp(~mulmod(b, b, m), ~div(e, 2), m), b, m)
""")
c.submit(test4.address)
modexp_addr = "0x"+utils.encode_hex(test4.address)
test5 = s.abi_contract("""
def modinv(b, m):
inpdata = [0xa7d4bbe6, b, m-2, m]
outdata = [0]
~call(100000, %s, 0, inpdata + 28, 100, outdata, 32)
return outdata[0]
""" % modexp_addr)
c.submit(test5.address)
test6 = s.abi_contract("""
def phooey(h, v, r, s):
return ecrecover(h, v, r, s)
""")
c.submit(test6.address)
test7 = s.abi_contract("""
def modinv(b, m):
inpdata = [0xa7d4bbe6, b, m-2, m]
outdata = [0]
~call(msg.gas - 10000, %s, 0, inpdata + 28, 100, outdata, 32)
return outdata[0]
""" % failedtest_addr)
try:
c.submit(test7.address)
success = True
except:
success = False
assert not success
print('All tests passed')
kode = serpent.compile('check_for_impurity.se')
# Create transaction
t = transactions.Transaction(0, 30 * 10**9, 2999999, '', 0, kode)
t.startgas = t.intrinsic_gas_used + 50000 + 200 * len(kode)
t.v = 27
t.r = 45
t.s = 79
print('Send %d wei to %s' % (t.startgas * t.gasprice,
'0x'+utils.encode_hex(t.sender)))
print('Contract address: 0x'+utils.encode_hex(utils.mk_contract_address(t.sender, 0)))
print('Code: 0x'+utils.encode_hex(rlp.encode(t)))
print('ABI declaration: '+repr(serpent.mk_full_signature('check_for_impurity.se')))
| 20.814516 | 127 | 0.650523 | from ethereum import tester as t
from ethereum import utils
from ethereum import transactions
import rlp
import serpent
s = t.state()
c = s.abi_contract('check_for_impurity.se')
test1 = s.abi_contract("""
data horse
def foo():
return self.horse
""")
try:
c.submit(test1.address)
success = True
except:
success = False
assert not success
failedtest_addr = "0x"+utils.encode_hex(test1.address)
test2 = s.abi_contract("""
def foo():
return block.number
""")
try:
c.submit(test2.address)
success = True
except:
success = False
assert not success
test3 = s.abi_contract("""
def foo(x):
return x * 2
""")
c.submit(test3.address)
test4 = s.abi_contract("""
def modexp(b: uint256, e: uint256, m: uint256):
if e == 0:
return 1
elif e == 1:
return b
elif e % 2 == 0:
return self.modexp(~mulmod(b, b, m), ~div(e, 2), m)
elif e % 2 == 1:
return ~mulmod(self.modexp(~mulmod(b, b, m), ~div(e, 2), m), b, m)
""")
c.submit(test4.address)
modexp_addr = "0x"+utils.encode_hex(test4.address)
test5 = s.abi_contract("""
def modinv(b, m):
inpdata = [0xa7d4bbe6, b, m-2, m]
outdata = [0]
~call(100000, %s, 0, inpdata + 28, 100, outdata, 32)
return outdata[0]
""" % modexp_addr)
c.submit(test5.address)
test6 = s.abi_contract("""
def phooey(h, v, r, s):
return ecrecover(h, v, r, s)
""")
c.submit(test6.address)
test7 = s.abi_contract("""
def modinv(b, m):
inpdata = [0xa7d4bbe6, b, m-2, m]
outdata = [0]
~call(msg.gas - 10000, %s, 0, inpdata + 28, 100, outdata, 32)
return outdata[0]
""" % failedtest_addr)
try:
c.submit(test7.address)
success = True
except:
success = False
assert not success
print('All tests passed')
kode = serpent.compile('check_for_impurity.se')
t = transactions.Transaction(0, 30 * 10**9, 2999999, '', 0, kode)
t.startgas = t.intrinsic_gas_used + 50000 + 200 * len(kode)
t.v = 27
t.r = 45
t.s = 79
print('Send %d wei to %s' % (t.startgas * t.gasprice,
'0x'+utils.encode_hex(t.sender)))
print('Contract address: 0x'+utils.encode_hex(utils.mk_contract_address(t.sender, 0)))
print('Code: 0x'+utils.encode_hex(rlp.encode(t)))
print('ABI declaration: '+repr(serpent.mk_full_signature('check_for_impurity.se')))
| true | true |
f73b920f46b7725c72ef39bd90b06520a9dbd2b0 | 14,268 | py | Python | sdk/python/pulumi_cloudflare/access_rule.py | pulumi/pulumi-cloudflare | d444af2fab6101b388a15cf2e3933e45e9935cc6 | [
"ECL-2.0",
"Apache-2.0"
] | 35 | 2019-03-14T21:29:29.000Z | 2022-03-30T00:00:59.000Z | sdk/python/pulumi_cloudflare/access_rule.py | pulumi/pulumi-cloudflare | d444af2fab6101b388a15cf2e3933e45e9935cc6 | [
"ECL-2.0",
"Apache-2.0"
] | 128 | 2019-03-08T23:45:58.000Z | 2022-03-31T21:05:22.000Z | sdk/python/pulumi_cloudflare/access_rule.py | pulumi/pulumi-cloudflare | d444af2fab6101b388a15cf2e3933e45e9935cc6 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2019-05-10T12:52:56.000Z | 2020-03-24T15:02:14.000Z | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
from . import outputs
from ._inputs import *
__all__ = ['AccessRuleArgs', 'AccessRule']
@pulumi.input_type
class AccessRuleArgs:
def __init__(__self__, *,
configuration: pulumi.Input['AccessRuleConfigurationArgs'],
mode: pulumi.Input[str],
notes: Optional[pulumi.Input[str]] = None,
zone_id: Optional[pulumi.Input[str]] = None):
"""
The set of arguments for constructing a AccessRule resource.
:param pulumi.Input['AccessRuleConfigurationArgs'] configuration: Rule configuration to apply to a matched request. It's a complex value. See description below.
:param pulumi.Input[str] mode: The action to apply to a matched request. Allowed values: "block", "challenge", "whitelist", "js_challenge"
:param pulumi.Input[str] notes: A personal note about the rule. Typically used as a reminder or explanation for the rule.
:param pulumi.Input[str] zone_id: The DNS zone to which the access rule should be added.
"""
pulumi.set(__self__, "configuration", configuration)
pulumi.set(__self__, "mode", mode)
if notes is not None:
pulumi.set(__self__, "notes", notes)
if zone_id is not None:
pulumi.set(__self__, "zone_id", zone_id)
@property
@pulumi.getter
def configuration(self) -> pulumi.Input['AccessRuleConfigurationArgs']:
"""
Rule configuration to apply to a matched request. It's a complex value. See description below.
"""
return pulumi.get(self, "configuration")
@configuration.setter
def configuration(self, value: pulumi.Input['AccessRuleConfigurationArgs']):
pulumi.set(self, "configuration", value)
@property
@pulumi.getter
def mode(self) -> pulumi.Input[str]:
"""
The action to apply to a matched request. Allowed values: "block", "challenge", "whitelist", "js_challenge"
"""
return pulumi.get(self, "mode")
@mode.setter
def mode(self, value: pulumi.Input[str]):
pulumi.set(self, "mode", value)
@property
@pulumi.getter
def notes(self) -> Optional[pulumi.Input[str]]:
"""
A personal note about the rule. Typically used as a reminder or explanation for the rule.
"""
return pulumi.get(self, "notes")
@notes.setter
def notes(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "notes", value)
@property
@pulumi.getter(name="zoneId")
def zone_id(self) -> Optional[pulumi.Input[str]]:
"""
The DNS zone to which the access rule should be added.
"""
return pulumi.get(self, "zone_id")
@zone_id.setter
def zone_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "zone_id", value)
@pulumi.input_type
class _AccessRuleState:
def __init__(__self__, *,
configuration: Optional[pulumi.Input['AccessRuleConfigurationArgs']] = None,
mode: Optional[pulumi.Input[str]] = None,
notes: Optional[pulumi.Input[str]] = None,
zone_id: Optional[pulumi.Input[str]] = None):
"""
Input properties used for looking up and filtering AccessRule resources.
:param pulumi.Input['AccessRuleConfigurationArgs'] configuration: Rule configuration to apply to a matched request. It's a complex value. See description below.
:param pulumi.Input[str] mode: The action to apply to a matched request. Allowed values: "block", "challenge", "whitelist", "js_challenge"
:param pulumi.Input[str] notes: A personal note about the rule. Typically used as a reminder or explanation for the rule.
:param pulumi.Input[str] zone_id: The DNS zone to which the access rule should be added.
"""
if configuration is not None:
pulumi.set(__self__, "configuration", configuration)
if mode is not None:
pulumi.set(__self__, "mode", mode)
if notes is not None:
pulumi.set(__self__, "notes", notes)
if zone_id is not None:
pulumi.set(__self__, "zone_id", zone_id)
@property
@pulumi.getter
def configuration(self) -> Optional[pulumi.Input['AccessRuleConfigurationArgs']]:
"""
Rule configuration to apply to a matched request. It's a complex value. See description below.
"""
return pulumi.get(self, "configuration")
@configuration.setter
def configuration(self, value: Optional[pulumi.Input['AccessRuleConfigurationArgs']]):
pulumi.set(self, "configuration", value)
@property
@pulumi.getter
def mode(self) -> Optional[pulumi.Input[str]]:
"""
The action to apply to a matched request. Allowed values: "block", "challenge", "whitelist", "js_challenge"
"""
return pulumi.get(self, "mode")
@mode.setter
def mode(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "mode", value)
@property
@pulumi.getter
def notes(self) -> Optional[pulumi.Input[str]]:
"""
A personal note about the rule. Typically used as a reminder or explanation for the rule.
"""
return pulumi.get(self, "notes")
@notes.setter
def notes(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "notes", value)
@property
@pulumi.getter(name="zoneId")
def zone_id(self) -> Optional[pulumi.Input[str]]:
"""
The DNS zone to which the access rule should be added.
"""
return pulumi.get(self, "zone_id")
@zone_id.setter
def zone_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "zone_id", value)
class AccessRule(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
configuration: Optional[pulumi.Input[pulumi.InputType['AccessRuleConfigurationArgs']]] = None,
mode: Optional[pulumi.Input[str]] = None,
notes: Optional[pulumi.Input[str]] = None,
zone_id: Optional[pulumi.Input[str]] = None,
__props__=None):
"""
Provides a Cloudflare IP Firewall Access Rule resource. Access control can be applied on basis of IP addresses, IP ranges, AS numbers or countries.
## Import
Records can be imported using a composite ID formed of access rule type, access rule type identifier and identifer value, e.g.
```sh
$ pulumi import cloudflare:index/accessRule:AccessRule default zone/cb029e245cfdd66dc8d2e570d5dd3322/d41d8cd98f00b204e9800998ecf8427e
```
where* `zone` - access rule type (`account`, `zone` or `user`) * `cb029e245cfdd66dc8d2e570d5dd3322` - access rule type ID (i.e the zone ID
or account ID you wish to target) * `d41d8cd98f00b204e9800998ecf8427e` - access rule ID as returned by
respective API endpoint for the type you are attempting to import.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[pulumi.InputType['AccessRuleConfigurationArgs']] configuration: Rule configuration to apply to a matched request. It's a complex value. See description below.
:param pulumi.Input[str] mode: The action to apply to a matched request. Allowed values: "block", "challenge", "whitelist", "js_challenge"
:param pulumi.Input[str] notes: A personal note about the rule. Typically used as a reminder or explanation for the rule.
:param pulumi.Input[str] zone_id: The DNS zone to which the access rule should be added.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: AccessRuleArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
Provides a Cloudflare IP Firewall Access Rule resource. Access control can be applied on basis of IP addresses, IP ranges, AS numbers or countries.
## Import
Records can be imported using a composite ID formed of access rule type, access rule type identifier and identifer value, e.g.
```sh
$ pulumi import cloudflare:index/accessRule:AccessRule default zone/cb029e245cfdd66dc8d2e570d5dd3322/d41d8cd98f00b204e9800998ecf8427e
```
where* `zone` - access rule type (`account`, `zone` or `user`) * `cb029e245cfdd66dc8d2e570d5dd3322` - access rule type ID (i.e the zone ID
or account ID you wish to target) * `d41d8cd98f00b204e9800998ecf8427e` - access rule ID as returned by
respective API endpoint for the type you are attempting to import.
:param str resource_name: The name of the resource.
:param AccessRuleArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(AccessRuleArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
configuration: Optional[pulumi.Input[pulumi.InputType['AccessRuleConfigurationArgs']]] = None,
mode: Optional[pulumi.Input[str]] = None,
notes: Optional[pulumi.Input[str]] = None,
zone_id: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = AccessRuleArgs.__new__(AccessRuleArgs)
if configuration is None and not opts.urn:
raise TypeError("Missing required property 'configuration'")
__props__.__dict__["configuration"] = configuration
if mode is None and not opts.urn:
raise TypeError("Missing required property 'mode'")
__props__.__dict__["mode"] = mode
__props__.__dict__["notes"] = notes
__props__.__dict__["zone_id"] = zone_id
super(AccessRule, __self__).__init__(
'cloudflare:index/accessRule:AccessRule',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
configuration: Optional[pulumi.Input[pulumi.InputType['AccessRuleConfigurationArgs']]] = None,
mode: Optional[pulumi.Input[str]] = None,
notes: Optional[pulumi.Input[str]] = None,
zone_id: Optional[pulumi.Input[str]] = None) -> 'AccessRule':
"""
Get an existing AccessRule resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[pulumi.InputType['AccessRuleConfigurationArgs']] configuration: Rule configuration to apply to a matched request. It's a complex value. See description below.
:param pulumi.Input[str] mode: The action to apply to a matched request. Allowed values: "block", "challenge", "whitelist", "js_challenge"
:param pulumi.Input[str] notes: A personal note about the rule. Typically used as a reminder or explanation for the rule.
:param pulumi.Input[str] zone_id: The DNS zone to which the access rule should be added.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _AccessRuleState.__new__(_AccessRuleState)
__props__.__dict__["configuration"] = configuration
__props__.__dict__["mode"] = mode
__props__.__dict__["notes"] = notes
__props__.__dict__["zone_id"] = zone_id
return AccessRule(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def configuration(self) -> pulumi.Output['outputs.AccessRuleConfiguration']:
"""
Rule configuration to apply to a matched request. It's a complex value. See description below.
"""
return pulumi.get(self, "configuration")
@property
@pulumi.getter
def mode(self) -> pulumi.Output[str]:
"""
The action to apply to a matched request. Allowed values: "block", "challenge", "whitelist", "js_challenge"
"""
return pulumi.get(self, "mode")
@property
@pulumi.getter
def notes(self) -> pulumi.Output[Optional[str]]:
"""
A personal note about the rule. Typically used as a reminder or explanation for the rule.
"""
return pulumi.get(self, "notes")
@property
@pulumi.getter(name="zoneId")
def zone_id(self) -> pulumi.Output[str]:
"""
The DNS zone to which the access rule should be added.
"""
return pulumi.get(self, "zone_id")
| 44.448598 | 186 | 0.651248 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
from . import outputs
from ._inputs import *
__all__ = ['AccessRuleArgs', 'AccessRule']
@pulumi.input_type
class AccessRuleArgs:
def __init__(__self__, *,
configuration: pulumi.Input['AccessRuleConfigurationArgs'],
mode: pulumi.Input[str],
notes: Optional[pulumi.Input[str]] = None,
zone_id: Optional[pulumi.Input[str]] = None):
pulumi.set(__self__, "configuration", configuration)
pulumi.set(__self__, "mode", mode)
if notes is not None:
pulumi.set(__self__, "notes", notes)
if zone_id is not None:
pulumi.set(__self__, "zone_id", zone_id)
@property
@pulumi.getter
def configuration(self) -> pulumi.Input['AccessRuleConfigurationArgs']:
return pulumi.get(self, "configuration")
@configuration.setter
def configuration(self, value: pulumi.Input['AccessRuleConfigurationArgs']):
pulumi.set(self, "configuration", value)
@property
@pulumi.getter
def mode(self) -> pulumi.Input[str]:
return pulumi.get(self, "mode")
@mode.setter
def mode(self, value: pulumi.Input[str]):
pulumi.set(self, "mode", value)
@property
@pulumi.getter
def notes(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "notes")
@notes.setter
def notes(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "notes", value)
@property
@pulumi.getter(name="zoneId")
def zone_id(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "zone_id")
@zone_id.setter
def zone_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "zone_id", value)
@pulumi.input_type
class _AccessRuleState:
def __init__(__self__, *,
configuration: Optional[pulumi.Input['AccessRuleConfigurationArgs']] = None,
mode: Optional[pulumi.Input[str]] = None,
notes: Optional[pulumi.Input[str]] = None,
zone_id: Optional[pulumi.Input[str]] = None):
if configuration is not None:
pulumi.set(__self__, "configuration", configuration)
if mode is not None:
pulumi.set(__self__, "mode", mode)
if notes is not None:
pulumi.set(__self__, "notes", notes)
if zone_id is not None:
pulumi.set(__self__, "zone_id", zone_id)
@property
@pulumi.getter
def configuration(self) -> Optional[pulumi.Input['AccessRuleConfigurationArgs']]:
return pulumi.get(self, "configuration")
@configuration.setter
def configuration(self, value: Optional[pulumi.Input['AccessRuleConfigurationArgs']]):
pulumi.set(self, "configuration", value)
@property
@pulumi.getter
def mode(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "mode")
@mode.setter
def mode(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "mode", value)
@property
@pulumi.getter
def notes(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "notes")
@notes.setter
def notes(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "notes", value)
@property
@pulumi.getter(name="zoneId")
def zone_id(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "zone_id")
@zone_id.setter
def zone_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "zone_id", value)
class AccessRule(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
configuration: Optional[pulumi.Input[pulumi.InputType['AccessRuleConfigurationArgs']]] = None,
mode: Optional[pulumi.Input[str]] = None,
notes: Optional[pulumi.Input[str]] = None,
zone_id: Optional[pulumi.Input[str]] = None,
__props__=None):
...
@overload
def __init__(__self__,
resource_name: str,
args: AccessRuleArgs,
opts: Optional[pulumi.ResourceOptions] = None):
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(AccessRuleArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
configuration: Optional[pulumi.Input[pulumi.InputType['AccessRuleConfigurationArgs']]] = None,
mode: Optional[pulumi.Input[str]] = None,
notes: Optional[pulumi.Input[str]] = None,
zone_id: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = AccessRuleArgs.__new__(AccessRuleArgs)
if configuration is None and not opts.urn:
raise TypeError("Missing required property 'configuration'")
__props__.__dict__["configuration"] = configuration
if mode is None and not opts.urn:
raise TypeError("Missing required property 'mode'")
__props__.__dict__["mode"] = mode
__props__.__dict__["notes"] = notes
__props__.__dict__["zone_id"] = zone_id
super(AccessRule, __self__).__init__(
'cloudflare:index/accessRule:AccessRule',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
configuration: Optional[pulumi.Input[pulumi.InputType['AccessRuleConfigurationArgs']]] = None,
mode: Optional[pulumi.Input[str]] = None,
notes: Optional[pulumi.Input[str]] = None,
zone_id: Optional[pulumi.Input[str]] = None) -> 'AccessRule':
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _AccessRuleState.__new__(_AccessRuleState)
__props__.__dict__["configuration"] = configuration
__props__.__dict__["mode"] = mode
__props__.__dict__["notes"] = notes
__props__.__dict__["zone_id"] = zone_id
return AccessRule(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def configuration(self) -> pulumi.Output['outputs.AccessRuleConfiguration']:
return pulumi.get(self, "configuration")
@property
@pulumi.getter
def mode(self) -> pulumi.Output[str]:
return pulumi.get(self, "mode")
@property
@pulumi.getter
def notes(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "notes")
@property
@pulumi.getter(name="zoneId")
def zone_id(self) -> pulumi.Output[str]:
return pulumi.get(self, "zone_id")
| true | true |
f73b92740682e2a96e9119cd7935cc8c606e5abc | 2,479 | py | Python | setup.py | p-boaz/docassemble-graphletter | 38969ea3acc0dd6c913f99faad85567e8731e767 | [
"MIT"
] | null | null | null | setup.py | p-boaz/docassemble-graphletter | 38969ea3acc0dd6c913f99faad85567e8731e767 | [
"MIT"
] | null | null | null | setup.py | p-boaz/docassemble-graphletter | 38969ea3acc0dd6c913f99faad85567e8731e767 | [
"MIT"
] | null | null | null | import os
import sys
from setuptools import setup, find_packages
from fnmatch import fnmatchcase
from distutils.util import convert_path
standard_exclude = ('*.pyc', '*~', '.*', '*.bak', '*.swp*')
standard_exclude_directories = ('.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info')
def find_package_data(where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories):
out = {}
stack = [(convert_path(where), '', package)]
while stack:
where, prefix, package = stack.pop(0)
for name in os.listdir(where):
fn = os.path.join(where, name)
if os.path.isdir(fn):
bad_name = False
for pattern in exclude_directories:
if (fnmatchcase(name, pattern)
or fn.lower() == pattern.lower()):
bad_name = True
break
if bad_name:
continue
if os.path.isfile(os.path.join(fn, '__init__.py')):
if not package:
new_package = name
else:
new_package = package + '.' + name
stack.append((fn, '', new_package))
else:
stack.append((fn, prefix + name + '/', package))
else:
bad_name = False
for pattern in exclude:
if (fnmatchcase(name, pattern)
or fn.lower() == pattern.lower()):
bad_name = True
break
if bad_name:
continue
out.setdefault(package, []).append(prefix+name)
return out
setup(name='docassemble.graphletter',
version='0.0.1',
description=('A docassemble extension.'),
long_description='# docassemble.graphletter\n\nA docassemble extension.\n\n## Author\n\nSystem Administrator, admin@graphletter.com\n\n',
long_description_content_type='text/markdown',
author='System Administrator',
author_email='admin@graphletter.com',
license='The MIT License (MIT)',
url='https://docassemble.org',
packages=find_packages(),
namespace_packages=['docassemble'],
install_requires=[],
zip_safe=False,
package_data=find_package_data(where='docassemble/graphletter/', package='docassemble.graphletter'),
)
| 40.639344 | 143 | 0.546591 | import os
import sys
from setuptools import setup, find_packages
from fnmatch import fnmatchcase
from distutils.util import convert_path
standard_exclude = ('*.pyc', '*~', '.*', '*.bak', '*.swp*')
standard_exclude_directories = ('.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info')
def find_package_data(where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories):
out = {}
stack = [(convert_path(where), '', package)]
while stack:
where, prefix, package = stack.pop(0)
for name in os.listdir(where):
fn = os.path.join(where, name)
if os.path.isdir(fn):
bad_name = False
for pattern in exclude_directories:
if (fnmatchcase(name, pattern)
or fn.lower() == pattern.lower()):
bad_name = True
break
if bad_name:
continue
if os.path.isfile(os.path.join(fn, '__init__.py')):
if not package:
new_package = name
else:
new_package = package + '.' + name
stack.append((fn, '', new_package))
else:
stack.append((fn, prefix + name + '/', package))
else:
bad_name = False
for pattern in exclude:
if (fnmatchcase(name, pattern)
or fn.lower() == pattern.lower()):
bad_name = True
break
if bad_name:
continue
out.setdefault(package, []).append(prefix+name)
return out
setup(name='docassemble.graphletter',
version='0.0.1',
description=('A docassemble extension.'),
long_description='# docassemble.graphletter\n\nA docassemble extension.\n\n## Author\n\nSystem Administrator, admin@graphletter.com\n\n',
long_description_content_type='text/markdown',
author='System Administrator',
author_email='admin@graphletter.com',
license='The MIT License (MIT)',
url='https://docassemble.org',
packages=find_packages(),
namespace_packages=['docassemble'],
install_requires=[],
zip_safe=False,
package_data=find_package_data(where='docassemble/graphletter/', package='docassemble.graphletter'),
)
| true | true |
f73b93ab910858ada11953806a0efea7fb62c984 | 688 | py | Python | syntacticstrutting/migrations/0002_auto_20180316_1526.py | notkrd/languagegames | d0d5a0a0673c039de4f699c1fe5cfd60b8eeaa70 | [
"MIT"
] | null | null | null | syntacticstrutting/migrations/0002_auto_20180316_1526.py | notkrd/languagegames | d0d5a0a0673c039de4f699c1fe5cfd60b8eeaa70 | [
"MIT"
] | null | null | null | syntacticstrutting/migrations/0002_auto_20180316_1526.py | notkrd/languagegames | d0d5a0a0673c039de4f699c1fe5cfd60b8eeaa70 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-03-16 22:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('syntacticstrutting', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='SyntaxToxen',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('token_str', models.CharField(max_length=200)),
],
),
migrations.DeleteModel(
name='PhraseRule',
),
]
| 26.461538 | 115 | 0.56686 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('syntacticstrutting', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='SyntaxToxen',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('token_str', models.CharField(max_length=200)),
],
),
migrations.DeleteModel(
name='PhraseRule',
),
]
| true | true |
f73b93b1d7918f3c5b8ba827750cd7b57f8d1a6a | 7,911 | py | Python | folium_maps.py | AlchemistPrimus/data_crunchers_knbs | b6d5a73bdbfed3f4a99e7047bd0747f3653a7fd2 | [
"MIT"
] | null | null | null | folium_maps.py | AlchemistPrimus/data_crunchers_knbs | b6d5a73bdbfed3f4a99e7047bd0747f3653a7fd2 | [
"MIT"
] | null | null | null | folium_maps.py | AlchemistPrimus/data_crunchers_knbs | b6d5a73bdbfed3f4a99e7047bd0747f3653a7fd2 | [
"MIT"
] | null | null | null | # Importing the necessary libraries
import pandas as pd
import geopandas as gpd
import fiona
import matplotlib.pyplot as plt
import folium
import os
from folium.plugins import StripePattern
dir=os.path.dirname("/home/ado/Desktop/new_datacranchers/data_crunchers_knbs/app/data_processing/open_source_data_values/folium_maps_data/")
# Loading the datasets
core_healthworkforce = gpd.read_file(os.path.join(dir,"core_healthworkforce.geojson"))
govt_open_late_night = gpd.read_file(os.path.join(dir,"govt_open_late_night.geojson"))
govt_open_public_holidays = gpd.read_file(os.path.join(dir,"govt_open_public_holidays.geojson"))
govt_open_weekends = gpd.read_file(os.path.join(dir,"govt_open_weekends.geojson"))
govt_open_whole_day = gpd.read_file(os.path.join(dir,'govt_open_whole_day.geojson'))
nongovt_open_late_night = gpd.read_file(os.path.join(dir,"nongovt_open_late_night.geojson"))
nongovt_open_public_holidays = gpd.read_file(os.path.join(dir,"nongovt_open_public_holidays.geojson"))
nongovt_open_weekends = gpd.read_file(os.path.join(dir,"nongovt_open_weekends.geojson"))
nongovt_open_whole_day = gpd.read_file(os.path.join(dir,'nongovt_open_whole_day.geojson'))
homes_with_fixed_internet = gpd.read_file(os.path.join(dir,"homes_fixed_with_internet.geojson"))
human_waste_disposal = gpd.read_file(os.path.join(dir,"human_waste_disposal.geojson"))
internet_through_mobile = gpd.read_file(os.path.join(dir,"internet_through_mobile.geojson"))
internet_users = gpd.read_file(os.path.join(dir,"internet_users.geojson"))
main_source_of_drinking_water = gpd.read_file(os.path.join(dir,"main_source_of_drinking_water.geojson"))
place_of_birth = gpd.read_file(os.path.join(dir,"place_of_birth.geojson"))
# Naming the dataframes
core_healthworkforce.name = 'core_healthworkforce'
govt_open_late_night.name = 'govt_open_late_night'
govt_open_public_holidays.name = 'govt_open_public_holidays'
govt_open_weekends.name = 'govt_open_weekends'
govt_open_whole_day.name = 'govt_open_whole_day'
nongovt_open_late_night.name = 'nongovt_open_late_night'
nongovt_open_public_holidays.name = 'nongovt_open_public_holidays'
nongovt_open_weekends.name = 'nongovt_open_weekends'
nongovt_open_whole_day.name = 'nongovt_open_whole_day'
homes_with_fixed_internet.name = 'homes_with_fixed_internet'
human_waste_disposal.name = 'human_waste_disposal'
internet_through_mobile.name = 'internet_through_mobile'
internet_users.name = 'internet_users'
main_source_of_drinking_water.name = 'main_source_of_drinking_water'
place_of_birth.name = 'place_of_birth'
# The mapping function
def mapping_func(geojson_data):
#creating Kenya map object
KEN=folium.Map(location=[0.0236,37.9062], zoom_start=7)
if geojson_data.name == 'core_healthworkforce':
clmn = ('objectid','\% change')
col = 'Greys'
nm = 'Healthworkforce'
lgd_name = ('Core Healthworkforce')
elif geojson_data.name == 'govt_open_late_night':
clmn = ('objectid','No')
col = 'Purples'
nm = 'Govt_Open_Late_Night'
lgd_name = ('Government Hospitals Open Late Night')
elif geojson_data.name == 'govt_open_public_holidays':
clmn = ('objectid','No')
col = 'Blues'
nm = 'Govt_Open_Public_Holidays'
lgd_name = ('Government Hospitals Open on Public Holidays')
elif geojson_data.name == 'govt_open_weekends':
clmn = ('objectid','No')
col = 'Greens'
nm = 'Govt_Open_Weekends'
lgd_name = ('Government Hospitals Open on Weekends')
elif geojson_data.name == 'govt_open_whole_day':
clmn = ('objectid','No')
col = 'Oranges'
nm = 'Govt_Open_Whole_Day'
lgd_name = ('Government Hospitals Open Whole Day')
elif geojson_data.name == 'nongovt_open_late_night':
clmn = ('objectid','No')
col = 'Reds'
nm = 'Nongovt_Open_Late_Night'
lgd_name = ('Non-Governmental Hospitals Open Late Night')
elif geojson_data.name == 'nongovt_open_public_holidays':
clmn = ('objectid','No')
col = 'YlOrBr'
nm = 'Nongovt_Open_Public_Holidays'
lgd_name = ('Non-Governmental Hospitals Open on Public Holidays')
elif geojson_data.name == 'nongovt_open_weekends':
clmn = ('objectid','No')
col = 'YlOrRd'
nm = 'Nongovt_Open_Weekends'
lgd_name = ('Non-Governmental Hospitals Open on Weekends')
elif geojson_data.name == 'nongovt_open_whole_day':
clmn = ('objectid','No')
col = 'OrRd'
nm = 'Nongovt_Open_Whole_Day'
lgd_name = ('Non-Governmental Hospitals Open Whole Day')
elif geojson_data.name == 'homes_with_fixed_internet':
clmn = ('objectid','No')
col = 'PuRd'
nm = 'Fixed_Internet'
lgd_name = ('Households with Fixed Internet at Home')
elif geojson_data.name == 'human_waste_disposal':
clmn = ('objectid','Improper')
col = 'RdPu'
nm = 'Human_Waste_Disposal'
lgd_name = ('Households Modes of Human Waste Disposal')
elif geojson_data.name == 'internet_through_mobile':
clmn = ('objectid','No')
col = 'BuPu'
nm = 'Internet_Through_Mobile'
lgd_name = ('Households that Accessed Internet Through Mobile')
elif geojson_data.name == 'internet_users':
clmn = ('objectid','No')
col = 'GnBu'
nm = 'Internet_Users'
lgd_name = ('Persons that Accessed Internet in the Last Three Months')
elif geojson_data.name == 'main_source_of_drinking_water':
clmn = ('objectid','Unsafe')
col = 'PuBu'
nm = 'Drinking_Water'
lgd_name = ('Households Main Source of Drinking Water')
else:
clmn = ('objectid','Non Health Facility')
col = 'YlGnBu'
nm = 'Place_Of_Birth'
lgd_name = ('Women who gave Birth in a Non-Health Facility')
choropleth= folium.Choropleth(
geo_data = geojson_data,
data=geojson_data,
columns= clmn,
key_on=('feature.properties.objectid'),
fill_color=(col),
fill_opacity=0.8,
nan_fill_opacity=0.4,
line_opacity=0.5,
name= nm,
show=True,
overlay=True,
legend_name= lgd_name,
highlight=True,
nan_fill_color = "black",
reset=True
).add_to(KEN)
# Add hover functionality.
style_function = lambda x: {'fillColor': '#ffffff',
'color':'#000000',
'fillOpacity': 0.1,
'weight': 0.1}
highlight_function = lambda x: {'fillColor': '#000000',
'color':'#000000',
'fillOpacity': 0.50,
'weight': 0.1}
# Add dark and light mode.
folium.TileLayer('cartodbdark_matter',name="dark mode",control=True).add_to(KEN)
folium.TileLayer('cartodbpositron',name="light mode",control=True).add_to(KEN)
# We add a layer controller.
folium.LayerControl(collapsed=False).add_to(KEN)
children = list(geojson_data.drop(['objectid', 'geometry'], axis=1).columns)
choropleth.geojson.add_child(folium.features.GeoJsonTooltip(children, labels=True))
return KEN.save('app/templates/maps_templates/'+nm+'.html')
#lst=['core_healthworkforce.geojson','govt_open_late_night.geojson','govt_open_public_holidays.geojson','govt_open_weekends.geojson','govt_open_whole_day.geojson','homes_fixed_with_internet.geojson','human_waste_disposal.geojson','internet_through_mobile.geojson','internet_users.geojson','main_source_of_drinking_water.geojson','nongovt_open_late_night.geojson','non_govt_open_public_holidays.geojson','nongovt_open_weekends.geojson','non_govt_open_whole_day.geojson','place_of_birth.geojson']
loc=os.path.join(dir,'core_healthworkforce.geojson')
file_=gpd.read_file(loc)
mapping_func(file_)
| 44.694915 | 494 | 0.69435 |
import pandas as pd
import geopandas as gpd
import fiona
import matplotlib.pyplot as plt
import folium
import os
from folium.plugins import StripePattern
dir=os.path.dirname("/home/ado/Desktop/new_datacranchers/data_crunchers_knbs/app/data_processing/open_source_data_values/folium_maps_data/")
core_healthworkforce = gpd.read_file(os.path.join(dir,"core_healthworkforce.geojson"))
govt_open_late_night = gpd.read_file(os.path.join(dir,"govt_open_late_night.geojson"))
govt_open_public_holidays = gpd.read_file(os.path.join(dir,"govt_open_public_holidays.geojson"))
govt_open_weekends = gpd.read_file(os.path.join(dir,"govt_open_weekends.geojson"))
govt_open_whole_day = gpd.read_file(os.path.join(dir,'govt_open_whole_day.geojson'))
nongovt_open_late_night = gpd.read_file(os.path.join(dir,"nongovt_open_late_night.geojson"))
nongovt_open_public_holidays = gpd.read_file(os.path.join(dir,"nongovt_open_public_holidays.geojson"))
nongovt_open_weekends = gpd.read_file(os.path.join(dir,"nongovt_open_weekends.geojson"))
nongovt_open_whole_day = gpd.read_file(os.path.join(dir,'nongovt_open_whole_day.geojson'))
homes_with_fixed_internet = gpd.read_file(os.path.join(dir,"homes_fixed_with_internet.geojson"))
human_waste_disposal = gpd.read_file(os.path.join(dir,"human_waste_disposal.geojson"))
internet_through_mobile = gpd.read_file(os.path.join(dir,"internet_through_mobile.geojson"))
internet_users = gpd.read_file(os.path.join(dir,"internet_users.geojson"))
main_source_of_drinking_water = gpd.read_file(os.path.join(dir,"main_source_of_drinking_water.geojson"))
place_of_birth = gpd.read_file(os.path.join(dir,"place_of_birth.geojson"))
core_healthworkforce.name = 'core_healthworkforce'
govt_open_late_night.name = 'govt_open_late_night'
govt_open_public_holidays.name = 'govt_open_public_holidays'
govt_open_weekends.name = 'govt_open_weekends'
govt_open_whole_day.name = 'govt_open_whole_day'
nongovt_open_late_night.name = 'nongovt_open_late_night'
nongovt_open_public_holidays.name = 'nongovt_open_public_holidays'
nongovt_open_weekends.name = 'nongovt_open_weekends'
nongovt_open_whole_day.name = 'nongovt_open_whole_day'
homes_with_fixed_internet.name = 'homes_with_fixed_internet'
human_waste_disposal.name = 'human_waste_disposal'
internet_through_mobile.name = 'internet_through_mobile'
internet_users.name = 'internet_users'
main_source_of_drinking_water.name = 'main_source_of_drinking_water'
place_of_birth.name = 'place_of_birth'
def mapping_func(geojson_data):
KEN=folium.Map(location=[0.0236,37.9062], zoom_start=7)
if geojson_data.name == 'core_healthworkforce':
clmn = ('objectid','\% change')
col = 'Greys'
nm = 'Healthworkforce'
lgd_name = ('Core Healthworkforce')
elif geojson_data.name == 'govt_open_late_night':
clmn = ('objectid','No')
col = 'Purples'
nm = 'Govt_Open_Late_Night'
lgd_name = ('Government Hospitals Open Late Night')
elif geojson_data.name == 'govt_open_public_holidays':
clmn = ('objectid','No')
col = 'Blues'
nm = 'Govt_Open_Public_Holidays'
lgd_name = ('Government Hospitals Open on Public Holidays')
elif geojson_data.name == 'govt_open_weekends':
clmn = ('objectid','No')
col = 'Greens'
nm = 'Govt_Open_Weekends'
lgd_name = ('Government Hospitals Open on Weekends')
elif geojson_data.name == 'govt_open_whole_day':
clmn = ('objectid','No')
col = 'Oranges'
nm = 'Govt_Open_Whole_Day'
lgd_name = ('Government Hospitals Open Whole Day')
elif geojson_data.name == 'nongovt_open_late_night':
clmn = ('objectid','No')
col = 'Reds'
nm = 'Nongovt_Open_Late_Night'
lgd_name = ('Non-Governmental Hospitals Open Late Night')
elif geojson_data.name == 'nongovt_open_public_holidays':
clmn = ('objectid','No')
col = 'YlOrBr'
nm = 'Nongovt_Open_Public_Holidays'
lgd_name = ('Non-Governmental Hospitals Open on Public Holidays')
elif geojson_data.name == 'nongovt_open_weekends':
clmn = ('objectid','No')
col = 'YlOrRd'
nm = 'Nongovt_Open_Weekends'
lgd_name = ('Non-Governmental Hospitals Open on Weekends')
elif geojson_data.name == 'nongovt_open_whole_day':
clmn = ('objectid','No')
col = 'OrRd'
nm = 'Nongovt_Open_Whole_Day'
lgd_name = ('Non-Governmental Hospitals Open Whole Day')
elif geojson_data.name == 'homes_with_fixed_internet':
clmn = ('objectid','No')
col = 'PuRd'
nm = 'Fixed_Internet'
lgd_name = ('Households with Fixed Internet at Home')
elif geojson_data.name == 'human_waste_disposal':
clmn = ('objectid','Improper')
col = 'RdPu'
nm = 'Human_Waste_Disposal'
lgd_name = ('Households Modes of Human Waste Disposal')
elif geojson_data.name == 'internet_through_mobile':
clmn = ('objectid','No')
col = 'BuPu'
nm = 'Internet_Through_Mobile'
lgd_name = ('Households that Accessed Internet Through Mobile')
elif geojson_data.name == 'internet_users':
clmn = ('objectid','No')
col = 'GnBu'
nm = 'Internet_Users'
lgd_name = ('Persons that Accessed Internet in the Last Three Months')
elif geojson_data.name == 'main_source_of_drinking_water':
clmn = ('objectid','Unsafe')
col = 'PuBu'
nm = 'Drinking_Water'
lgd_name = ('Households Main Source of Drinking Water')
else:
clmn = ('objectid','Non Health Facility')
col = 'YlGnBu'
nm = 'Place_Of_Birth'
lgd_name = ('Women who gave Birth in a Non-Health Facility')
choropleth= folium.Choropleth(
geo_data = geojson_data,
data=geojson_data,
columns= clmn,
key_on=('feature.properties.objectid'),
fill_color=(col),
fill_opacity=0.8,
nan_fill_opacity=0.4,
line_opacity=0.5,
name= nm,
show=True,
overlay=True,
legend_name= lgd_name,
highlight=True,
nan_fill_color = "black",
reset=True
).add_to(KEN)
style_function = lambda x: {'fillColor': '#ffffff',
'color':'#000000',
'fillOpacity': 0.1,
'weight': 0.1}
highlight_function = lambda x: {'fillColor': '#000000',
'color':'#000000',
'fillOpacity': 0.50,
'weight': 0.1}
folium.TileLayer('cartodbdark_matter',name="dark mode",control=True).add_to(KEN)
folium.TileLayer('cartodbpositron',name="light mode",control=True).add_to(KEN)
folium.LayerControl(collapsed=False).add_to(KEN)
children = list(geojson_data.drop(['objectid', 'geometry'], axis=1).columns)
choropleth.geojson.add_child(folium.features.GeoJsonTooltip(children, labels=True))
return KEN.save('app/templates/maps_templates/'+nm+'.html')
loc=os.path.join(dir,'core_healthworkforce.geojson')
file_=gpd.read_file(loc)
mapping_func(file_)
| true | true |
f73b93defe6ee4a59d12ac0a35ff6e564397e369 | 3,830 | py | Python | src/python/twitter/common/git/__init__.py | zhouyijiaren/commons | 10df6fb63547baa9047782aa7ad4edf354914b10 | [
"Apache-2.0"
] | 1,143 | 2015-01-05T04:19:24.000Z | 2019-12-11T12:02:23.000Z | src/python/twitter/common/git/__init__.py | zhouyijiaren/commons | 10df6fb63547baa9047782aa7ad4edf354914b10 | [
"Apache-2.0"
] | 144 | 2015-01-06T05:05:07.000Z | 2019-12-12T18:02:37.000Z | src/python/twitter/common/git/__init__.py | zhouyijiaren/commons | 10df6fb63547baa9047782aa7ad4edf354914b10 | [
"Apache-2.0"
] | 426 | 2015-01-08T08:33:41.000Z | 2019-12-09T13:15:40.000Z | # ==================================================================================================
# Copyright 2012 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the License.
# You may obtain a copy of the License in the LICENSE file, or 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 __future__ import print_function
import contextlib
from twitter.common.lang import Compatibility
import git
__all__ = (
'DirtyRepositoryError',
'branch',
'checkout',
)
class DirtyRepositoryError(Exception):
def __init__(self, branch=None):
super(DirtyRepositoryError, self).__init__('%s must not be dirty!' % (
'Current branch (%s)' % branch if branch else 'Current branch'))
def validate_args(sha, project, repo=None):
"""Validates arguments and returns head, repo, branch_name"""
repo = repo or git.Repo()
active_head = repo.active_branch
if repo.is_dirty():
raise DirtyRepositoryError(active_head)
else:
print('Active head: %s' % active_head)
branch_name = '_%s_' % sha
if project:
if not isinstance(project, Compatibility.string):
raise ValueError('project must be a string, got %r' % (project,))
branch_name = '_' + project + branch_name
return active_head, repo, branch_name
def checkout_branch(repo, sha, branch_name):
print('Creating head %s' % branch_name)
head = repo.create_head(branch_name)
head.commit = repo.commit(sha) if isinstance(sha, Compatibility.string) else sha
head.checkout()
@contextlib.contextmanager
def branch(sha, project=None, repo=None):
"""
Perform actions at a given sha in a repository. Implemented as a context manager.
Must be run in the CWD of a git repository.
:param sha: A fully-qualified revision as specified in
http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html
:param project: (optional) A label to prepend to the temporary branch.
:param repo: (optional) The location of the .git repository (by default current working directory.)
Example:
>>> import subprocess
>>> from twitter.common.git import branch
>>> with branch('master@{yesterday}'):
... subprocess.check_call('./pants tests/python/twitter/common:all')
"""
active_head, repo, branch_name = validate_args(sha, project, repo)
try:
checkout_branch(repo, sha, branch_name)
yield
finally:
print('Resetting head: %s' % active_head)
active_head.checkout()
print('Deleting temporary head: %s' % branch_name)
repo.delete_head(branch_name, force=True)
def checkout(sha, project=None, repo=None):
"""
Checkout a sha in a given repository.
:param sha: A fully-qualified revision as specified in
http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html
:param project: (optional) A label to prepend to the temporary branch.
:param repo: (optional) The location of the .git repository (by default current working directory.)
If project is supplied, generate a more readable branch name based upon
the project name.
If repo is supplied, it should be the location of the git repository.
"""
_, repo, branch_name = validate_args(sha, project, repo)
checkout_branch(repo, sha, branch_name)
| 34.196429 | 103 | 0.663185 |
from __future__ import print_function
import contextlib
from twitter.common.lang import Compatibility
import git
__all__ = (
'DirtyRepositoryError',
'branch',
'checkout',
)
class DirtyRepositoryError(Exception):
def __init__(self, branch=None):
super(DirtyRepositoryError, self).__init__('%s must not be dirty!' % (
'Current branch (%s)' % branch if branch else 'Current branch'))
def validate_args(sha, project, repo=None):
repo = repo or git.Repo()
active_head = repo.active_branch
if repo.is_dirty():
raise DirtyRepositoryError(active_head)
else:
print('Active head: %s' % active_head)
branch_name = '_%s_' % sha
if project:
if not isinstance(project, Compatibility.string):
raise ValueError('project must be a string, got %r' % (project,))
branch_name = '_' + project + branch_name
return active_head, repo, branch_name
def checkout_branch(repo, sha, branch_name):
print('Creating head %s' % branch_name)
head = repo.create_head(branch_name)
head.commit = repo.commit(sha) if isinstance(sha, Compatibility.string) else sha
head.checkout()
@contextlib.contextmanager
def branch(sha, project=None, repo=None):
active_head, repo, branch_name = validate_args(sha, project, repo)
try:
checkout_branch(repo, sha, branch_name)
yield
finally:
print('Resetting head: %s' % active_head)
active_head.checkout()
print('Deleting temporary head: %s' % branch_name)
repo.delete_head(branch_name, force=True)
def checkout(sha, project=None, repo=None):
_, repo, branch_name = validate_args(sha, project, repo)
checkout_branch(repo, sha, branch_name)
| true | true |
f73b9404900e5880147a1838a38652cc7c29e1c3 | 413 | py | Python | annotation_project/wsgi.py | meisin/annotation_project | 158e33b86eef05e6e11a09938149d6f9737eec2c | [
"MIT"
] | null | null | null | annotation_project/wsgi.py | meisin/annotation_project | 158e33b86eef05e6e11a09938149d6f9737eec2c | [
"MIT"
] | null | null | null | annotation_project/wsgi.py | meisin/annotation_project | 158e33b86eef05e6e11a09938149d6f9737eec2c | [
"MIT"
] | null | null | null | """
WSGI config for annotation_project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'annotation_project.settings')
application = get_wsgi_application()
| 24.294118 | 78 | 0.79661 |
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'annotation_project.settings')
application = get_wsgi_application()
| true | true |
f73b951c5372de73def2e8f15ff4ec2835e78330 | 505 | py | Python | exoplanets/models.py | zemogle/astropony | fc82f4398ddb2bebcce3bf0dc600eb0171392a1a | [
"MIT"
] | null | null | null | exoplanets/models.py | zemogle/astropony | fc82f4398ddb2bebcce3bf0dc600eb0171392a1a | [
"MIT"
] | null | null | null | exoplanets/models.py | zemogle/astropony | fc82f4398ddb2bebcce3bf0dc600eb0171392a1a | [
"MIT"
] | null | null | null | from django.db import models
class Mission(models.Model):
name = models.CharField(max_length=200)
start_date = models.DateTimeField('date discovered')
def __unicode__(self):
return self.name
class Planet(models.Model):
name = models.CharField(max_length=200)
discovery_date = models.DateTimeField('date discovered')
mass = models.FloatField()
radius = models.FloatField()
misson = models.ForeignKey(Mission)
def __unicode__(self):
return self.name
| 25.25 | 60 | 0.708911 | from django.db import models
class Mission(models.Model):
name = models.CharField(max_length=200)
start_date = models.DateTimeField('date discovered')
def __unicode__(self):
return self.name
class Planet(models.Model):
name = models.CharField(max_length=200)
discovery_date = models.DateTimeField('date discovered')
mass = models.FloatField()
radius = models.FloatField()
misson = models.ForeignKey(Mission)
def __unicode__(self):
return self.name
| true | true |
f73b96ad5235bf6c02bb882592c8fa46f4320505 | 722 | py | Python | tests/test_classifier_evaluator.py | edublancas/sklearn-model-evaluation | 1f35d5bcc689a5f4d54c14fde60abf09af9fc374 | [
"MIT"
] | 351 | 2016-01-27T19:15:27.000Z | 2022-03-09T15:40:56.000Z | tests/test_classifier_evaluator.py | edublancas/sklearn-model-evaluation | 1f35d5bcc689a5f4d54c14fde60abf09af9fc374 | [
"MIT"
] | 37 | 2016-03-16T03:57:59.000Z | 2021-06-26T14:02:33.000Z | tests/test_classifier_evaluator.py | edublancas/sklearn-model-evaluation | 1f35d5bcc689a5f4d54c14fde60abf09af9fc374 | [
"MIT"
] | 30 | 2016-01-27T19:27:08.000Z | 2022-03-31T06:09:59.000Z | from sklearn_evaluation import ClassifierEvaluator
# import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
def test_can_plot():
data = datasets.make_classification(200,
10,
n_informative=5,
class_sep=0.65)
X = data[0]
y = data[1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
est = RandomForestClassifier()
est.fit(X_train, y_train)
evaluator = ClassifierEvaluator(est, y_true=y_test, X=X_test)
evaluator.confusion_matrix()
| 28.88 | 76 | 0.635734 | from sklearn_evaluation import ClassifierEvaluator
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
def test_can_plot():
data = datasets.make_classification(200,
10,
n_informative=5,
class_sep=0.65)
X = data[0]
y = data[1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
est = RandomForestClassifier()
est.fit(X_train, y_train)
evaluator = ClassifierEvaluator(est, y_true=y_test, X=X_test)
evaluator.confusion_matrix()
| true | true |
f73b96b04bd569769b47b3ebd11ac480cc73ca36 | 687 | py | Python | Upload/app.py | bitshop/sam-PresignedS3Trigger | 8ea435e8a4aaff0fefda5df802b78a43aaee6422 | [
"MIT"
] | null | null | null | Upload/app.py | bitshop/sam-PresignedS3Trigger | 8ea435e8a4aaff0fefda5df802b78a43aaee6422 | [
"MIT"
] | null | null | null | Upload/app.py | bitshop/sam-PresignedS3Trigger | 8ea435e8a4aaff0fefda5df802b78a43aaee6422 | [
"MIT"
] | null | null | null | import requests
import pprint
# Configuration:
# filename = file to upload
filename='app.py'
# url = GET API for presigning
url = "https://vqdrwi0ee1.execute-api.us-east-1.amazonaws.com/Prod/PreSign"
# Get presign response
result = requests.get(url).json()
# Print some debug information
pp = pprint.PrettyPrinter(indent=4)
print ("Result from URL:")
pp.pprint(result)
print ("Send to: {}".format(result['url']))
# Get URL information for upload:
presign = result['url']
#Upload file to S3 using presigned URL
r = requests.post(presign['url'], data=presign['fields'], files={ 'file': open(filename, 'rb')})
# Expect a 204 (no response) for a successful upload
print(r.status_code) | 25.444444 | 96 | 0.724891 | import requests
import pprint
filename='app.py'
url = "https://vqdrwi0ee1.execute-api.us-east-1.amazonaws.com/Prod/PreSign"
result = requests.get(url).json()
pp = pprint.PrettyPrinter(indent=4)
print ("Result from URL:")
pp.pprint(result)
print ("Send to: {}".format(result['url']))
presign = result['url']
r = requests.post(presign['url'], data=presign['fields'], files={ 'file': open(filename, 'rb')})
print(r.status_code) | true | true |
f73b96dca5565331f69bd92053d81d92907d09dd | 330 | py | Python | AdventOfCode/2020/day1/day1-pt1.py | neiesc/Problem-solving | d3bce7a3b9801e6049e2c135418b31cba47b0964 | [
"MIT"
] | 1 | 2019-07-20T16:59:21.000Z | 2019-07-20T16:59:21.000Z | AdventOfCode/2020/day1/day1-pt1.py | neiesc/Problem-solving | d3bce7a3b9801e6049e2c135418b31cba47b0964 | [
"MIT"
] | 5 | 2019-03-10T19:46:42.000Z | 2020-04-24T22:42:30.000Z | AdventOfCode/2020/day1/day1-pt1.py | neiesc/Problem-solving | d3bce7a3b9801e6049e2c135418b31cba47b0964 | [
"MIT"
] | null | null | null | with open("input.txt", "r") as f:
lines = f.readlines()
for line1 in lines:
for line2 in lines:
total = int(line1) + int(line2)
if total == 2020:
print(f"line1: {line1}")
print(f"line2: {line2}")
print(f"Multiply: {int(line1) * int(line2)}") | 36.666667 | 61 | 0.481818 | with open("input.txt", "r") as f:
lines = f.readlines()
for line1 in lines:
for line2 in lines:
total = int(line1) + int(line2)
if total == 2020:
print(f"line1: {line1}")
print(f"line2: {line2}")
print(f"Multiply: {int(line1) * int(line2)}") | true | true |
f73b9778f6a9ffca618825b57fbf365955dc0ccb | 18,705 | py | Python | youtube_dl/extractor/xhamster.py | jonyg80/youtube-dl | ef3a87fb77891329de1d3dbebfee53bf50645261 | [
"Unlicense"
] | 66,635 | 2019-03-10T21:34:18.000Z | 2022-03-31T23:50:31.000Z | youtube_dl/extractor/xhamster.py | jonyg80/youtube-dl | ef3a87fb77891329de1d3dbebfee53bf50645261 | [
"Unlicense"
] | 10,936 | 2019-03-10T21:35:47.000Z | 2022-03-31T23:46:52.000Z | youtube_dl/extractor/xhamster.py | jonyg80/youtube-dl | ef3a87fb77891329de1d3dbebfee53bf50645261 | [
"Unlicense"
] | 15,194 | 2019-03-10T21:09:27.000Z | 2022-03-31T22:13:49.000Z | from __future__ import unicode_literals
import itertools
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
clean_html,
determine_ext,
dict_get,
extract_attributes,
ExtractorError,
float_or_none,
int_or_none,
parse_duration,
str_or_none,
try_get,
unified_strdate,
url_or_none,
urljoin,
)
class XHamsterIE(InfoExtractor):
_DOMAINS = r'(?:xhamster\.(?:com|one|desi)|xhms\.pro|xhamster\d+\.com)'
_VALID_URL = r'''(?x)
https?://
(?:.+?\.)?%s/
(?:
movies/(?P<id>[\dA-Za-z]+)/(?P<display_id>[^/]*)\.html|
videos/(?P<display_id_2>[^/]*)-(?P<id_2>[\dA-Za-z]+)
)
''' % _DOMAINS
_TESTS = [{
'url': 'https://xhamster.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
'md5': '98b4687efb1ffd331c4197854dc09e8f',
'info_dict': {
'id': '1509445',
'display_id': 'femaleagent-shy-beauty-takes-the-bait',
'ext': 'mp4',
'title': 'FemaleAgent Shy beauty takes the bait',
'timestamp': 1350194821,
'upload_date': '20121014',
'uploader': 'Ruseful2011',
'duration': 893,
'age_limit': 18,
},
}, {
'url': 'https://xhamster.com/videos/britney-spears-sexy-booty-2221348?hd=',
'info_dict': {
'id': '2221348',
'display_id': 'britney-spears-sexy-booty',
'ext': 'mp4',
'title': 'Britney Spears Sexy Booty',
'timestamp': 1379123460,
'upload_date': '20130914',
'uploader': 'jojo747400',
'duration': 200,
'age_limit': 18,
},
'params': {
'skip_download': True,
},
}, {
# empty seo, unavailable via new URL schema
'url': 'http://xhamster.com/movies/5667973/.html',
'info_dict': {
'id': '5667973',
'ext': 'mp4',
'title': '....',
'timestamp': 1454948101,
'upload_date': '20160208',
'uploader': 'parejafree',
'duration': 72,
'age_limit': 18,
},
'params': {
'skip_download': True,
},
}, {
# mobile site
'url': 'https://m.xhamster.com/videos/cute-teen-jacqueline-solo-masturbation-8559111',
'only_matching': True,
}, {
'url': 'https://xhamster.com/movies/2272726/amber_slayed_by_the_knight.html',
'only_matching': True,
}, {
# This video is visible for marcoalfa123456's friends only
'url': 'https://it.xhamster.com/movies/7263980/la_mia_vicina.html',
'only_matching': True,
}, {
# new URL schema
'url': 'https://pt.xhamster.com/videos/euro-pedal-pumping-7937821',
'only_matching': True,
}, {
'url': 'https://xhamster.one/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
'only_matching': True,
}, {
'url': 'https://xhamster.desi/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
'only_matching': True,
}, {
'url': 'https://xhamster2.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
'only_matching': True,
}, {
'url': 'https://xhamster11.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
'only_matching': True,
}, {
'url': 'https://xhamster26.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
'only_matching': True,
}, {
'url': 'http://xhamster.com/movies/1509445/femaleagent_shy_beauty_takes_the_bait.html',
'only_matching': True,
}, {
'url': 'http://xhamster.com/movies/2221348/britney_spears_sexy_booty.html?hd',
'only_matching': True,
}, {
'url': 'http://de.xhamster.com/videos/skinny-girl-fucks-herself-hard-in-the-forest-xhnBJZx',
'only_matching': True,
}]
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id') or mobj.group('id_2')
display_id = mobj.group('display_id') or mobj.group('display_id_2')
desktop_url = re.sub(r'^(https?://(?:.+?\.)?)m\.', r'\1', url)
webpage, urlh = self._download_webpage_handle(desktop_url, video_id)
error = self._html_search_regex(
r'<div[^>]+id=["\']videoClosed["\'][^>]*>(.+?)</div>',
webpage, 'error', default=None)
if error:
raise ExtractorError(error, expected=True)
age_limit = self._rta_search(webpage)
def get_height(s):
return int_or_none(self._search_regex(
r'^(\d+)[pP]', s, 'height', default=None))
initials = self._parse_json(
self._search_regex(
(r'window\.initials\s*=\s*({.+?})\s*;\s*</script>',
r'window\.initials\s*=\s*({.+?})\s*;'), webpage, 'initials',
default='{}'),
video_id, fatal=False)
if initials:
video = initials['videoModel']
title = video['title']
formats = []
format_urls = set()
format_sizes = {}
sources = try_get(video, lambda x: x['sources'], dict) or {}
for format_id, formats_dict in sources.items():
if not isinstance(formats_dict, dict):
continue
download_sources = try_get(sources, lambda x: x['download'], dict) or {}
for quality, format_dict in download_sources.items():
if not isinstance(format_dict, dict):
continue
format_sizes[quality] = float_or_none(format_dict.get('size'))
for quality, format_item in formats_dict.items():
if format_id == 'download':
# Download link takes some time to be generated,
# skipping for now
continue
format_url = format_item
format_url = url_or_none(format_url)
if not format_url or format_url in format_urls:
continue
format_urls.add(format_url)
formats.append({
'format_id': '%s-%s' % (format_id, quality),
'url': format_url,
'ext': determine_ext(format_url, 'mp4'),
'height': get_height(quality),
'filesize': format_sizes.get(quality),
'http_headers': {
'Referer': urlh.geturl(),
},
})
xplayer_sources = try_get(
initials, lambda x: x['xplayerSettings']['sources'], dict)
if xplayer_sources:
hls_sources = xplayer_sources.get('hls')
if isinstance(hls_sources, dict):
for hls_format_key in ('url', 'fallback'):
hls_url = hls_sources.get(hls_format_key)
if not hls_url:
continue
hls_url = urljoin(url, hls_url)
if not hls_url or hls_url in format_urls:
continue
format_urls.add(hls_url)
formats.extend(self._extract_m3u8_formats(
hls_url, video_id, 'mp4', entry_protocol='m3u8_native',
m3u8_id='hls', fatal=False))
standard_sources = xplayer_sources.get('standard')
if isinstance(standard_sources, dict):
for format_id, formats_list in standard_sources.items():
if not isinstance(formats_list, list):
continue
for standard_format in formats_list:
if not isinstance(standard_format, dict):
continue
for standard_format_key in ('url', 'fallback'):
standard_url = standard_format.get(standard_format_key)
if not standard_url:
continue
standard_url = urljoin(url, standard_url)
if not standard_url or standard_url in format_urls:
continue
format_urls.add(standard_url)
ext = determine_ext(standard_url, 'mp4')
if ext == 'm3u8':
formats.extend(self._extract_m3u8_formats(
standard_url, video_id, 'mp4', entry_protocol='m3u8_native',
m3u8_id='hls', fatal=False))
continue
quality = (str_or_none(standard_format.get('quality'))
or str_or_none(standard_format.get('label'))
or '')
formats.append({
'format_id': '%s-%s' % (format_id, quality),
'url': standard_url,
'ext': ext,
'height': get_height(quality),
'filesize': format_sizes.get(quality),
'http_headers': {
'Referer': standard_url,
},
})
self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
categories_list = video.get('categories')
if isinstance(categories_list, list):
categories = []
for c in categories_list:
if not isinstance(c, dict):
continue
c_name = c.get('name')
if isinstance(c_name, compat_str):
categories.append(c_name)
else:
categories = None
return {
'id': video_id,
'display_id': display_id,
'title': title,
'description': video.get('description'),
'timestamp': int_or_none(video.get('created')),
'uploader': try_get(
video, lambda x: x['author']['name'], compat_str),
'thumbnail': video.get('thumbURL'),
'duration': int_or_none(video.get('duration')),
'view_count': int_or_none(video.get('views')),
'like_count': int_or_none(try_get(
video, lambda x: x['rating']['likes'], int)),
'dislike_count': int_or_none(try_get(
video, lambda x: x['rating']['dislikes'], int)),
'comment_count': int_or_none(video.get('views')),
'age_limit': age_limit,
'categories': categories,
'formats': formats,
}
# Old layout fallback
title = self._html_search_regex(
[r'<h1[^>]*>([^<]+)</h1>',
r'<meta[^>]+itemprop=".*?caption.*?"[^>]+content="(.+?)"',
r'<title[^>]*>(.+?)(?:,\s*[^,]*?\s*Porn\s*[^,]*?:\s*xHamster[^<]*| - xHamster\.com)</title>'],
webpage, 'title')
formats = []
format_urls = set()
sources = self._parse_json(
self._search_regex(
r'sources\s*:\s*({.+?})\s*,?\s*\n', webpage, 'sources',
default='{}'),
video_id, fatal=False)
for format_id, format_url in sources.items():
format_url = url_or_none(format_url)
if not format_url:
continue
if format_url in format_urls:
continue
format_urls.add(format_url)
formats.append({
'format_id': format_id,
'url': format_url,
'height': get_height(format_id),
})
video_url = self._search_regex(
[r'''file\s*:\s*(?P<q>["'])(?P<mp4>.+?)(?P=q)''',
r'''<a\s+href=(?P<q>["'])(?P<mp4>.+?)(?P=q)\s+class=["']mp4Thumb''',
r'''<video[^>]+file=(?P<q>["'])(?P<mp4>.+?)(?P=q)[^>]*>'''],
webpage, 'video url', group='mp4', default=None)
if video_url and video_url not in format_urls:
formats.append({
'url': video_url,
})
self._sort_formats(formats)
# Only a few videos have an description
mobj = re.search(r'<span>Description: </span>([^<]+)', webpage)
description = mobj.group(1) if mobj else None
upload_date = unified_strdate(self._search_regex(
r'hint=["\'](\d{4}-\d{2}-\d{2}) \d{2}:\d{2}:\d{2} [A-Z]{3,4}',
webpage, 'upload date', fatal=False))
uploader = self._html_search_regex(
r'<span[^>]+itemprop=["\']author[^>]+><a[^>]+><span[^>]+>([^<]+)',
webpage, 'uploader', default='anonymous')
thumbnail = self._search_regex(
[r'''["']thumbUrl["']\s*:\s*(?P<q>["'])(?P<thumbnail>.+?)(?P=q)''',
r'''<video[^>]+"poster"=(?P<q>["'])(?P<thumbnail>.+?)(?P=q)[^>]*>'''],
webpage, 'thumbnail', fatal=False, group='thumbnail')
duration = parse_duration(self._search_regex(
[r'<[^<]+\bitemprop=["\']duration["\'][^<]+\bcontent=["\'](.+?)["\']',
r'Runtime:\s*</span>\s*([\d:]+)'], webpage,
'duration', fatal=False))
view_count = int_or_none(self._search_regex(
r'content=["\']User(?:View|Play)s:(\d+)',
webpage, 'view count', fatal=False))
mobj = re.search(r'hint=[\'"](?P<likecount>\d+) Likes / (?P<dislikecount>\d+) Dislikes', webpage)
(like_count, dislike_count) = (mobj.group('likecount'), mobj.group('dislikecount')) if mobj else (None, None)
mobj = re.search(r'</label>Comments \((?P<commentcount>\d+)\)</div>', webpage)
comment_count = mobj.group('commentcount') if mobj else 0
categories_html = self._search_regex(
r'(?s)<table.+?(<span>Categories:.+?)</table>', webpage,
'categories', default=None)
categories = [clean_html(category) for category in re.findall(
r'<a[^>]+>(.+?)</a>', categories_html)] if categories_html else None
return {
'id': video_id,
'display_id': display_id,
'title': title,
'description': description,
'upload_date': upload_date,
'uploader': uploader,
'thumbnail': thumbnail,
'duration': duration,
'view_count': view_count,
'like_count': int_or_none(like_count),
'dislike_count': int_or_none(dislike_count),
'comment_count': int_or_none(comment_count),
'age_limit': age_limit,
'categories': categories,
'formats': formats,
}
class XHamsterEmbedIE(InfoExtractor):
_VALID_URL = r'https?://(?:.+?\.)?%s/xembed\.php\?video=(?P<id>\d+)' % XHamsterIE._DOMAINS
_TEST = {
'url': 'http://xhamster.com/xembed.php?video=3328539',
'info_dict': {
'id': '3328539',
'ext': 'mp4',
'title': 'Pen Masturbation',
'timestamp': 1406581861,
'upload_date': '20140728',
'uploader': 'ManyakisArt',
'duration': 5,
'age_limit': 18,
}
}
@staticmethod
def _extract_urls(webpage):
return [url for _, url in re.findall(
r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?xhamster\.com/xembed\.php\?video=\d+)\1',
webpage)]
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
video_url = self._search_regex(
r'href="(https?://xhamster\.com/(?:movies/{0}/[^"]*\.html|videos/[^/]*-{0})[^"]*)"'.format(video_id),
webpage, 'xhamster url', default=None)
if not video_url:
vars = self._parse_json(
self._search_regex(r'vars\s*:\s*({.+?})\s*,\s*\n', webpage, 'vars'),
video_id)
video_url = dict_get(vars, ('downloadLink', 'homepageLink', 'commentsLink', 'shareUrl'))
return self.url_result(video_url, 'XHamster')
class XHamsterUserIE(InfoExtractor):
_VALID_URL = r'https?://(?:.+?\.)?%s/users/(?P<id>[^/?#&]+)' % XHamsterIE._DOMAINS
_TESTS = [{
# Paginated user profile
'url': 'https://xhamster.com/users/netvideogirls/videos',
'info_dict': {
'id': 'netvideogirls',
},
'playlist_mincount': 267,
}, {
# Non-paginated user profile
'url': 'https://xhamster.com/users/firatkaan/videos',
'info_dict': {
'id': 'firatkaan',
},
'playlist_mincount': 1,
}]
def _entries(self, user_id):
next_page_url = 'https://xhamster.com/users/%s/videos/1' % user_id
for pagenum in itertools.count(1):
page = self._download_webpage(
next_page_url, user_id, 'Downloading page %s' % pagenum)
for video_tag in re.findall(
r'(<a[^>]+class=["\'].*?\bvideo-thumb__image-container[^>]+>)',
page):
video = extract_attributes(video_tag)
video_url = url_or_none(video.get('href'))
if not video_url or not XHamsterIE.suitable(video_url):
continue
video_id = XHamsterIE._match_id(video_url)
yield self.url_result(
video_url, ie=XHamsterIE.ie_key(), video_id=video_id)
mobj = re.search(r'<a[^>]+data-page=["\']next[^>]+>', page)
if not mobj:
break
next_page = extract_attributes(mobj.group(0))
next_page_url = url_or_none(next_page.get('href'))
if not next_page_url:
break
def _real_extract(self, url):
user_id = self._match_id(url)
return self.playlist_result(self._entries(user_id), user_id)
| 41.474501 | 117 | 0.493077 | from __future__ import unicode_literals
import itertools
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
clean_html,
determine_ext,
dict_get,
extract_attributes,
ExtractorError,
float_or_none,
int_or_none,
parse_duration,
str_or_none,
try_get,
unified_strdate,
url_or_none,
urljoin,
)
class XHamsterIE(InfoExtractor):
_DOMAINS = r'(?:xhamster\.(?:com|one|desi)|xhms\.pro|xhamster\d+\.com)'
_VALID_URL = r'''(?x)
https?://
(?:.+?\.)?%s/
(?:
movies/(?P<id>[\dA-Za-z]+)/(?P<display_id>[^/]*)\.html|
videos/(?P<display_id_2>[^/]*)-(?P<id_2>[\dA-Za-z]+)
)
''' % _DOMAINS
_TESTS = [{
'url': 'https://xhamster.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
'md5': '98b4687efb1ffd331c4197854dc09e8f',
'info_dict': {
'id': '1509445',
'display_id': 'femaleagent-shy-beauty-takes-the-bait',
'ext': 'mp4',
'title': 'FemaleAgent Shy beauty takes the bait',
'timestamp': 1350194821,
'upload_date': '20121014',
'uploader': 'Ruseful2011',
'duration': 893,
'age_limit': 18,
},
}, {
'url': 'https://xhamster.com/videos/britney-spears-sexy-booty-2221348?hd=',
'info_dict': {
'id': '2221348',
'display_id': 'britney-spears-sexy-booty',
'ext': 'mp4',
'title': 'Britney Spears Sexy Booty',
'timestamp': 1379123460,
'upload_date': '20130914',
'uploader': 'jojo747400',
'duration': 200,
'age_limit': 18,
},
'params': {
'skip_download': True,
},
}, {
'url': 'http://xhamster.com/movies/5667973/.html',
'info_dict': {
'id': '5667973',
'ext': 'mp4',
'title': '....',
'timestamp': 1454948101,
'upload_date': '20160208',
'uploader': 'parejafree',
'duration': 72,
'age_limit': 18,
},
'params': {
'skip_download': True,
},
}, {
'url': 'https://m.xhamster.com/videos/cute-teen-jacqueline-solo-masturbation-8559111',
'only_matching': True,
}, {
'url': 'https://xhamster.com/movies/2272726/amber_slayed_by_the_knight.html',
'only_matching': True,
}, {
'url': 'https://it.xhamster.com/movies/7263980/la_mia_vicina.html',
'only_matching': True,
}, {
# new URL schema
'url': 'https://pt.xhamster.com/videos/euro-pedal-pumping-7937821',
'only_matching': True,
}, {
'url': 'https://xhamster.one/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
'only_matching': True,
}, {
'url': 'https://xhamster.desi/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
'only_matching': True,
}, {
'url': 'https://xhamster2.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
'only_matching': True,
}, {
'url': 'https://xhamster11.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
'only_matching': True,
}, {
'url': 'https://xhamster26.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
'only_matching': True,
}, {
'url': 'http://xhamster.com/movies/1509445/femaleagent_shy_beauty_takes_the_bait.html',
'only_matching': True,
}, {
'url': 'http://xhamster.com/movies/2221348/britney_spears_sexy_booty.html?hd',
'only_matching': True,
}, {
'url': 'http://de.xhamster.com/videos/skinny-girl-fucks-herself-hard-in-the-forest-xhnBJZx',
'only_matching': True,
}]
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id') or mobj.group('id_2')
display_id = mobj.group('display_id') or mobj.group('display_id_2')
desktop_url = re.sub(r'^(https?://(?:.+?\.)?)m\.', r'\1', url)
webpage, urlh = self._download_webpage_handle(desktop_url, video_id)
error = self._html_search_regex(
r'<div[^>]+id=["\']videoClosed["\'][^>]*>(.+?)</div>',
webpage, 'error', default=None)
if error:
raise ExtractorError(error, expected=True)
age_limit = self._rta_search(webpage)
def get_height(s):
return int_or_none(self._search_regex(
r'^(\d+)[pP]', s, 'height', default=None))
initials = self._parse_json(
self._search_regex(
(r'window\.initials\s*=\s*({.+?})\s*;\s*</script>',
r'window\.initials\s*=\s*({.+?})\s*;'), webpage, 'initials',
default='{}'),
video_id, fatal=False)
if initials:
video = initials['videoModel']
title = video['title']
formats = []
format_urls = set()
format_sizes = {}
sources = try_get(video, lambda x: x['sources'], dict) or {}
for format_id, formats_dict in sources.items():
if not isinstance(formats_dict, dict):
continue
download_sources = try_get(sources, lambda x: x['download'], dict) or {}
for quality, format_dict in download_sources.items():
if not isinstance(format_dict, dict):
continue
format_sizes[quality] = float_or_none(format_dict.get('size'))
for quality, format_item in formats_dict.items():
if format_id == 'download':
# Download link takes some time to be generated,
# skipping for now
continue
format_url = format_item
format_url = url_or_none(format_url)
if not format_url or format_url in format_urls:
continue
format_urls.add(format_url)
formats.append({
'format_id': '%s-%s' % (format_id, quality),
'url': format_url,
'ext': determine_ext(format_url, 'mp4'),
'height': get_height(quality),
'filesize': format_sizes.get(quality),
'http_headers': {
'Referer': urlh.geturl(),
},
})
xplayer_sources = try_get(
initials, lambda x: x['xplayerSettings']['sources'], dict)
if xplayer_sources:
hls_sources = xplayer_sources.get('hls')
if isinstance(hls_sources, dict):
for hls_format_key in ('url', 'fallback'):
hls_url = hls_sources.get(hls_format_key)
if not hls_url:
continue
hls_url = urljoin(url, hls_url)
if not hls_url or hls_url in format_urls:
continue
format_urls.add(hls_url)
formats.extend(self._extract_m3u8_formats(
hls_url, video_id, 'mp4', entry_protocol='m3u8_native',
m3u8_id='hls', fatal=False))
standard_sources = xplayer_sources.get('standard')
if isinstance(standard_sources, dict):
for format_id, formats_list in standard_sources.items():
if not isinstance(formats_list, list):
continue
for standard_format in formats_list:
if not isinstance(standard_format, dict):
continue
for standard_format_key in ('url', 'fallback'):
standard_url = standard_format.get(standard_format_key)
if not standard_url:
continue
standard_url = urljoin(url, standard_url)
if not standard_url or standard_url in format_urls:
continue
format_urls.add(standard_url)
ext = determine_ext(standard_url, 'mp4')
if ext == 'm3u8':
formats.extend(self._extract_m3u8_formats(
standard_url, video_id, 'mp4', entry_protocol='m3u8_native',
m3u8_id='hls', fatal=False))
continue
quality = (str_or_none(standard_format.get('quality'))
or str_or_none(standard_format.get('label'))
or '')
formats.append({
'format_id': '%s-%s' % (format_id, quality),
'url': standard_url,
'ext': ext,
'height': get_height(quality),
'filesize': format_sizes.get(quality),
'http_headers': {
'Referer': standard_url,
},
})
self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
categories_list = video.get('categories')
if isinstance(categories_list, list):
categories = []
for c in categories_list:
if not isinstance(c, dict):
continue
c_name = c.get('name')
if isinstance(c_name, compat_str):
categories.append(c_name)
else:
categories = None
return {
'id': video_id,
'display_id': display_id,
'title': title,
'description': video.get('description'),
'timestamp': int_or_none(video.get('created')),
'uploader': try_get(
video, lambda x: x['author']['name'], compat_str),
'thumbnail': video.get('thumbURL'),
'duration': int_or_none(video.get('duration')),
'view_count': int_or_none(video.get('views')),
'like_count': int_or_none(try_get(
video, lambda x: x['rating']['likes'], int)),
'dislike_count': int_or_none(try_get(
video, lambda x: x['rating']['dislikes'], int)),
'comment_count': int_or_none(video.get('views')),
'age_limit': age_limit,
'categories': categories,
'formats': formats,
}
# Old layout fallback
title = self._html_search_regex(
[r'<h1[^>]*>([^<]+)</h1>',
r'<meta[^>]+itemprop=".*?caption.*?"[^>]+content="(.+?)"',
r'<title[^>]*>(.+?)(?:,\s*[^,]*?\s*Porn\s*[^,]*?:\s*xHamster[^<]*| - xHamster\.com)</title>'],
webpage, 'title')
formats = []
format_urls = set()
sources = self._parse_json(
self._search_regex(
r'sources\s*:\s*({.+?})\s*,?\s*\n', webpage, 'sources',
default='{}'),
video_id, fatal=False)
for format_id, format_url in sources.items():
format_url = url_or_none(format_url)
if not format_url:
continue
if format_url in format_urls:
continue
format_urls.add(format_url)
formats.append({
'format_id': format_id,
'url': format_url,
'height': get_height(format_id),
})
video_url = self._search_regex(
[r'''file\s*:\s*(?P<q>["'])(?P<mp4>.+?)(?P=q)''',
r'''<a\s+href=(?P<q>["'])(?P<mp4>.+?)(?P=q)\s+class=["']mp4Thumb''',
r'''<video[^>]+file=(?P<q>["'])(?P<mp4>.+?)(?P=q)[^>]*>'''],
webpage, 'video url', group='mp4', default=None)
if video_url and video_url not in format_urls:
formats.append({
'url': video_url,
})
self._sort_formats(formats)
# Only a few videos have an description
mobj = re.search(r'<span>Description: </span>([^<]+)', webpage)
description = mobj.group(1) if mobj else None
upload_date = unified_strdate(self._search_regex(
r'hint=["\'](\d{4}-\d{2}-\d{2}) \d{2}:\d{2}:\d{2} [A-Z]{3,4}',
webpage, 'upload date', fatal=False))
uploader = self._html_search_regex(
r'<span[^>]+itemprop=["\']author[^>]+><a[^>]+><span[^>]+>([^<]+)',
webpage, 'uploader', default='anonymous')
thumbnail = self._search_regex(
[r'''["']thumbUrl["']\s*:\s*(?P<q>["'])(?P<thumbnail>.+?)(?P=q)''',
r'''<video[^>]+"poster"=(?P<q>["'])(?P<thumbnail>.+?)(?P=q)[^>]*>'''],
webpage, 'thumbnail', fatal=False, group='thumbnail')
duration = parse_duration(self._search_regex(
[r'<[^<]+\bitemprop=["\']duration["\'][^<]+\bcontent=["\'](.+?)["\']',
r'Runtime:\s*</span>\s*([\d:]+)'], webpage,
'duration', fatal=False))
view_count = int_or_none(self._search_regex(
r'content=["\']User(?:View|Play)s:(\d+)',
webpage, 'view count', fatal=False))
mobj = re.search(r'hint=[\'"](?P<likecount>\d+) Likes / (?P<dislikecount>\d+) Dislikes', webpage)
(like_count, dislike_count) = (mobj.group('likecount'), mobj.group('dislikecount')) if mobj else (None, None)
mobj = re.search(r'</label>Comments \((?P<commentcount>\d+)\)</div>', webpage)
comment_count = mobj.group('commentcount') if mobj else 0
categories_html = self._search_regex(
r'(?s)<table.+?(<span>Categories:.+?)</table>', webpage,
'categories', default=None)
categories = [clean_html(category) for category in re.findall(
r'<a[^>]+>(.+?)</a>', categories_html)] if categories_html else None
return {
'id': video_id,
'display_id': display_id,
'title': title,
'description': description,
'upload_date': upload_date,
'uploader': uploader,
'thumbnail': thumbnail,
'duration': duration,
'view_count': view_count,
'like_count': int_or_none(like_count),
'dislike_count': int_or_none(dislike_count),
'comment_count': int_or_none(comment_count),
'age_limit': age_limit,
'categories': categories,
'formats': formats,
}
class XHamsterEmbedIE(InfoExtractor):
_VALID_URL = r'https?://(?:.+?\.)?%s/xembed\.php\?video=(?P<id>\d+)' % XHamsterIE._DOMAINS
_TEST = {
'url': 'http://xhamster.com/xembed.php?video=3328539',
'info_dict': {
'id': '3328539',
'ext': 'mp4',
'title': 'Pen Masturbation',
'timestamp': 1406581861,
'upload_date': '20140728',
'uploader': 'ManyakisArt',
'duration': 5,
'age_limit': 18,
}
}
@staticmethod
def _extract_urls(webpage):
return [url for _, url in re.findall(
r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?xhamster\.com/xembed\.php\?video=\d+)\1',
webpage)]
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
video_url = self._search_regex(
r'href="(https?://xhamster\.com/(?:movies/{0}/[^"]*\.html|videos/[^/]*-{0})[^"]*)"'.format(video_id),
webpage, 'xhamster url', default=None)
if not video_url:
vars = self._parse_json(
self._search_regex(r'vars\s*:\s*({.+?})\s*,\s*\n', webpage, 'vars'),
video_id)
video_url = dict_get(vars, ('downloadLink', 'homepageLink', 'commentsLink', 'shareUrl'))
return self.url_result(video_url, 'XHamster')
class XHamsterUserIE(InfoExtractor):
_VALID_URL = r'https?://(?:.+?\.)?%s/users/(?P<id>[^/?#&]+)' % XHamsterIE._DOMAINS
_TESTS = [{
# Paginated user profile
'url': 'https://xhamster.com/users/netvideogirls/videos',
'info_dict': {
'id': 'netvideogirls',
},
'playlist_mincount': 267,
}, {
# Non-paginated user profile
'url': 'https://xhamster.com/users/firatkaan/videos',
'info_dict': {
'id': 'firatkaan',
},
'playlist_mincount': 1,
}]
def _entries(self, user_id):
next_page_url = 'https://xhamster.com/users/%s/videos/1' % user_id
for pagenum in itertools.count(1):
page = self._download_webpage(
next_page_url, user_id, 'Downloading page %s' % pagenum)
for video_tag in re.findall(
r'(<a[^>]+class=["\'].*?\bvideo-thumb__image-container[^>]+>)',
page):
video = extract_attributes(video_tag)
video_url = url_or_none(video.get('href'))
if not video_url or not XHamsterIE.suitable(video_url):
continue
video_id = XHamsterIE._match_id(video_url)
yield self.url_result(
video_url, ie=XHamsterIE.ie_key(), video_id=video_id)
mobj = re.search(r'<a[^>]+data-page=["\']next[^>]+>', page)
if not mobj:
break
next_page = extract_attributes(mobj.group(0))
next_page_url = url_or_none(next_page.get('href'))
if not next_page_url:
break
def _real_extract(self, url):
user_id = self._match_id(url)
return self.playlist_result(self._entries(user_id), user_id)
| true | true |
f73b987d0a8e022b4becf7575abd9d18a796cfb7 | 1,004 | py | Python | image-superresolution/esrgan/utils/__init__.py | AaratiAkkapeddi/nnabla-examples | db9e5ad850303c158773aeb275e5c3821b4a3935 | [
"Apache-2.0"
] | 228 | 2017-11-20T06:05:56.000Z | 2022-03-23T12:40:05.000Z | image-superresolution/esrgan/utils/__init__.py | AaratiAkkapeddi/nnabla-examples | db9e5ad850303c158773aeb275e5c3821b4a3935 | [
"Apache-2.0"
] | 36 | 2018-01-11T23:26:20.000Z | 2022-03-12T00:53:38.000Z | image-superresolution/esrgan/utils/__init__.py | AaratiAkkapeddi/nnabla-examples | db9e5ad850303c158773aeb275e5c3821b4a3935 | [
"Apache-2.0"
] | 76 | 2017-11-22T22:00:00.000Z | 2022-03-28T05:58:57.000Z | # Copyright 2020,2021 Sony Corporation.
# Copyright 2021 Sony Group Corporation.
#
# 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 __future__ import absolute_import
import os
import sys
common_utils_path = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', '..', '..', 'utils'))
sys.path.append(common_utils_path)
from neu.yaml_wrapper import read_yaml
from neu.misc import AttrDict
from neu.comm import CommunicatorWrapper
from neu.gan_losses import RelativisticAverageGanLoss, GanLoss
| 40.16 | 74 | 0.776892 |
from __future__ import absolute_import
import os
import sys
common_utils_path = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', '..', '..', 'utils'))
sys.path.append(common_utils_path)
from neu.yaml_wrapper import read_yaml
from neu.misc import AttrDict
from neu.comm import CommunicatorWrapper
from neu.gan_losses import RelativisticAverageGanLoss, GanLoss
| true | true |
f73b98c8bfa98fc01ddb7670ed85ac605935cf32 | 1,629 | py | Python | chapter5/encoding.py | arifmudi/Python-Machine-Learning-By-Example-Third-Edition | 7bdc45df2b519e3c0a929b03f0ac6fe30e028382 | [
"MIT"
] | 49 | 2020-03-21T08:37:46.000Z | 2022-02-01T12:48:23.000Z | chapter5/encoding.py | hmoharrer/Python-Machine-Learning-By-Example-Third-Edition | 7bdc45df2b519e3c0a929b03f0ac6fe30e028382 | [
"MIT"
] | 2 | 2021-03-28T17:25:57.000Z | 2021-04-05T18:14:55.000Z | chapter5/encoding.py | hmoharrer/Python-Machine-Learning-By-Example-Third-Edition | 7bdc45df2b519e3c0a929b03f0ac6fe30e028382 | [
"MIT"
] | 40 | 2020-05-02T18:30:00.000Z | 2022-02-27T09:15:16.000Z | '''
Source codes for Python Machine Learning By Example 3rd Edition (Packt Publishing)
Chapter 5 Predicting Online Ads Click-through with Logistic Regression
Author: Yuxi (Hayden) Liu (yuxi.liu.ece@gmail.com)
'''
from sklearn.feature_extraction import DictVectorizer
X_dict = [{'interest': 'tech', 'occupation': 'professional'},
{'interest': 'fashion', 'occupation': 'student'},
{'interest': 'fashion', 'occupation': 'professional'},
{'interest': 'sports', 'occupation': 'student'},
{'interest': 'tech', 'occupation': 'student'},
{'interest': 'tech', 'occupation': 'retired'},
{'interest': 'sports', 'occupation': 'professional'}]
dict_one_hot_encoder = DictVectorizer(sparse=False)
X_encoded = dict_one_hot_encoder.fit_transform(X_dict)
print(X_encoded)
print(dict_one_hot_encoder.vocabulary_)
new_dict = [{'interest': 'sports', 'occupation': 'retired'}]
new_encoded = dict_one_hot_encoder.transform(new_dict)
print(new_encoded)
print(dict_one_hot_encoder.inverse_transform(new_encoded))
# new category not encountered before
new_dict = [{'interest': 'unknown_interest', 'occupation': 'retired'},
{'interest': 'tech', 'occupation': 'unseen_occupation'}]
new_encoded = dict_one_hot_encoder.transform(new_dict)
print(new_encoded)
import pandas as pd
df = pd.DataFrame({'score': ['low',
'high',
'medium',
'medium',
'low']})
print(df)
mapping = {'low':1, 'medium':2, 'high':3}
df['score'] = df['score'].replace(mapping)
print(df) | 31.941176 | 82 | 0.646409 |
from sklearn.feature_extraction import DictVectorizer
X_dict = [{'interest': 'tech', 'occupation': 'professional'},
{'interest': 'fashion', 'occupation': 'student'},
{'interest': 'fashion', 'occupation': 'professional'},
{'interest': 'sports', 'occupation': 'student'},
{'interest': 'tech', 'occupation': 'student'},
{'interest': 'tech', 'occupation': 'retired'},
{'interest': 'sports', 'occupation': 'professional'}]
dict_one_hot_encoder = DictVectorizer(sparse=False)
X_encoded = dict_one_hot_encoder.fit_transform(X_dict)
print(X_encoded)
print(dict_one_hot_encoder.vocabulary_)
new_dict = [{'interest': 'sports', 'occupation': 'retired'}]
new_encoded = dict_one_hot_encoder.transform(new_dict)
print(new_encoded)
print(dict_one_hot_encoder.inverse_transform(new_encoded))
new_dict = [{'interest': 'unknown_interest', 'occupation': 'retired'},
{'interest': 'tech', 'occupation': 'unseen_occupation'}]
new_encoded = dict_one_hot_encoder.transform(new_dict)
print(new_encoded)
import pandas as pd
df = pd.DataFrame({'score': ['low',
'high',
'medium',
'medium',
'low']})
print(df)
mapping = {'low':1, 'medium':2, 'high':3}
df['score'] = df['score'].replace(mapping)
print(df) | true | true |
f73b9b4cf767cc6d6f020ce79bbd368c2eb1d942 | 2,250 | py | Python | heron/tools/cli/src/python/help.py | pjfanning/incubator-heron | 7db7c24733bd7e66ecfe704ea65f864d1fff4adc | [
"Apache-2.0"
] | 3,348 | 2016-05-25T16:04:31.000Z | 2018-03-28T17:46:14.000Z | heron/tools/cli/src/python/help.py | pjfanning/incubator-heron | 7db7c24733bd7e66ecfe704ea65f864d1fff4adc | [
"Apache-2.0"
] | 1,542 | 2016-05-25T16:46:44.000Z | 2018-03-29T17:30:23.000Z | heron/tools/cli/src/python/help.py | pjfanning/incubator-heron | 7db7c24733bd7e66ecfe704ea65f864d1fff4adc | [
"Apache-2.0"
] | 702 | 2016-05-25T16:07:43.000Z | 2018-03-27T06:31:07.000Z | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# 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.
''' help.py '''
from heron.common.src.python.utils.log import Log
from heron.tools.cli.src.python.result import SimpleResult, Status
from heron.tools.common.src.python.utils import config
def create_parser(subparsers):
'''
:param subparsers:
:return:
'''
parser = subparsers.add_parser(
'help',
help='Prints help for commands',
add_help=True)
# pylint: disable=protected-access
parser._positionals.title = "Required arguments"
parser._optionals.title = "Optional arguments"
parser.add_argument(
'help-command',
nargs='?',
default='help',
help='Provide help for a command')
parser.set_defaults(subcommand='help')
return parser
# pylint: disable=unused-argument,superfluous-parens
def run(command, parser, args, unknown_args):
'''
:param command:
:param parser:
:param args:
:param unknown_args:
:return:
'''
# get the command for detailed help
command_help = args['help-command']
# if no command is provided, just print main help
if command_help == 'help':
parser.print_help()
return SimpleResult(Status.Ok)
# get the subparser for the specific command
subparser = config.get_subparser(parser, command_help)
if subparser:
print(subparser.format_help())
return SimpleResult(Status.Ok)
Log.error("Unknown subcommand \'%s\'", command_help)
return SimpleResult(Status.InvocationError)
| 30.405405 | 66 | 0.723111 |
from heron.common.src.python.utils.log import Log
from heron.tools.cli.src.python.result import SimpleResult, Status
from heron.tools.common.src.python.utils import config
def create_parser(subparsers):
parser = subparsers.add_parser(
'help',
help='Prints help for commands',
add_help=True)
parser._positionals.title = "Required arguments"
parser._optionals.title = "Optional arguments"
parser.add_argument(
'help-command',
nargs='?',
default='help',
help='Provide help for a command')
parser.set_defaults(subcommand='help')
return parser
def run(command, parser, args, unknown_args):
command_help = args['help-command']
if command_help == 'help':
parser.print_help()
return SimpleResult(Status.Ok)
subparser = config.get_subparser(parser, command_help)
if subparser:
print(subparser.format_help())
return SimpleResult(Status.Ok)
Log.error("Unknown subcommand \'%s\'", command_help)
return SimpleResult(Status.InvocationError)
| true | true |
f73b9ba8b769400e549052d9f210b3d340c18d2d | 5,239 | py | Python | Python/Vote.py | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | 3 | 2020-11-01T05:48:04.000Z | 2021-04-25T05:33:47.000Z | Python/Vote.py | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | null | null | null | Python/Vote.py | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | 3 | 2020-10-31T05:29:55.000Z | 2021-06-19T09:33:53.000Z | '''
TCS Codevita Question, 2020
Elections are going on, and there are two candidates A and B, contesting with each other. There is a queue of voters and in this queue some of them are supporters of A and some of them are supporters of B. Many of them are neutral. The fate of the election will be decided on which side the neutral voters vote. Supporters of A and supporters of B make attempt to win the votes of neutral voters.
The way this can be done is explained below:
1. The voter queue is denoted by three characters, viz {-, A, B}. The - denotes neutral candidate, A denotes supporter of candidate A and B denotes supporter of candidate B.
2. Supporters of A can only move towards the left side of the queue.
3. Supporters of B can only move towards the right side of the queue.
4. Since time is critical, supporters of both A and B will move simultaneously.
5. They both will try and influence the neutral voters by moving in their direction in the queue. If supporter of A reaches the neutral voter before supporter of B reaches him, then that neutral voter will become a supporter of candidate A.
6. Similarly, if supporter of B reaches the neutral voter before supporter of A reaches him, then that neutral voter will become a supporter of candidate B.
7. Finally, if both reach at the same time, the voter will remain neutral. A neutral vote cannot decide the outcome of the election.
8. If finally, the queue has more votes for candidate A, then A wins the election. If B has more votes, then B wins that election. If both have equal votes, then it will be a coalition government.
Refer Examples section for understanding the dynamics of how the supporters influence the neutral voters.
Your task is to find the outcome of the election.
Note: There are no test cases where all votes are neutral.
Constraints
1 <= length of queue <= 10 ^ 5
Input
First line contains an integer which is length of queue of voters.
Second line contains characters {-, A, B}, in which denotes
· A = voter who is supporter of candidate A
· B = voter who is supporter of candidate B
· - = neutral voter
Output
Print candidate with maximum number of votes. If they have equal number of votes, print “Coalition government“.
Time Limit
1
Examples:-------------------------------
Example 1
Input
14
--AB--AB---A--
Output
A
Explanation:
For starting positions where there is no opposition from supporter of B, supporter of A can promote in left side of the queue. The voting queue will then look like below:
A A A B - - A B - - - A - -
From 4th place (in voting queue) B supporter is moving towards the right side, simultaneously 7th placed A supporter is also moving towards the left side. Then the voting queue will look like below:
A A A B B A A B - - - A - -
From 8th place B supporter is moving towards the right side, simultaneously 12th placed A supporter is also moving towards the left side. Then the voting queue will look like below:
A A A B B A A B B - A A - -
Since supporters of both A and B will reach the 10th voter at the same time, 10th voter will remain neutral.
Since supporter of A at 12th place cannot move towards right, last 2 voters will not be influenced and remain neutral. Then the voting queue will look like below:
A A A B B A A B B - A A - -
Since all voter have now cast their votes, election results can now be declared.
So final result is: A A A B B A A B B - A A - -
A has 7 votes, B has 4 votes hence, A wins the election.
Example 2
Input
4
A---
Output
A
Explanation:
Since supporter of A at 1st place cannot move towards right, last 3 voters will not be influenced and will remain neutral. Then the voting queue will look like below:
A - - -
Since all voter have now cast their votes, election results can now be declared.
So final result is: A - - -
A has 1 vote, B has 0 votes hence, A wins the election.
Example 3
Input
5
A---B
Output
Coalition government
Explanation:
Since supporter of A at 1st place cannot move towards right, supporter of B at 5th cannot move towards left, middle 3 voters will not be influenced and will remain neutral. Then the voting queue will look like below:
A - - - B
So final result is: A - - - B
A has 1 vote, B has 1 vote hence, output will be “Coalition government“.
'''
n=int(input())
i=list(input())
ac=bc=temp=0
latest=[0]
for j in range(n):
if (i[j]=="A" or i[j]=="B"):
latest.append(i[j])
if i[j] == "A":
if (j-1) >= 0:
if (i[j-1] == "-" and (latest[-2] == "A" or latest[-2] == 0)):
ac+=temp+1
else:
ac+=1
else:
ac+=1
temp=0
elif i[j] == "B":
if j-1 >=0:
if i[j-1] == "-" and latest[-2] == "B":
bc+=temp+1
else:
bc+=1
else:
bc+=1
temp=0
else:
temp+=1
if((i[-1]=="-") and (latest[-1]=="B")):
bc+=temp
if ac>bc:
#print("WINNER --> A ,by --",ac-bc,"vote(s)")
print("A")
elif bc>ac:
#print("WINNER --> B , by --",bc-ac,"vote(s)")
print("B")
else:
print("Coalition government")
| 40.3 | 397 | 0.671693 |
n=int(input())
i=list(input())
ac=bc=temp=0
latest=[0]
for j in range(n):
if (i[j]=="A" or i[j]=="B"):
latest.append(i[j])
if i[j] == "A":
if (j-1) >= 0:
if (i[j-1] == "-" and (latest[-2] == "A" or latest[-2] == 0)):
ac+=temp+1
else:
ac+=1
else:
ac+=1
temp=0
elif i[j] == "B":
if j-1 >=0:
if i[j-1] == "-" and latest[-2] == "B":
bc+=temp+1
else:
bc+=1
else:
bc+=1
temp=0
else:
temp+=1
if((i[-1]=="-") and (latest[-1]=="B")):
bc+=temp
if ac>bc:
print("A")
elif bc>ac:
print("B")
else:
print("Coalition government")
| true | true |
f73b9c28d257bb8ca18da403effc773363ed61fe | 2,158 | py | Python | examples/010_logs_and_prints.py | montefiore-ai/clustertools | ecb63afded2aff2370f54312b0336c28b531b6af | [
"BSD-3-Clause"
] | 7 | 2017-05-31T15:28:28.000Z | 2021-03-25T12:36:48.000Z | examples/010_logs_and_prints.py | montefiore-ai/clustertools | ecb63afded2aff2370f54312b0336c28b531b6af | [
"BSD-3-Clause"
] | 42 | 2017-06-09T07:35:50.000Z | 2019-08-29T15:23:29.000Z | examples/010_logs_and_prints.py | montefiore-ai/clustertools | ecb63afded2aff2370f54312b0336c28b531b6af | [
"BSD-3-Clause"
] | 3 | 2017-05-29T13:39:18.000Z | 2019-06-24T09:43:01.000Z | # -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
When running computations on the background or through a scheduler such as
Slurm, print statement are lost. Although you can redirect the standard outputs
in the former case, the procedure is not as straightforward in the latter case.
Fortunately, Clustertools offers a unify way of managing such things by creating
a log file in a standard fashion (independent of the environment/backend).
The `clustertools` utility offers a simple way to get the log of each
computation. Simply run `clustertools display log <exp_name> <comp_number>`.
1. Run `python 000_reset.py` to reset the experiment.
2. Run `python 010_logs_and_prints.py front-end`
3. Run `clustertools display log BasicUsage 0` to print the log
You can play with the computation number
"""
from clustertools import Computation, CTParser, ParameterSet, \
Experiment, set_stdout_logging
class MyComputation(Computation):
"""
Inherit from `Computation` and redefine the `run` method as you which
"""
def run(self, result, x, z, w, y=2, **parameters):
import time
from datetime import datetime
from random import randint
# We add a few print statements
print(repr(self))
print()
print("{}: I must multiply {} by {}. This is a hard computation, "
"it will take a few seconds".format(datetime.now(), x, y))
result["multiply"] = x * y
time.sleep(randint(1, 10))
print("{}: Now I must add {} and {}. This is easier but I am tired "
"with all those hard computations. Let me think..."
"".format(datetime.now(), z, w))
result["sum"] = z + w
time.sleep(randint(1, 10))
print("{}: Woah, it was hard. I think I'll go back to sleep."
"".format(datetime.now()))
if __name__ == "__main__":
set_stdout_logging()
parser = CTParser()
environment, _ = parser.parse()
param_set = ParameterSet()
param_set.add_parameters(x=[1, 2, 3], z=4, w=[5, 6])
experiment = Experiment("BasicUsage", param_set, MyComputation)
environment.run(experiment)
| 31.275362 | 80 | 0.661724 |
from clustertools import Computation, CTParser, ParameterSet, \
Experiment, set_stdout_logging
class MyComputation(Computation):
def run(self, result, x, z, w, y=2, **parameters):
import time
from datetime import datetime
from random import randint
print(repr(self))
print()
print("{}: I must multiply {} by {}. This is a hard computation, "
"it will take a few seconds".format(datetime.now(), x, y))
result["multiply"] = x * y
time.sleep(randint(1, 10))
print("{}: Now I must add {} and {}. This is easier but I am tired "
"with all those hard computations. Let me think..."
"".format(datetime.now(), z, w))
result["sum"] = z + w
time.sleep(randint(1, 10))
print("{}: Woah, it was hard. I think I'll go back to sleep."
"".format(datetime.now()))
if __name__ == "__main__":
set_stdout_logging()
parser = CTParser()
environment, _ = parser.parse()
param_set = ParameterSet()
param_set.add_parameters(x=[1, 2, 3], z=4, w=[5, 6])
experiment = Experiment("BasicUsage", param_set, MyComputation)
environment.run(experiment)
| true | true |
f73b9c6f4d7eebe9e6b33fa98a1f56b71aeab19e | 3,647 | py | Python | sdk/python/pulumi_azure_nextgen/containerregistry/get_build_step.py | pulumi/pulumi-azure-nextgen | 452736b0a1cf584c2d4c04666e017af6e9b2c15c | [
"Apache-2.0"
] | 31 | 2020-09-21T09:41:01.000Z | 2021-02-26T13:21:59.000Z | sdk/python/pulumi_azure_nextgen/containerregistry/get_build_step.py | pulumi/pulumi-azure-nextgen | 452736b0a1cf584c2d4c04666e017af6e9b2c15c | [
"Apache-2.0"
] | 231 | 2020-09-21T09:38:45.000Z | 2021-03-01T11:16:03.000Z | sdk/python/pulumi_azure_nextgen/containerregistry/get_build_step.py | pulumi/pulumi-azure-nextgen | 452736b0a1cf584c2d4c04666e017af6e9b2c15c | [
"Apache-2.0"
] | 4 | 2020-09-29T14:14:59.000Z | 2021-02-10T20:38:16.000Z | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from . import outputs
__all__ = [
'GetBuildStepResult',
'AwaitableGetBuildStepResult',
'get_build_step',
]
@pulumi.output_type
class GetBuildStepResult:
"""
Build step resource properties
"""
def __init__(__self__, id=None, name=None, properties=None, type=None):
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if properties and not isinstance(properties, dict):
raise TypeError("Expected argument 'properties' to be a dict")
pulumi.set(__self__, "properties", properties)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter
def id(self) -> str:
"""
The resource ID.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the resource.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def properties(self) -> 'outputs.DockerBuildStepResponse':
"""
The properties of a build step.
"""
return pulumi.get(self, "properties")
@property
@pulumi.getter
def type(self) -> str:
"""
The type of the resource.
"""
return pulumi.get(self, "type")
class AwaitableGetBuildStepResult(GetBuildStepResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetBuildStepResult(
id=self.id,
name=self.name,
properties=self.properties,
type=self.type)
def get_build_step(build_task_name: Optional[str] = None,
registry_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
step_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetBuildStepResult:
"""
Build step resource properties
API Version: 2018-02-01-preview.
:param str build_task_name: The name of the container registry build task.
:param str registry_name: The name of the container registry.
:param str resource_group_name: The name of the resource group to which the container registry belongs.
:param str step_name: The name of a build step for a container registry build task.
"""
__args__ = dict()
__args__['buildTaskName'] = build_task_name
__args__['registryName'] = registry_name
__args__['resourceGroupName'] = resource_group_name
__args__['stepName'] = step_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-nextgen:containerregistry:getBuildStep', __args__, opts=opts, typ=GetBuildStepResult).value
return AwaitableGetBuildStepResult(
id=__ret__.id,
name=__ret__.name,
properties=__ret__.properties,
type=__ret__.type)
| 32.274336 | 134 | 0.639978 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from . import outputs
__all__ = [
'GetBuildStepResult',
'AwaitableGetBuildStepResult',
'get_build_step',
]
@pulumi.output_type
class GetBuildStepResult:
def __init__(__self__, id=None, name=None, properties=None, type=None):
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if properties and not isinstance(properties, dict):
raise TypeError("Expected argument 'properties' to be a dict")
pulumi.set(__self__, "properties", properties)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter
def id(self) -> str:
return pulumi.get(self, "id")
@property
@pulumi.getter
def name(self) -> str:
return pulumi.get(self, "name")
@property
@pulumi.getter
def properties(self) -> 'outputs.DockerBuildStepResponse':
return pulumi.get(self, "properties")
@property
@pulumi.getter
def type(self) -> str:
return pulumi.get(self, "type")
class AwaitableGetBuildStepResult(GetBuildStepResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetBuildStepResult(
id=self.id,
name=self.name,
properties=self.properties,
type=self.type)
def get_build_step(build_task_name: Optional[str] = None,
registry_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
step_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetBuildStepResult:
__args__ = dict()
__args__['buildTaskName'] = build_task_name
__args__['registryName'] = registry_name
__args__['resourceGroupName'] = resource_group_name
__args__['stepName'] = step_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-nextgen:containerregistry:getBuildStep', __args__, opts=opts, typ=GetBuildStepResult).value
return AwaitableGetBuildStepResult(
id=__ret__.id,
name=__ret__.name,
properties=__ret__.properties,
type=__ret__.type)
| true | true |
f73b9d6623e4d92f66f56427571a87ef28b089c1 | 2,439 | py | Python | pipert/contrib/routines/face_detection.py | Elon-Abulafia/PipeRT | fba46d67a6dd546a9d70c3d854c3b7d3910f82ba | [
"MIT"
] | null | null | null | pipert/contrib/routines/face_detection.py | Elon-Abulafia/PipeRT | fba46d67a6dd546a9d70c3d854c3b7d3910f82ba | [
"MIT"
] | null | null | null | pipert/contrib/routines/face_detection.py | Elon-Abulafia/PipeRT | fba46d67a6dd546a9d70c3d854c3b7d3910f82ba | [
"MIT"
] | null | null | null | import torch
from pipert import Routine
from pipert.core.message import Message
from pipert.core.routine import RoutineTypes
from pipert.utils.structures import Instances, Boxes
from queue import Empty
import time
import cv2
import pkg_resources
class FaceDetection(Routine):
routine_type = RoutineTypes.PROCESSING
def __init__(self, in_queue, out_queue, *args, **kwargs):
super().__init__(*args, **kwargs)
self.in_queue = in_queue
self.out_queue = out_queue
self.face_cas = None
def main_logic(self, *args, **kwargs):
try:
frame_msg = self.in_queue.get(block=False)
frame = frame_msg.get_payload()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = self.face_cas.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(20, 20)
)
if len(faces):
faces = torch.from_numpy(faces)
faces[:, 2:] += faces[:, :2]
# print(faces.size(), faces)
new_instances = Instances(frame.shape[:2])
new_instances.set("pred_boxes", Boxes(faces))
new_instances.set("pred_classes", torch.zeros(faces.size(0)).int())
else:
new_instances = Instances(frame.shape[:2])
new_instances.set("pred_classes", [])
try:
self.out_queue.get(block=False)
self.state.dropped += 1
except Empty:
pass
pred_msg = Message(new_instances, frame_msg.source_address)
self.out_queue.put(pred_msg, block=False)
return True
except Empty:
time.sleep(0)
return False
def setup(self, *args, **kwargs):
haar_xml = pkg_resources.resource_filename('cv2', 'data/haarcascade_frontalface_default.xml')
self.face_cas = cv2.CascadeClassifier(haar_xml)
self.state.dropped = 0
def cleanup(self, *args, **kwargs):
pass
@staticmethod
def get_constructor_parameters():
dicts = Routine.get_constructor_parameters()
dicts.update({
"in_queue": "QueueIn",
"out_queue": "QueueOut",
})
return dicts
def does_routine_use_queue(self, queue):
return (self.in_queue == queue) or (self.out_queue == queue)
| 31.269231 | 101 | 0.585076 | import torch
from pipert import Routine
from pipert.core.message import Message
from pipert.core.routine import RoutineTypes
from pipert.utils.structures import Instances, Boxes
from queue import Empty
import time
import cv2
import pkg_resources
class FaceDetection(Routine):
routine_type = RoutineTypes.PROCESSING
def __init__(self, in_queue, out_queue, *args, **kwargs):
super().__init__(*args, **kwargs)
self.in_queue = in_queue
self.out_queue = out_queue
self.face_cas = None
def main_logic(self, *args, **kwargs):
try:
frame_msg = self.in_queue.get(block=False)
frame = frame_msg.get_payload()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = self.face_cas.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(20, 20)
)
if len(faces):
faces = torch.from_numpy(faces)
faces[:, 2:] += faces[:, :2]
new_instances = Instances(frame.shape[:2])
new_instances.set("pred_boxes", Boxes(faces))
new_instances.set("pred_classes", torch.zeros(faces.size(0)).int())
else:
new_instances = Instances(frame.shape[:2])
new_instances.set("pred_classes", [])
try:
self.out_queue.get(block=False)
self.state.dropped += 1
except Empty:
pass
pred_msg = Message(new_instances, frame_msg.source_address)
self.out_queue.put(pred_msg, block=False)
return True
except Empty:
time.sleep(0)
return False
def setup(self, *args, **kwargs):
haar_xml = pkg_resources.resource_filename('cv2', 'data/haarcascade_frontalface_default.xml')
self.face_cas = cv2.CascadeClassifier(haar_xml)
self.state.dropped = 0
def cleanup(self, *args, **kwargs):
pass
@staticmethod
def get_constructor_parameters():
dicts = Routine.get_constructor_parameters()
dicts.update({
"in_queue": "QueueIn",
"out_queue": "QueueOut",
})
return dicts
def does_routine_use_queue(self, queue):
return (self.in_queue == queue) or (self.out_queue == queue)
| true | true |
f73b9d8531c50a0be0abdb652d380f1c2b226a1c | 8,219 | py | Python | Project_Data Warehouse/sql_queries.py | yumengdong/Data-Engineer-Nanodegree-Udacity | 9fff4ccc088263049d5842f89174f335142bcb60 | [
"MIT"
] | null | null | null | Project_Data Warehouse/sql_queries.py | yumengdong/Data-Engineer-Nanodegree-Udacity | 9fff4ccc088263049d5842f89174f335142bcb60 | [
"MIT"
] | null | null | null | Project_Data Warehouse/sql_queries.py | yumengdong/Data-Engineer-Nanodegree-Udacity | 9fff4ccc088263049d5842f89174f335142bcb60 | [
"MIT"
] | null | null | null | import configparser
# CONFIG
config = configparser.ConfigParser()
config.read('dwh.cfg')
IAM_ROLE = config['IAM_ROLE']['ARN']
LOG_DATA = config['S3']['LOG_DATA']
SONG_DATA = config['S3']['SONG_DATA']
LOG_JSONPATH = config['S3']['LOG_JSONPATH']
# DROP TABLES
staging_events_table_drop = "DROP TABLE IF EXISTS staging_events_table"
staging_songs_table_drop = "DROP TABLE IF EXISTS staging_songs_table"
songplay_table_drop = "DROP TABLE IF EXISTS songplay_table"
user_table_drop = "DROP TABLE IF EXISTS user_table"
song_table_drop = "DROP TABLE IF EXISTS song_table"
artist_table_drop = "DROP TABLE IF EXISTS artist_table"
time_table_drop = "DROP TABLE IF EXISTS time_table"
# CREATE TABLES
#stage table for events.json/log_data and song_data
staging_events_table_create= ("""
CREATE TABLE IF NOT EXISTS staging_events(
event_id INT IDENTITY(0, 1) NOT NULL SORTKEY DISTKEY,
artist VARCHAR,
auth VARCHAR,
firstname VARCHAR,
gender VARCHAR,
itemInSession INTEGER,
lastname VARCHAR,
length FLOAT,
level VARCHAR,
location VARCHAR,
method VARCHAR,
page VARCHAR,
registrtion BIGINT,
sessionId INTEGER,
song VARCHAR,
status INTEGER,
ts TIMESTAMP,
userAgent VARCHAR,
userId INTEGER)
""")
staging_songs_table_create = ("""
CREATE TABLE IF NOT EXISTS staging_songs(
num_songs INTEGER SORTKEY DISTKEY,
artist_id VARCHAR,
artist_latitude NUMERIC,
artist_longitude NUMERIC,
artist_location VARCHAR,
artist_name VARCHAR,
song_id VARCHAR,
title VARCHAR,
duration NUMERIC,
year INTEGER)
""")
songplay_table_create = ("""
CREATE TABLE IF NOT EXISTS songplay_table(
songplay_id INTEGER IDENTITY(0,1) PRIMARY KEY SORTKEY,
start_time timestamp,
user_id varchar,
level varchar,
song_id varchar,
artist_id varchar,
session_id varchar,
location varchar,
user_agent varchar)
""")
user_table_create = ("""
CREATE TABLE IF NOT EXISTS user_table(
user_id INTEGER PRIMARY KEY DISTKEY,
first_name varchar,
last_name varchar,
gender varchar,
level varchar)
""")
song_table_create = ("""
CREATE TABLE IF NOT EXISTS song_table(
song_id varchar NOT NULL PRIMARY KEY,
title varchar,
artist_id varchar DISTKEY,
year int,
duration NUMERIC)
""")
artist_table_create = ("""
CREATE TABLE IF NOT EXISTS artist_table(
artist_id varchar NOT NULL PRIMARY KEY DISTKEY,
name varchar,
location varchar,
latitude NUMERIC,
longitude NUMERIC)
""")
time_table_create = ("""
CREATE TABLE IF NOT EXISTS time_table(
start_time TIMESTAMP PRIMARY KEY DISTKEY,
hour int,
day int,
week int,
month int,
year int,
weekday int)
""")
# STAGING TABLES
staging_events_copy = ("""
COPY staging_events
FROM {}
iam_role {}
JSON {};
""").format(LOG_DATA, IAM_ROLE, LOG_JSONPATH)
staging_songs_copy = ("""
COPY staging_songs
FROM {}
iam_role {}
JSON 'auto';
""").format(SONG_DATA, IAM_ROLE)
# FINAL TABLES
songplay_table_insert = ("""INSERT INTO songplay(start_time, user_id, level, song_id, artist_id, session_id, location, user_agent)
SELECT timestamp 'epoch' + se.ts/1000 * interval '1 second' as start_time, se.user_id, se.level,
ss.song_id, ss.artist_id, se.session_id, se.location, se.user_agent
FROM staging_events se, staging_songs ss
WHERE se.page = 'NextSong' AND
se.song =ss.title AND
se.artist = ss.artist_name AND
se.length = ss.duration
""")
user_table_insert = ("""INSERT INTO users(user_id, first_name, last_name, gender, level)
SELECT distinct user_id, first_name, last_name, gender, level
FROM staging_events
WHERE page = 'NextSong'
""")
song_table_insert = ("""INSERT INTO song(song_id, title, artist_id, year, duration)
SELECT song_id, title, artist_id, year, duration
FROM staging_songs
WHERE song_id IS NOT NULL
""")
artist_table_insert = ("""INSERT INTO artist(artist_id, name, location, latitude, longitude)
SELECT distinct artist_id, artist_name, artist_location , artist_latitude, artist_longitude
FROM staging_songs
WHERE artist_id IS NOT NULL
""")
time_table_insert = ("""INSERT INTO time(start_time, hour, day, week, month, year, weekDay)
SELECT start_time, extract(hour from start_time), extract(day from start_time),
extract(week from start_time), extract(month from start_time),
extract(year from start_time), extract(dayofweek from start_time)
FROM songplay
""")
# QUERY LISTS
create_table_queries = [staging_events_table_create, staging_songs_table_create, songplay_table_create, user_table_create, song_table_create, artist_table_create, time_table_create]
drop_table_queries = [staging_events_table_drop, staging_songs_table_drop, songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop]
copy_table_queries = [staging_events_copy, staging_songs_copy]
insert_table_queries = [songplay_table_insert, user_table_insert, song_table_insert, artist_table_insert, time_table_insert]
| 46.435028 | 181 | 0.453218 | import configparser
config = configparser.ConfigParser()
config.read('dwh.cfg')
IAM_ROLE = config['IAM_ROLE']['ARN']
LOG_DATA = config['S3']['LOG_DATA']
SONG_DATA = config['S3']['SONG_DATA']
LOG_JSONPATH = config['S3']['LOG_JSONPATH']
staging_events_table_drop = "DROP TABLE IF EXISTS staging_events_table"
staging_songs_table_drop = "DROP TABLE IF EXISTS staging_songs_table"
songplay_table_drop = "DROP TABLE IF EXISTS songplay_table"
user_table_drop = "DROP TABLE IF EXISTS user_table"
song_table_drop = "DROP TABLE IF EXISTS song_table"
artist_table_drop = "DROP TABLE IF EXISTS artist_table"
time_table_drop = "DROP TABLE IF EXISTS time_table"
staging_events_table_create= ("""
CREATE TABLE IF NOT EXISTS staging_events(
event_id INT IDENTITY(0, 1) NOT NULL SORTKEY DISTKEY,
artist VARCHAR,
auth VARCHAR,
firstname VARCHAR,
gender VARCHAR,
itemInSession INTEGER,
lastname VARCHAR,
length FLOAT,
level VARCHAR,
location VARCHAR,
method VARCHAR,
page VARCHAR,
registrtion BIGINT,
sessionId INTEGER,
song VARCHAR,
status INTEGER,
ts TIMESTAMP,
userAgent VARCHAR,
userId INTEGER)
""")
staging_songs_table_create = ("""
CREATE TABLE IF NOT EXISTS staging_songs(
num_songs INTEGER SORTKEY DISTKEY,
artist_id VARCHAR,
artist_latitude NUMERIC,
artist_longitude NUMERIC,
artist_location VARCHAR,
artist_name VARCHAR,
song_id VARCHAR,
title VARCHAR,
duration NUMERIC,
year INTEGER)
""")
songplay_table_create = ("""
CREATE TABLE IF NOT EXISTS songplay_table(
songplay_id INTEGER IDENTITY(0,1) PRIMARY KEY SORTKEY,
start_time timestamp,
user_id varchar,
level varchar,
song_id varchar,
artist_id varchar,
session_id varchar,
location varchar,
user_agent varchar)
""")
user_table_create = ("""
CREATE TABLE IF NOT EXISTS user_table(
user_id INTEGER PRIMARY KEY DISTKEY,
first_name varchar,
last_name varchar,
gender varchar,
level varchar)
""")
song_table_create = ("""
CREATE TABLE IF NOT EXISTS song_table(
song_id varchar NOT NULL PRIMARY KEY,
title varchar,
artist_id varchar DISTKEY,
year int,
duration NUMERIC)
""")
artist_table_create = ("""
CREATE TABLE IF NOT EXISTS artist_table(
artist_id varchar NOT NULL PRIMARY KEY DISTKEY,
name varchar,
location varchar,
latitude NUMERIC,
longitude NUMERIC)
""")
time_table_create = ("""
CREATE TABLE IF NOT EXISTS time_table(
start_time TIMESTAMP PRIMARY KEY DISTKEY,
hour int,
day int,
week int,
month int,
year int,
weekday int)
""")
staging_events_copy = ("""
COPY staging_events
FROM {}
iam_role {}
JSON {};
""").format(LOG_DATA, IAM_ROLE, LOG_JSONPATH)
staging_songs_copy = ("""
COPY staging_songs
FROM {}
iam_role {}
JSON 'auto';
""").format(SONG_DATA, IAM_ROLE)
songplay_table_insert = ("""INSERT INTO songplay(start_time, user_id, level, song_id, artist_id, session_id, location, user_agent)
SELECT timestamp 'epoch' + se.ts/1000 * interval '1 second' as start_time, se.user_id, se.level,
ss.song_id, ss.artist_id, se.session_id, se.location, se.user_agent
FROM staging_events se, staging_songs ss
WHERE se.page = 'NextSong' AND
se.song =ss.title AND
se.artist = ss.artist_name AND
se.length = ss.duration
""")
user_table_insert = ("""INSERT INTO users(user_id, first_name, last_name, gender, level)
SELECT distinct user_id, first_name, last_name, gender, level
FROM staging_events
WHERE page = 'NextSong'
""")
song_table_insert = ("""INSERT INTO song(song_id, title, artist_id, year, duration)
SELECT song_id, title, artist_id, year, duration
FROM staging_songs
WHERE song_id IS NOT NULL
""")
artist_table_insert = ("""INSERT INTO artist(artist_id, name, location, latitude, longitude)
SELECT distinct artist_id, artist_name, artist_location , artist_latitude, artist_longitude
FROM staging_songs
WHERE artist_id IS NOT NULL
""")
time_table_insert = ("""INSERT INTO time(start_time, hour, day, week, month, year, weekDay)
SELECT start_time, extract(hour from start_time), extract(day from start_time),
extract(week from start_time), extract(month from start_time),
extract(year from start_time), extract(dayofweek from start_time)
FROM songplay
""")
create_table_queries = [staging_events_table_create, staging_songs_table_create, songplay_table_create, user_table_create, song_table_create, artist_table_create, time_table_create]
drop_table_queries = [staging_events_table_drop, staging_songs_table_drop, songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop]
copy_table_queries = [staging_events_copy, staging_songs_copy]
insert_table_queries = [songplay_table_insert, user_table_insert, song_table_insert, artist_table_insert, time_table_insert]
| true | true |
f73ba0a3eca9cf1cc7c88a2392cf00c719ba3621 | 8,729 | py | Python | setup.py | vstinner/greenlet | fa91f03d5ec8d46017300cb6b161ec3dbe0d3a0c | [
"PSF-2.0",
"MIT"
] | 1 | 2021-12-21T18:56:12.000Z | 2021-12-21T18:56:12.000Z | setup.py | sthagen/greenlet | fa91f03d5ec8d46017300cb6b161ec3dbe0d3a0c | [
"PSF-2.0",
"MIT"
] | null | null | null | setup.py | sthagen/greenlet | fa91f03d5ec8d46017300cb6b161ec3dbe0d3a0c | [
"PSF-2.0",
"MIT"
] | null | null | null | #! /usr/bin/env python
from __future__ import print_function
import sys
import os
import glob
import platform
# distutils is deprecated and vendored into setuptools now.
from setuptools import setup
from setuptools import Extension
from setuptools import find_packages
# Extra compiler arguments passed to *all* extensions.
global_compile_args = []
# Extra compiler arguments passed to C++ extensions
cpp_compile_args = []
# Extra linker arguments passed to C++ extensions
cpp_link_args = []
# Extra compiler arguments passed to the main extension
main_compile_args = []
# workaround segfaults on openbsd and RHEL 3 / CentOS 3 . see
# https://bitbucket.org/ambroff/greenlet/issue/11/segfault-on-openbsd-i386
# https://github.com/python-greenlet/greenlet/issues/4
# https://github.com/python-greenlet/greenlet/issues/94
# pylint:disable=too-many-boolean-expressions
is_linux = sys.platform.startswith('linux') # could be linux or linux2
if ((sys.platform == "openbsd4" and os.uname()[-1] == "i386")
or ("-with-redhat-3." in platform.platform() and platform.machine() == 'i686')
or (sys.platform == "sunos5" and os.uname()[-1] == "sun4v")
or ("SunOS" in platform.platform() and platform.machine() == "sun4v")
or (is_linux and platform.machine() == "ppc")):
global_compile_args.append("-Os")
if sys.platform == 'darwin':
# The clang compiler doesn't use --std=c++11 by default
cpp_compile_args.append("--std=gnu++11")
elif sys.platform == 'win32' and "MSC" in platform.python_compiler():
# Older versions of MSVC (Python 2.7) don't handle C++ exceptions
# correctly by default. While newer versions do handle exceptions by default,
# they don't do it fully correctly. So we need an argument on all versions.
#"/EH" == exception handling.
# "s" == standard C++,
# "c" == extern C functions don't throw
# OR
# "a" == standard C++, and Windows SEH; anything may throw, compiler optimizations
# around try blocks are less aggressive.
# /EHsc is suggested, as /EHa isn't supposed to be linked to other things not built
# with it.
# See https://docs.microsoft.com/en-us/cpp/build/reference/eh-exception-handling-model?view=msvc-160
handler = "/EHsc"
cpp_compile_args.append(handler)
# To disable most optimizations:
#cpp_compile_args.append('/Od')
# To enable assertions:
#cpp_compile_args.append('/UNDEBUG')
# To enable more compile-time warnings (/Wall produces a mountain of output).
#cpp_compile_args.append('/W4')
# To link with the debug C runtime...except we can't because we need
# the Python debug lib too, and they're not around by default
# cpp_compile_args.append('/MDd')
# Support fiber-safe thread-local storage: "the compiler mustn't
# cache the address of the TLS array, or optimize it as a common
# subexpression across a function call." This would probably solve
# some of the issues we had with MSVC caching the thread local
# variables on the stack, leading to having to split some
# functions up. Revisit those.
cpp_compile_args.append("/GT")
def readfile(filename):
with open(filename, 'r') as f: # pylint:disable=unspecified-encoding
return f.read()
GREENLET_SRC_DIR = 'src/greenlet/'
GREENLET_HEADER_DIR = GREENLET_SRC_DIR
GREENLET_HEADER = GREENLET_HEADER_DIR + 'greenlet.h'
GREENLET_TEST_DIR = 'src/greenlet/tests/'
# The location of the platform specific assembly files
# for switching.
GREENLET_PLATFORM_DIR = GREENLET_SRC_DIR + 'platform/'
def _find_platform_headers():
return glob.glob(GREENLET_PLATFORM_DIR + "switch_*.h")
def _find_impl_headers():
return glob.glob(GREENLET_SRC_DIR + "*.hpp")
if hasattr(sys, "pypy_version_info"):
ext_modules = []
headers = []
else:
headers = [GREENLET_HEADER]
if sys.platform == 'win32' and '64 bit' in sys.version:
# this works when building with msvc, not with 64 bit gcc
# switch_<platform>_masm.obj can be created with setup_switch_<platform>_masm.cmd
obj_fn = 'switch_arm64_masm.obj' if platform.machine() == 'ARM64' else 'switch_x64_masm.obj'
extra_objects = [os.path.join(GREENLET_PLATFORM_DIR, obj_fn)]
else:
extra_objects = []
if sys.platform == 'win32' and os.environ.get('GREENLET_STATIC_RUNTIME') in ('1', 'yes'):
main_compile_args.append('/MT')
elif hasattr(os, 'uname') and os.uname()[4] in ['ppc64el', 'ppc64le']:
main_compile_args.append('-fno-tree-dominator-opts')
ext_modules = [
Extension(
name='greenlet._greenlet',
sources=[
GREENLET_SRC_DIR + 'greenlet.cpp',
],
language='c++',
extra_objects=extra_objects,
extra_compile_args=global_compile_args + main_compile_args + cpp_compile_args,
extra_link_args=cpp_link_args,
depends=[
GREENLET_HEADER,
GREENLET_SRC_DIR + 'slp_platformselect.h',
] + _find_platform_headers() + _find_impl_headers()
),
# Test extensions.
#
# We used to try hard to not include these in built
# distributions, because we only distributed ``greenlet.so``.
# That's really not important, now we have a clean layout with
# the test directory nested inside a greenlet directory. See
# https://github.com/python-greenlet/greenlet/issues/184 and
# 189
Extension(
name='greenlet.tests._test_extension',
sources=[GREENLET_TEST_DIR + '_test_extension.c'],
include_dirs=[GREENLET_HEADER_DIR],
extra_compile_args=global_compile_args,
),
Extension(
name='greenlet.tests._test_extension_cpp',
sources=[GREENLET_TEST_DIR + '_test_extension_cpp.cpp'],
language="c++",
include_dirs=[GREENLET_HEADER_DIR],
extra_compile_args=global_compile_args + cpp_compile_args,
extra_link_args=cpp_link_args,
),
]
def get_greenlet_version():
with open('src/greenlet/__init__.py') as f: # pylint:disable=unspecified-encoding
looking_for = '__version__ = \''
for line in f:
if line.startswith(looking_for):
version = line[len(looking_for):-2]
return version
raise ValueError("Unable to find version")
setup(
name="greenlet",
version=get_greenlet_version(),
description='Lightweight in-process concurrent programming',
long_description=readfile("README.rst"),
long_description_content_type="text/x-rst",
url="https://greenlet.readthedocs.io/",
keywords="greenlet coroutine concurrency threads cooperative",
author="Alexey Borzenkov",
author_email="snaury@gmail.com",
maintainer='Jason Madden',
maintainer_email='jason@nextthought.com',
project_urls={
'Bug Tracker': 'https://github.com/python-greenlet/greenlet/issues',
'Source Code': 'https://github.com/python-greenlet/greenlet/',
'Documentation': 'https://greenlet.readthedocs.io/',
},
license="MIT License",
platforms=['any'],
package_dir={'': 'src'},
packages=find_packages('src'),
include_package_data=True,
headers=headers,
ext_modules=ext_modules,
classifiers=[
"Development Status :: 5 - Production/Stable",
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: C',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'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',
'Programming Language :: Python :: 3.10',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules'
],
extras_require={
'docs': [
'Sphinx',
# 0.18b1 breaks sphinx 1.8.5 which is the latest version that runs
# on Python 2. The version pin sphinx itself contains isn't specific enough.
'docutils < 0.18; python_version < "3"',
],
'test': [
'objgraph',
'faulthandler; python_version == "2.7" and platform_python_implementation == "CPython"',
],
},
python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*",
zip_safe=False,
)
| 38.96875 | 104 | 0.655631 |
from __future__ import print_function
import sys
import os
import glob
import platform
from setuptools import setup
from setuptools import Extension
from setuptools import find_packages
global_compile_args = []
cpp_compile_args = []
cpp_link_args = []
main_compile_args = []
is_linux = sys.platform.startswith('linux')
if ((sys.platform == "openbsd4" and os.uname()[-1] == "i386")
or ("-with-redhat-3." in platform.platform() and platform.machine() == 'i686')
or (sys.platform == "sunos5" and os.uname()[-1] == "sun4v")
or ("SunOS" in platform.platform() and platform.machine() == "sun4v")
or (is_linux and platform.machine() == "ppc")):
global_compile_args.append("-Os")
if sys.platform == 'darwin':
cpp_compile_args.append("--std=gnu++11")
elif sys.platform == 'win32' and "MSC" in platform.python_compiler():
# Older versions of MSVC (Python 2.7) don't handle C++ exceptions
#"/EH" == exception handling.
# "s" == standard C++,
# "c" == extern C functions don't throw
# with it.
# See https://docs.microsoft.com/en-us/cpp/build/reference/eh-exception-handling-model?view=msvc-160
handler = "/EHsc"
cpp_compile_args.append(handler)
# To disable most optimizations:
#cpp_compile_args.append('/Od')
# To enable assertions:
#cpp_compile_args.append('/UNDEBUG')
# To enable more compile-time warnings (/Wall produces a mountain of output).
#cpp_compile_args.append('/W4')
# To link with the debug C runtime...except we can't because we need
# cpp_compile_args.append('/MDd')
# Support fiber-safe thread-local storage: "the compiler mustn't
# cache the address of the TLS array, or optimize it as a common
# subexpression across a function call." This would probably solve
cpp_compile_args.append("/GT")
def readfile(filename):
with open(filename, 'r') as f:
return f.read()
GREENLET_SRC_DIR = 'src/greenlet/'
GREENLET_HEADER_DIR = GREENLET_SRC_DIR
GREENLET_HEADER = GREENLET_HEADER_DIR + 'greenlet.h'
GREENLET_TEST_DIR = 'src/greenlet/tests/'
GREENLET_PLATFORM_DIR = GREENLET_SRC_DIR + 'platform/'
def _find_platform_headers():
return glob.glob(GREENLET_PLATFORM_DIR + "switch_*.h")
def _find_impl_headers():
return glob.glob(GREENLET_SRC_DIR + "*.hpp")
if hasattr(sys, "pypy_version_info"):
ext_modules = []
headers = []
else:
headers = [GREENLET_HEADER]
if sys.platform == 'win32' and '64 bit' in sys.version:
obj_fn = 'switch_arm64_masm.obj' if platform.machine() == 'ARM64' else 'switch_x64_masm.obj'
extra_objects = [os.path.join(GREENLET_PLATFORM_DIR, obj_fn)]
else:
extra_objects = []
if sys.platform == 'win32' and os.environ.get('GREENLET_STATIC_RUNTIME') in ('1', 'yes'):
main_compile_args.append('/MT')
elif hasattr(os, 'uname') and os.uname()[4] in ['ppc64el', 'ppc64le']:
main_compile_args.append('-fno-tree-dominator-opts')
ext_modules = [
Extension(
name='greenlet._greenlet',
sources=[
GREENLET_SRC_DIR + 'greenlet.cpp',
],
language='c++',
extra_objects=extra_objects,
extra_compile_args=global_compile_args + main_compile_args + cpp_compile_args,
extra_link_args=cpp_link_args,
depends=[
GREENLET_HEADER,
GREENLET_SRC_DIR + 'slp_platformselect.h',
] + _find_platform_headers() + _find_impl_headers()
),
# the test directory nested inside a greenlet directory. See
# https://github.com/python-greenlet/greenlet/issues/184 and
# 189
Extension(
name='greenlet.tests._test_extension',
sources=[GREENLET_TEST_DIR + '_test_extension.c'],
include_dirs=[GREENLET_HEADER_DIR],
extra_compile_args=global_compile_args,
),
Extension(
name='greenlet.tests._test_extension_cpp',
sources=[GREENLET_TEST_DIR + '_test_extension_cpp.cpp'],
language="c++",
include_dirs=[GREENLET_HEADER_DIR],
extra_compile_args=global_compile_args + cpp_compile_args,
extra_link_args=cpp_link_args,
),
]
def get_greenlet_version():
with open('src/greenlet/__init__.py') as f: # pylint:disable=unspecified-encoding
looking_for = '__version__ = \''
for line in f:
if line.startswith(looking_for):
version = line[len(looking_for):-2]
return version
raise ValueError("Unable to find version")
setup(
name="greenlet",
version=get_greenlet_version(),
description='Lightweight in-process concurrent programming',
long_description=readfile("README.rst"),
long_description_content_type="text/x-rst",
url="https://greenlet.readthedocs.io/",
keywords="greenlet coroutine concurrency threads cooperative",
author="Alexey Borzenkov",
author_email="snaury@gmail.com",
maintainer='Jason Madden',
maintainer_email='jason@nextthought.com',
project_urls={
'Bug Tracker': 'https://github.com/python-greenlet/greenlet/issues',
'Source Code': 'https://github.com/python-greenlet/greenlet/',
'Documentation': 'https://greenlet.readthedocs.io/',
},
license="MIT License",
platforms=['any'],
package_dir={'': 'src'},
packages=find_packages('src'),
include_package_data=True,
headers=headers,
ext_modules=ext_modules,
classifiers=[
"Development Status :: 5 - Production/Stable",
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: C',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'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',
'Programming Language :: Python :: 3.10',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules'
],
extras_require={
'docs': [
'Sphinx',
'docutils < 0.18; python_version < "3"',
],
'test': [
'objgraph',
'faulthandler; python_version == "2.7" and platform_python_implementation == "CPython"',
],
},
python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*",
zip_safe=False,
)
| true | true |
f73ba1260f6c61ae598472db10d540a6958cc696 | 4,421 | py | Python | apps/fastrunner/adminx.py | fairain/FasterRunner | 56e287bf0e45f0c31ac9a7dc6a4893d312088a11 | [
"MIT"
] | 19 | 2019-05-29T02:33:27.000Z | 2021-05-01T01:48:35.000Z | apps/fastrunner/adminx.py | fairain/FasterRunner | 56e287bf0e45f0c31ac9a7dc6a4893d312088a11 | [
"MIT"
] | 3 | 2020-06-06T01:08:24.000Z | 2021-06-10T22:25:19.000Z | apps/fastrunner/adminx.py | fairain/FasterRunner | 56e287bf0e45f0c31ac9a7dc6a4893d312088a11 | [
"MIT"
] | 6 | 2019-08-07T01:43:20.000Z | 2021-04-20T01:51:36.000Z | # -*- coding: utf-8 -*-
import xadmin
from xadmin import views
from .models import Project, Config, API, Case, CaseStep, HostIP, Variables, Report, ModelWithFileField, Pycode
from djcelery.models import TaskState, WorkerState, PeriodicTask, IntervalSchedule, CrontabSchedule, TaskMeta
class BaseSetting(object):
enable_themes = True
use_bootswatch = True
class GlobalSettings(object):
site_title = "fastrunner后台管理系统"
site_footer = "fastrunner"
class ProjectAdmin(object):
list_display = ['name', 'desc', 'responsible', 'create_time', 'update_time']
search_fields = ['name', 'desc', 'responsible']
list_filter = ['name', 'desc', 'responsible', 'create_time', 'update_time']
ordering = ['-update_time']
class ConfigAdmin(object):
list_display = ['name', 'body', 'base_url', 'project', 'create_time', 'update_time']
search_fields = ['name', 'body', 'base_url', 'project__name']
list_filter = ['name', 'body', 'base_url', 'project', 'create_time', 'update_time']
ordering = ['-update_time']
class APIAdmin(object):
list_display = ['name', 'body', 'url', 'method', 'relation', 'project', 'create_time', 'update_time']
search_fields = ['name', 'body', 'url', 'method', 'relation', 'project__name']
list_filter = ['name', 'body', 'url', 'method', 'relation', 'project', 'create_time', 'update_time']
ordering = ['-update_time']
class CaseAdmin(object):
list_display = ['name', 'length', 'tag', 'relation', 'project', 'create_time', 'update_time']
search_fields = ['name', 'length', 'tag', 'relation', 'project__name']
list_filter = ['name', 'length', 'tag', 'relation', 'project', 'create_time', 'update_time']
ordering = ['-update_time']
class CaseStepAdmin(object):
list_display = ['name', 'body', 'url', 'method', 'case', 'step', 'apiId', 'create_time', 'update_time']
search_fields = ['name', 'body', 'url', 'method', 'case__name', 'step', 'apiId']
list_filter = ['name', 'body', 'url', 'method', 'case', 'step', 'apiId', 'create_time', 'update_time']
ordering = ['-update_time']
class HostIPAdmin(object):
list_display = ['name', 'hostInfo', 'base_url', 'project', 'create_time', 'update_time']
search_fields = ['name', 'hostInfo', 'base_url', 'project__name']
list_filter = ['name', 'hostInfo', 'base_url', 'project', 'create_time', 'update_time']
ordering = ['-update_time']
class VariablesAdmin(object):
list_display = ['key', 'value', 'project', 'create_time', 'update_time']
search_fields = ['key', 'value', 'project__name']
list_filter = ['key', 'value', 'project', 'create_time', 'update_time']
ordering = ['-update_time']
class ReportAdmin(object):
list_display = ['name', 'type', 'summary', 'project', 'create_time']
search_fields = ['name', 'type', 'summary', 'project__name']
list_filter = ['name', 'type', 'summary', 'project', 'create_time']
ordering = ['-create_time']
class ModelWithFileFieldAdmin(object):
list_display = ['name', 'file', 'project', 'create_time', 'update_time']
search_fields = ['name', 'file', 'project__name']
list_filter = ['name', 'file', 'project', 'create_time', 'update_time']
ordering = ['-update_time']
class PycodeAdmin(object):
list_display = ['name', 'code', 'desc', 'project', 'create_time', 'update_time']
search_fields = ['name', 'code', 'desc', 'project__name']
list_filter = ['name', 'code', 'desc', 'project', 'create_time', 'update_time']
ordering = ['-update_time']
# 全局配置
# xadmin.site.register(views.BaseAdminView, BaseSetting) #因为配置域名的关系访问不到远程库,所以不使用多主题功能
xadmin.site.register(views.CommAdminView, GlobalSettings)
# djcelery
xadmin.site.register(IntervalSchedule) # 存储循环任务设置的时间
xadmin.site.register(CrontabSchedule) # 存储定时任务设置的时间
xadmin.site.register(PeriodicTask) # 存储任务
xadmin.site.register(TaskState) # 存储任务执行状态
xadmin.site.register(WorkerState) # 存储执行任务的worker
xadmin.site.register(TaskMeta) # 异步任务回执
# 自己的表
xadmin.site.register(Project, ProjectAdmin)
xadmin.site.register(Config, ConfigAdmin)
xadmin.site.register(API, APIAdmin)
xadmin.site.register(Case, CaseAdmin)
xadmin.site.register(CaseStep, CaseStepAdmin)
xadmin.site.register(HostIP, HostIPAdmin)
xadmin.site.register(Variables, VariablesAdmin)
xadmin.site.register(Report, ReportAdmin)
xadmin.site.register(ModelWithFileField, ModelWithFileFieldAdmin)
xadmin.site.register(Pycode, PycodeAdmin)
| 40.190909 | 111 | 0.689437 |
import xadmin
from xadmin import views
from .models import Project, Config, API, Case, CaseStep, HostIP, Variables, Report, ModelWithFileField, Pycode
from djcelery.models import TaskState, WorkerState, PeriodicTask, IntervalSchedule, CrontabSchedule, TaskMeta
class BaseSetting(object):
enable_themes = True
use_bootswatch = True
class GlobalSettings(object):
site_title = "fastrunner后台管理系统"
site_footer = "fastrunner"
class ProjectAdmin(object):
list_display = ['name', 'desc', 'responsible', 'create_time', 'update_time']
search_fields = ['name', 'desc', 'responsible']
list_filter = ['name', 'desc', 'responsible', 'create_time', 'update_time']
ordering = ['-update_time']
class ConfigAdmin(object):
list_display = ['name', 'body', 'base_url', 'project', 'create_time', 'update_time']
search_fields = ['name', 'body', 'base_url', 'project__name']
list_filter = ['name', 'body', 'base_url', 'project', 'create_time', 'update_time']
ordering = ['-update_time']
class APIAdmin(object):
list_display = ['name', 'body', 'url', 'method', 'relation', 'project', 'create_time', 'update_time']
search_fields = ['name', 'body', 'url', 'method', 'relation', 'project__name']
list_filter = ['name', 'body', 'url', 'method', 'relation', 'project', 'create_time', 'update_time']
ordering = ['-update_time']
class CaseAdmin(object):
list_display = ['name', 'length', 'tag', 'relation', 'project', 'create_time', 'update_time']
search_fields = ['name', 'length', 'tag', 'relation', 'project__name']
list_filter = ['name', 'length', 'tag', 'relation', 'project', 'create_time', 'update_time']
ordering = ['-update_time']
class CaseStepAdmin(object):
list_display = ['name', 'body', 'url', 'method', 'case', 'step', 'apiId', 'create_time', 'update_time']
search_fields = ['name', 'body', 'url', 'method', 'case__name', 'step', 'apiId']
list_filter = ['name', 'body', 'url', 'method', 'case', 'step', 'apiId', 'create_time', 'update_time']
ordering = ['-update_time']
class HostIPAdmin(object):
list_display = ['name', 'hostInfo', 'base_url', 'project', 'create_time', 'update_time']
search_fields = ['name', 'hostInfo', 'base_url', 'project__name']
list_filter = ['name', 'hostInfo', 'base_url', 'project', 'create_time', 'update_time']
ordering = ['-update_time']
class VariablesAdmin(object):
list_display = ['key', 'value', 'project', 'create_time', 'update_time']
search_fields = ['key', 'value', 'project__name']
list_filter = ['key', 'value', 'project', 'create_time', 'update_time']
ordering = ['-update_time']
class ReportAdmin(object):
list_display = ['name', 'type', 'summary', 'project', 'create_time']
search_fields = ['name', 'type', 'summary', 'project__name']
list_filter = ['name', 'type', 'summary', 'project', 'create_time']
ordering = ['-create_time']
class ModelWithFileFieldAdmin(object):
list_display = ['name', 'file', 'project', 'create_time', 'update_time']
search_fields = ['name', 'file', 'project__name']
list_filter = ['name', 'file', 'project', 'create_time', 'update_time']
ordering = ['-update_time']
class PycodeAdmin(object):
list_display = ['name', 'code', 'desc', 'project', 'create_time', 'update_time']
search_fields = ['name', 'code', 'desc', 'project__name']
list_filter = ['name', 'code', 'desc', 'project', 'create_time', 'update_time']
ordering = ['-update_time']
CommAdminView, GlobalSettings)
xadmin.site.register(IntervalSchedule)
xadmin.site.register(CrontabSchedule)
xadmin.site.register(PeriodicTask)
xadmin.site.register(TaskState)
xadmin.site.register(WorkerState)
xadmin.site.register(TaskMeta)
xadmin.site.register(Project, ProjectAdmin)
xadmin.site.register(Config, ConfigAdmin)
xadmin.site.register(API, APIAdmin)
xadmin.site.register(Case, CaseAdmin)
xadmin.site.register(CaseStep, CaseStepAdmin)
xadmin.site.register(HostIP, HostIPAdmin)
xadmin.site.register(Variables, VariablesAdmin)
xadmin.site.register(Report, ReportAdmin)
xadmin.site.register(ModelWithFileField, ModelWithFileFieldAdmin)
xadmin.site.register(Pycode, PycodeAdmin)
| true | true |
f73ba15148396433a160c8f2ad8cfdd25970f355 | 788 | py | Python | leetcode/algorithms/decode-ways.py | yasserglez/programming-problems | 08cef1186b182430b231ed9772d8f92ec1d2365b | [
"MIT"
] | 2 | 2017-02-17T01:40:27.000Z | 2018-04-22T12:47:28.000Z | leetcode/algorithms/decode-ways.py | yasserglez/programming-problems | 08cef1186b182430b231ed9772d8f92ec1d2365b | [
"MIT"
] | null | null | null | leetcode/algorithms/decode-ways.py | yasserglez/programming-problems | 08cef1186b182430b231ed9772d8f92ec1d2365b | [
"MIT"
] | 1 | 2016-10-14T06:00:42.000Z | 2016-10-14T06:00:42.000Z | # https://leetcode.com/problems/decode-ways/
import string
import fileinput
from typing import Dict
class Solution:
MAPPING = dict(zip(map(str, range(1, 28)), string.ascii_uppercase))
def _numDecodings(self, s: str, mem: Dict[str, int]) -> int:
if s in mem:
return mem[s]
mem[s] = 0
if len(s) >= 1 and s[:1] in self.MAPPING:
mem[s] += self._numDecodings(s[1:], mem)
if len(s) >= 2 and s[:2] in self.MAPPING:
mem[s] += self._numDecodings(s[2:], mem)
return mem[s]
def numDecodings(self, s: str) -> int:
mem = {"": 1}
return self._numDecodings(s, mem)
if __name__ == "__main__":
s = Solution()
for line in fileinput.input():
print(s.numDecodings(line.strip()))
| 24.625 | 71 | 0.573604 |
import string
import fileinput
from typing import Dict
class Solution:
MAPPING = dict(zip(map(str, range(1, 28)), string.ascii_uppercase))
def _numDecodings(self, s: str, mem: Dict[str, int]) -> int:
if s in mem:
return mem[s]
mem[s] = 0
if len(s) >= 1 and s[:1] in self.MAPPING:
mem[s] += self._numDecodings(s[1:], mem)
if len(s) >= 2 and s[:2] in self.MAPPING:
mem[s] += self._numDecodings(s[2:], mem)
return mem[s]
def numDecodings(self, s: str) -> int:
mem = {"": 1}
return self._numDecodings(s, mem)
if __name__ == "__main__":
s = Solution()
for line in fileinput.input():
print(s.numDecodings(line.strip()))
| true | true |
f73ba15bafc8d6ae0d62d795f37def44009aa0d3 | 8,945 | py | Python | delfin/drivers/hpe/hpe_3par/rest_handler.py | joseph-v/SIM | 61fedb261aa745d715b8a30c0945a6244fb807e2 | [
"Apache-2.0"
] | 4 | 2020-04-10T03:48:55.000Z | 2020-04-27T07:52:55.000Z | delfin/drivers/hpe/hpe_3par/rest_handler.py | joseph-v/SIM | 61fedb261aa745d715b8a30c0945a6244fb807e2 | [
"Apache-2.0"
] | 210 | 2020-05-08T04:06:49.000Z | 2020-06-22T12:59:02.000Z | delfin/drivers/hpe/hpe_3par/rest_handler.py | joseph-v/SIM | 61fedb261aa745d715b8a30c0945a6244fb807e2 | [
"Apache-2.0"
] | 10 | 2020-04-11T07:09:55.000Z | 2020-04-28T09:50:13.000Z | # Copyright 2020 The SODA Authors.
# Copyright (c) 2016 Huawei Technologies Co., Ltd.
# 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 threading
import six
from oslo_log import log as logging
from delfin import cryptor
from delfin import exception
from delfin.drivers.hpe.hpe_3par import consts
from delfin.drivers.utils.tools import Tools
LOG = logging.getLogger(__name__)
class RestHandler(object):
"""Common class for Hpe 3parStor storage system."""
REST_AUTH_URL = '/api/v1/credentials'
REST_LOGOUT_URL = '/api/v1/credentials/'
REST_STORAGE_URL = '/api/v1/system'
REST_CAPACITY_URL = '/api/v1/capacity'
REST_POOLS_URL = '/api/v1/cpgs'
REST_VOLUMES_URL = '/api/v1/volumes'
REST_ALERTS_URL = '/api/v1/eventlog?query="category EQ 2"'
REST_HOSTS_URL = '/api/v1/hosts'
REST_AUTH_KEY = 'X-HP3PAR-WSAPI-SessionKey'
REST_CPGSTATISTICS_URL = '/api/v1/systemreporter' \
'/attime/cpgstatistics/hires?' \
'query="sampleTime GE %s AND sampleTime LE %s"'
session_lock = None
def __init__(self, rest_client):
self.rest_client = rest_client
self.session_lock = threading.Lock()
def call(self, url, data=None, method=None):
"""Send requests to server.
If fail, try another RestURL.
Increase the judgment of token invalidation
"""
try:
res = self.rest_client.do_call(url, data, method,
calltimeout=consts.SOCKET_TIMEOUT)
# Judge whether the access failure is caused by
# the token invalidation.
# If the token fails, it will be retrieved again,
# and the token will be accessed again
if res is not None:
# 403 The client request has an invalid session key.
# The request came from a different IP address
# 409 Session key is being used.
if (res.status_code == consts.ERROR_SESSION_INVALID_CODE
or res.status_code ==
consts.ERROR_SESSION_IS_BEING_USED_CODE):
LOG.error(
"Failed to get token=={0}=={1}".format(res.status_code,
res.text))
LOG.error("Failed to get token,relogin,Get token again")
# if method is logout,return immediately
if method == 'DELETE' and RestHandler.\
REST_LOGOUT_URL in url:
return res
self.rest_client.rest_auth_token = None
access_session = self.login()
# if get token,Revisit url
if access_session is not None:
res = self.rest_client. \
do_call(url, data, method,
calltimeout=consts.SOCKET_TIMEOUT)
else:
LOG.error('Login res is None')
elif res.status_code == 503:
raise exception.InvalidResults(res.text)
else:
LOG.error('Rest exec failed')
return res
except exception.DelfinException as e:
err_msg = "Call failed: %s" % (six.text_type(e))
LOG.error(err_msg)
raise e
except Exception as e:
err_msg = "Get RestHandler.call failed: %s" % (six.text_type(e))
LOG.error(err_msg)
raise exception.InvalidResults(err_msg)
def get_resinfo_call(self, url, data=None, method=None):
rejson = None
res = self.call(url, data, method)
if res is not None:
if res.status_code == consts.SUCCESS_STATUS_CODES:
rejson = res.json()
else:
if res.text and 'unsupported' in res.text:
LOG.warning('rest api error: {}'.format(res.text))
else:
raise exception.StorageBackendException(res.text)
return rejson
def login(self):
"""Login Hpe3par storage array."""
try:
access_session = self.rest_client.rest_auth_token
if self.rest_client.san_address:
url = RestHandler.REST_AUTH_URL
data = {"user": self.rest_client.rest_username,
"password": cryptor.decode(
self.rest_client.rest_password)
}
self.session_lock.acquire()
if self.rest_client.rest_auth_token is not None:
return self.rest_client.rest_auth_token
self.rest_client.init_http_head()
res = self.rest_client. \
do_call(url, data, 'POST',
calltimeout=consts.SOCKET_TIMEOUT)
if res is None:
LOG.error('Login res is None')
raise exception.InvalidResults('res is None')
if res.status_code == consts. \
LOGIN_SUCCESS_STATUS_CODES:
result = res.json()
access_session = result.get('key')
self.rest_client.rest_auth_token = access_session
self.rest_client.session.headers[
RestHandler.REST_AUTH_KEY] = access_session
else:
LOG.error("Login error. URL: %(url)s\n"
"Reason: %(reason)s.",
{"url": url, "reason": res.text})
if 'invalid username or password' in res.text:
raise exception.InvalidUsernameOrPassword()
else:
raise exception.StorageBackendException(
six.text_type(res.text))
else:
LOG.error('Login Parameter error')
return access_session
except Exception as e:
LOG.error("Login error: %s", six.text_type(e))
raise e
finally:
self.session_lock.release()
def logout(self):
"""Logout the session."""
try:
url = RestHandler.REST_LOGOUT_URL
if self.rest_client.rest_auth_token is not None:
url = '%s%s' % (url, self.rest_client.rest_auth_token)
self.rest_client.rest_auth_token = None
if self.rest_client.san_address:
self.call(url, method='DELETE')
if self.rest_client.session:
self.rest_client.session.close()
except exception.DelfinException as e:
err_msg = "Logout error: %s" % (e.msg)
LOG.error(err_msg)
raise e
except Exception as e:
err_msg = "Logout error: %s" % (six.text_type(e))
LOG.error(err_msg)
raise exception.InvalidResults(err_msg)
def get_storage(self):
rejson = self.get_resinfo_call(RestHandler.REST_STORAGE_URL,
method='GET')
return rejson
def get_capacity(self):
rejson = self.get_resinfo_call(RestHandler.REST_CAPACITY_URL,
method='GET')
return rejson
def get_all_pools(self):
rejson = self.get_resinfo_call(RestHandler.REST_POOLS_URL,
method='GET')
return rejson
def get_all_volumes(self):
rejson = self.get_resinfo_call(RestHandler.REST_VOLUMES_URL,
method='GET')
return rejson
def get_pool_metrics(self, start_time, end_time):
start_time_str = Tools.timestamp_to_utc_time_str(
start_time, consts.REST_COLLEC_TTIME_PATTERN)
end_time_str = Tools.timestamp_to_utc_time_str(
end_time, consts.REST_COLLEC_TTIME_PATTERN)
url = RestHandler.REST_CPGSTATISTICS_URL % (
start_time_str, end_time_str)
rejson = self.get_resinfo_call(url, method='GET')
return rejson
def list_storage_host(self):
rejson = self.get_resinfo_call(RestHandler.REST_HOSTS_URL,
method='GET')
return rejson
| 39.579646 | 79 | 0.555953 |
import threading
import six
from oslo_log import log as logging
from delfin import cryptor
from delfin import exception
from delfin.drivers.hpe.hpe_3par import consts
from delfin.drivers.utils.tools import Tools
LOG = logging.getLogger(__name__)
class RestHandler(object):
REST_AUTH_URL = '/api/v1/credentials'
REST_LOGOUT_URL = '/api/v1/credentials/'
REST_STORAGE_URL = '/api/v1/system'
REST_CAPACITY_URL = '/api/v1/capacity'
REST_POOLS_URL = '/api/v1/cpgs'
REST_VOLUMES_URL = '/api/v1/volumes'
REST_ALERTS_URL = '/api/v1/eventlog?query="category EQ 2"'
REST_HOSTS_URL = '/api/v1/hosts'
REST_AUTH_KEY = 'X-HP3PAR-WSAPI-SessionKey'
REST_CPGSTATISTICS_URL = '/api/v1/systemreporter' \
'/attime/cpgstatistics/hires?' \
'query="sampleTime GE %s AND sampleTime LE %s"'
session_lock = None
def __init__(self, rest_client):
self.rest_client = rest_client
self.session_lock = threading.Lock()
def call(self, url, data=None, method=None):
try:
res = self.rest_client.do_call(url, data, method,
calltimeout=consts.SOCKET_TIMEOUT)
if res is not None:
if (res.status_code == consts.ERROR_SESSION_INVALID_CODE
or res.status_code ==
consts.ERROR_SESSION_IS_BEING_USED_CODE):
LOG.error(
"Failed to get token=={0}=={1}".format(res.status_code,
res.text))
LOG.error("Failed to get token,relogin,Get token again")
if method == 'DELETE' and RestHandler.\
REST_LOGOUT_URL in url:
return res
self.rest_client.rest_auth_token = None
access_session = self.login()
if access_session is not None:
res = self.rest_client. \
do_call(url, data, method,
calltimeout=consts.SOCKET_TIMEOUT)
else:
LOG.error('Login res is None')
elif res.status_code == 503:
raise exception.InvalidResults(res.text)
else:
LOG.error('Rest exec failed')
return res
except exception.DelfinException as e:
err_msg = "Call failed: %s" % (six.text_type(e))
LOG.error(err_msg)
raise e
except Exception as e:
err_msg = "Get RestHandler.call failed: %s" % (six.text_type(e))
LOG.error(err_msg)
raise exception.InvalidResults(err_msg)
def get_resinfo_call(self, url, data=None, method=None):
rejson = None
res = self.call(url, data, method)
if res is not None:
if res.status_code == consts.SUCCESS_STATUS_CODES:
rejson = res.json()
else:
if res.text and 'unsupported' in res.text:
LOG.warning('rest api error: {}'.format(res.text))
else:
raise exception.StorageBackendException(res.text)
return rejson
def login(self):
try:
access_session = self.rest_client.rest_auth_token
if self.rest_client.san_address:
url = RestHandler.REST_AUTH_URL
data = {"user": self.rest_client.rest_username,
"password": cryptor.decode(
self.rest_client.rest_password)
}
self.session_lock.acquire()
if self.rest_client.rest_auth_token is not None:
return self.rest_client.rest_auth_token
self.rest_client.init_http_head()
res = self.rest_client. \
do_call(url, data, 'POST',
calltimeout=consts.SOCKET_TIMEOUT)
if res is None:
LOG.error('Login res is None')
raise exception.InvalidResults('res is None')
if res.status_code == consts. \
LOGIN_SUCCESS_STATUS_CODES:
result = res.json()
access_session = result.get('key')
self.rest_client.rest_auth_token = access_session
self.rest_client.session.headers[
RestHandler.REST_AUTH_KEY] = access_session
else:
LOG.error("Login error. URL: %(url)s\n"
"Reason: %(reason)s.",
{"url": url, "reason": res.text})
if 'invalid username or password' in res.text:
raise exception.InvalidUsernameOrPassword()
else:
raise exception.StorageBackendException(
six.text_type(res.text))
else:
LOG.error('Login Parameter error')
return access_session
except Exception as e:
LOG.error("Login error: %s", six.text_type(e))
raise e
finally:
self.session_lock.release()
def logout(self):
try:
url = RestHandler.REST_LOGOUT_URL
if self.rest_client.rest_auth_token is not None:
url = '%s%s' % (url, self.rest_client.rest_auth_token)
self.rest_client.rest_auth_token = None
if self.rest_client.san_address:
self.call(url, method='DELETE')
if self.rest_client.session:
self.rest_client.session.close()
except exception.DelfinException as e:
err_msg = "Logout error: %s" % (e.msg)
LOG.error(err_msg)
raise e
except Exception as e:
err_msg = "Logout error: %s" % (six.text_type(e))
LOG.error(err_msg)
raise exception.InvalidResults(err_msg)
def get_storage(self):
rejson = self.get_resinfo_call(RestHandler.REST_STORAGE_URL,
method='GET')
return rejson
def get_capacity(self):
rejson = self.get_resinfo_call(RestHandler.REST_CAPACITY_URL,
method='GET')
return rejson
def get_all_pools(self):
rejson = self.get_resinfo_call(RestHandler.REST_POOLS_URL,
method='GET')
return rejson
def get_all_volumes(self):
rejson = self.get_resinfo_call(RestHandler.REST_VOLUMES_URL,
method='GET')
return rejson
def get_pool_metrics(self, start_time, end_time):
start_time_str = Tools.timestamp_to_utc_time_str(
start_time, consts.REST_COLLEC_TTIME_PATTERN)
end_time_str = Tools.timestamp_to_utc_time_str(
end_time, consts.REST_COLLEC_TTIME_PATTERN)
url = RestHandler.REST_CPGSTATISTICS_URL % (
start_time_str, end_time_str)
rejson = self.get_resinfo_call(url, method='GET')
return rejson
def list_storage_host(self):
rejson = self.get_resinfo_call(RestHandler.REST_HOSTS_URL,
method='GET')
return rejson
| true | true |
f73ba186175834f99c30359a8cd3f218441c1611 | 3,296 | py | Python | setup.py | ckmessi/alfred | 48f85f43ee89d4370e1ef5a5ce1158dffc0596d4 | [
"Apache-2.0"
] | 1 | 2022-01-05T01:19:52.000Z | 2022-01-05T01:19:52.000Z | setup.py | ckmessi/alfred | 48f85f43ee89d4370e1ef5a5ce1158dffc0596d4 | [
"Apache-2.0"
] | null | null | null | setup.py | ckmessi/alfred | 48f85f43ee89d4370e1ef5a5ce1158dffc0596d4 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
#
# Copyright (c) 2020 JinTian.
#
# This file is part of alfred
# (see http://jinfagang.github.io).
#
# 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.
#
"""
install alfred into local bin dir.
"""
from setuptools import setup, find_packages
from setuptools import setup, Extension
import io
from os import path
this_directory = path.abspath(path.dirname(__file__))
with io.open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(name='alfred-py',
version='2.8.13',
keywords=['deep learning', 'script helper', 'tools'],
description='''
Alfred is a DeepLearning utility library.
''',
long_description=long_description,
long_description_content_type='text/markdown',
license='Apache 2.0',
packages=[
'alfred',
'alfred.dl',
'alfred.dl.inference',
'alfred.dl.data',
'alfred.dl.data.common',
'alfred.dl.data.meta',
'alfred.dl.torch',
'alfred.dl.torch.train',
'alfred.dl.torch.distribute',
'alfred.dl.torch.runner',
'alfred.dl.torch.nn',
'alfred.dl.torch.nn.modules',
'alfred.dl.torch.ops',
'alfred.dl.metrics',
'alfred.dl.tf',
'alfred.dl.evaluator',
'alfred.vis',
'alfred.modules',
'alfred.modules.scrap',
'alfred.modules.text',
'alfred.modules.vision',
'alfred.modules.data',
'alfred.modules.dltool',
'alfred.modules.cabinet',
'alfred.modules.cabinet.mdparse',
'alfred.modules.cabinet.mdparse.formatters',
'alfred.modules.cabinet.mdparse.transformers',
'alfred.modules.cabinet.mdparse.transformers.html',
'alfred.modules.cabinet.mdparse.transformers.md',
'alfred.modules',
'alfred.fusion',
'alfred.vis.image',
'alfred.vis.pointcloud',
'alfred.utils',
'alfred.protos'
],
# package_dir={'alfred': 'alfred'},
entry_points={
'console_scripts': [
'alfred = alfred.alfred:main'
]
},
include_package_data=True,
author="Lucas Jin",
author_email="jinfagang19@163.com",
url='https://github.com/jinfagang/alfred',
platforms='any',
install_requires=['colorama', 'requests', 'regex', 'funcy', 'pascal-voc-writer',
'future', 'deprecated', 'loguru', 'pyquaternion', 'lxml']
)
| 33.979381 | 86 | 0.624393 |
from setuptools import setup, find_packages
from setuptools import setup, Extension
import io
from os import path
this_directory = path.abspath(path.dirname(__file__))
with io.open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(name='alfred-py',
version='2.8.13',
keywords=['deep learning', 'script helper', 'tools'],
description='''
Alfred is a DeepLearning utility library.
''',
long_description=long_description,
long_description_content_type='text/markdown',
license='Apache 2.0',
packages=[
'alfred',
'alfred.dl',
'alfred.dl.inference',
'alfred.dl.data',
'alfred.dl.data.common',
'alfred.dl.data.meta',
'alfred.dl.torch',
'alfred.dl.torch.train',
'alfred.dl.torch.distribute',
'alfred.dl.torch.runner',
'alfred.dl.torch.nn',
'alfred.dl.torch.nn.modules',
'alfred.dl.torch.ops',
'alfred.dl.metrics',
'alfred.dl.tf',
'alfred.dl.evaluator',
'alfred.vis',
'alfred.modules',
'alfred.modules.scrap',
'alfred.modules.text',
'alfred.modules.vision',
'alfred.modules.data',
'alfred.modules.dltool',
'alfred.modules.cabinet',
'alfred.modules.cabinet.mdparse',
'alfred.modules.cabinet.mdparse.formatters',
'alfred.modules.cabinet.mdparse.transformers',
'alfred.modules.cabinet.mdparse.transformers.html',
'alfred.modules.cabinet.mdparse.transformers.md',
'alfred.modules',
'alfred.fusion',
'alfred.vis.image',
'alfred.vis.pointcloud',
'alfred.utils',
'alfred.protos'
],
entry_points={
'console_scripts': [
'alfred = alfred.alfred:main'
]
},
include_package_data=True,
author="Lucas Jin",
author_email="jinfagang19@163.com",
url='https://github.com/jinfagang/alfred',
platforms='any',
install_requires=['colorama', 'requests', 'regex', 'funcy', 'pascal-voc-writer',
'future', 'deprecated', 'loguru', 'pyquaternion', 'lxml']
)
| true | true |
f73ba2bc52e48cbecdb860b9404b32baf7b51f16 | 262 | py | Python | reports/tests/__init__.py | allankellynet/mimas | 10025d43bba9e84f502a266760786842e7158a05 | [
"MIT"
] | null | null | null | reports/tests/__init__.py | allankellynet/mimas | 10025d43bba9e84f502a266760786842e7158a05 | [
"MIT"
] | 1 | 2020-02-05T13:00:29.000Z | 2020-02-05T13:00:29.000Z | tests/__init__.py | allankellynet/mimas | 10025d43bba9e84f502a266760786842e7158a05 | [
"MIT"
] | null | null | null | #-----------------------------------------------------
# Mimas: conference submission and review system
# (c) Allan Kelly 2016-2020 http://www.allankelly.net
# Licensed under MIT License, see LICENSE file
# -----------------------------------------------------
| 37.428571 | 55 | 0.442748 | true | true | |
f73ba402bc4b622f51aa158d62543f104495ca17 | 3,831 | py | Python | GPS_Berkley/experiments/mjc_disc_cost_pilqr_example/hyperparams.py | bvsk35/Hopping_Bot | 5a8c7d4fdb4ae0a5ddf96002deb3c9ba1116c216 | [
"MIT"
] | null | null | null | GPS_Berkley/experiments/mjc_disc_cost_pilqr_example/hyperparams.py | bvsk35/Hopping_Bot | 5a8c7d4fdb4ae0a5ddf96002deb3c9ba1116c216 | [
"MIT"
] | null | null | null | GPS_Berkley/experiments/mjc_disc_cost_pilqr_example/hyperparams.py | bvsk35/Hopping_Bot | 5a8c7d4fdb4ae0a5ddf96002deb3c9ba1116c216 | [
"MIT"
] | 1 | 2020-03-02T07:27:04.000Z | 2020-03-02T07:27:04.000Z | """ Hyperparameters for MJC 2D navigation with discontinous target region. """
from __future__ import division
from datetime import datetime
import os.path
import numpy as np
from gps import __file__ as gps_filepath
from gps.agent.mjc.agent_mjc import AgentMuJoCo
from gps.algorithm.algorithm_traj_opt_pilqr import AlgorithmTrajOptPILQR
from gps.algorithm.cost.cost_state import CostState
from gps.algorithm.cost.cost_binary_region import CostBinaryRegion
from gps.algorithm.cost.cost_sum import CostSum
from gps.algorithm.dynamics.dynamics_lr_prior import DynamicsLRPrior
from gps.algorithm.dynamics.dynamics_prior_gmm import DynamicsPriorGMM
from gps.algorithm.traj_opt.traj_opt_pilqr import TrajOptPILQR
from gps.algorithm.policy.lin_gauss_init import init_lqr
from gps.proto.gps_pb2 import JOINT_ANGLES, JOINT_VELOCITIES, \
END_EFFECTOR_POINTS, END_EFFECTOR_POINT_VELOCITIES, ACTION
from gps.gui.config import generate_experiment_info
SENSOR_DIMS = {
JOINT_ANGLES: 2,
JOINT_VELOCITIES: 2,
END_EFFECTOR_POINTS: 3,
END_EFFECTOR_POINT_VELOCITIES: 3,
ACTION: 2,
}
BASE_DIR = '/'.join(str.split(gps_filepath, '/')[:-2])
EXP_DIR = BASE_DIR + '/../experiments/mjc_disc_cost_pilqr_example/'
common = {
'experiment_name': 'my_experiment' + '_' + \
datetime.strftime(datetime.now(), '%m-%d-%y_%H-%M'),
'experiment_dir': EXP_DIR,
'data_files_dir': EXP_DIR + 'data_files/',
'target_filename': EXP_DIR + 'target.npz',
'log_filename': EXP_DIR + 'log.txt',
'conditions': 1,
}
if not os.path.exists(common['data_files_dir']):
os.makedirs(common['data_files_dir'])
agent = {
'type': AgentMuJoCo,
'filename': './mjc_models/pointmass_disc_cost.xml',
'x0': [np.array([1., 0., 0., 0.])],
'dt': 0.05,
'substeps': 5,
'conditions': common['conditions'],
'T': 100,
'sensor_dims': SENSOR_DIMS,
'state_include': [JOINT_ANGLES, JOINT_VELOCITIES,
END_EFFECTOR_POINTS, END_EFFECTOR_POINT_VELOCITIES],
'obs_include': [JOINT_ANGLES, JOINT_VELOCITIES,
END_EFFECTOR_POINTS, END_EFFECTOR_POINT_VELOCITIES],
'camera_pos': np.array([5., 6., 6.5, 0., 0., 0.]),
'smooth_noise_var': 3.,
}
algorithm = {
'type': AlgorithmTrajOptPILQR,
'conditions': common['conditions'],
'iterations': 20,
'step_rule': 'res_percent',
'step_rule_res_ratio_inc': 0.05,
'step_rule_res_ratio_dec': 0.2,
}
algorithm['init_traj_distr'] = {
'type': init_lqr,
'init_var': 20.,
'dt': agent['dt'],
'T': agent['T'],
}
state_cost = {
'type': CostState,
'data_types' : {
END_EFFECTOR_POINTS: {
'wp': np.ones(SENSOR_DIMS[END_EFFECTOR_POINTS]),
'target_state': np.array([3., 0, 0]),
},
},
}
binary_region_cost = {
'type': CostBinaryRegion,
'data_types' : {
END_EFFECTOR_POINTS: {
'wp': np.ones(SENSOR_DIMS[END_EFFECTOR_POINTS]),
'target_state': np.array([2.5, 0.5, 0]),
'max_distance': 0.3,
'outside_cost': 0.,
'inside_cost': -3.,
},
},
}
algorithm['cost'] = {
'type': CostSum,
'costs': [state_cost, binary_region_cost],
'weights': [1., 10.],
}
algorithm['dynamics'] = {
'type': DynamicsLRPrior,
'regularization': 1e-6,
'prior': {
'type': DynamicsPriorGMM,
'max_clusters': 2,
'min_samples_per_cluster': 40,
'max_samples': 20,
}
}
algorithm['traj_opt'] = {
'type': TrajOptPILQR,
'kl_threshold': 1.0,
}
algorithm['policy_opt'] = {}
config = {
'iterations': algorithm['iterations'],
'num_samples': 20,
'verbose_trials': 1,
'common': common,
'agent': agent,
'gui_on': True,
'algorithm': algorithm,
}
common['info'] = generate_experiment_info(config)
| 27.364286 | 78 | 0.655181 | from __future__ import division
from datetime import datetime
import os.path
import numpy as np
from gps import __file__ as gps_filepath
from gps.agent.mjc.agent_mjc import AgentMuJoCo
from gps.algorithm.algorithm_traj_opt_pilqr import AlgorithmTrajOptPILQR
from gps.algorithm.cost.cost_state import CostState
from gps.algorithm.cost.cost_binary_region import CostBinaryRegion
from gps.algorithm.cost.cost_sum import CostSum
from gps.algorithm.dynamics.dynamics_lr_prior import DynamicsLRPrior
from gps.algorithm.dynamics.dynamics_prior_gmm import DynamicsPriorGMM
from gps.algorithm.traj_opt.traj_opt_pilqr import TrajOptPILQR
from gps.algorithm.policy.lin_gauss_init import init_lqr
from gps.proto.gps_pb2 import JOINT_ANGLES, JOINT_VELOCITIES, \
END_EFFECTOR_POINTS, END_EFFECTOR_POINT_VELOCITIES, ACTION
from gps.gui.config import generate_experiment_info
SENSOR_DIMS = {
JOINT_ANGLES: 2,
JOINT_VELOCITIES: 2,
END_EFFECTOR_POINTS: 3,
END_EFFECTOR_POINT_VELOCITIES: 3,
ACTION: 2,
}
BASE_DIR = '/'.join(str.split(gps_filepath, '/')[:-2])
EXP_DIR = BASE_DIR + '/../experiments/mjc_disc_cost_pilqr_example/'
common = {
'experiment_name': 'my_experiment' + '_' + \
datetime.strftime(datetime.now(), '%m-%d-%y_%H-%M'),
'experiment_dir': EXP_DIR,
'data_files_dir': EXP_DIR + 'data_files/',
'target_filename': EXP_DIR + 'target.npz',
'log_filename': EXP_DIR + 'log.txt',
'conditions': 1,
}
if not os.path.exists(common['data_files_dir']):
os.makedirs(common['data_files_dir'])
agent = {
'type': AgentMuJoCo,
'filename': './mjc_models/pointmass_disc_cost.xml',
'x0': [np.array([1., 0., 0., 0.])],
'dt': 0.05,
'substeps': 5,
'conditions': common['conditions'],
'T': 100,
'sensor_dims': SENSOR_DIMS,
'state_include': [JOINT_ANGLES, JOINT_VELOCITIES,
END_EFFECTOR_POINTS, END_EFFECTOR_POINT_VELOCITIES],
'obs_include': [JOINT_ANGLES, JOINT_VELOCITIES,
END_EFFECTOR_POINTS, END_EFFECTOR_POINT_VELOCITIES],
'camera_pos': np.array([5., 6., 6.5, 0., 0., 0.]),
'smooth_noise_var': 3.,
}
algorithm = {
'type': AlgorithmTrajOptPILQR,
'conditions': common['conditions'],
'iterations': 20,
'step_rule': 'res_percent',
'step_rule_res_ratio_inc': 0.05,
'step_rule_res_ratio_dec': 0.2,
}
algorithm['init_traj_distr'] = {
'type': init_lqr,
'init_var': 20.,
'dt': agent['dt'],
'T': agent['T'],
}
state_cost = {
'type': CostState,
'data_types' : {
END_EFFECTOR_POINTS: {
'wp': np.ones(SENSOR_DIMS[END_EFFECTOR_POINTS]),
'target_state': np.array([3., 0, 0]),
},
},
}
binary_region_cost = {
'type': CostBinaryRegion,
'data_types' : {
END_EFFECTOR_POINTS: {
'wp': np.ones(SENSOR_DIMS[END_EFFECTOR_POINTS]),
'target_state': np.array([2.5, 0.5, 0]),
'max_distance': 0.3,
'outside_cost': 0.,
'inside_cost': -3.,
},
},
}
algorithm['cost'] = {
'type': CostSum,
'costs': [state_cost, binary_region_cost],
'weights': [1., 10.],
}
algorithm['dynamics'] = {
'type': DynamicsLRPrior,
'regularization': 1e-6,
'prior': {
'type': DynamicsPriorGMM,
'max_clusters': 2,
'min_samples_per_cluster': 40,
'max_samples': 20,
}
}
algorithm['traj_opt'] = {
'type': TrajOptPILQR,
'kl_threshold': 1.0,
}
algorithm['policy_opt'] = {}
config = {
'iterations': algorithm['iterations'],
'num_samples': 20,
'verbose_trials': 1,
'common': common,
'agent': agent,
'gui_on': True,
'algorithm': algorithm,
}
common['info'] = generate_experiment_info(config)
| true | true |
f73ba456a8d183a22a82ba4101b9c30900c4e534 | 11,541 | py | Python | pep425.py | brettcannon/pep425 | 5c9baea482ee4d643107ff2e10cd2c1996100977 | [
"BSD-3-Clause"
] | null | null | null | pep425.py | brettcannon/pep425 | 5c9baea482ee4d643107ff2e10cd2c1996100977 | [
"BSD-3-Clause"
] | 2 | 2018-11-22T20:03:18.000Z | 2018-12-16T10:14:31.000Z | pep425.py | brettcannon/pep425 | 5c9baea482ee4d643107ff2e10cd2c1996100977 | [
"BSD-3-Clause"
] | 1 | 2018-11-17T09:40:52.000Z | 2018-11-17T09:40:52.000Z | """Provide support for PEP 425 compatibility tags triples."""
import distutils.util
import os
import os.path
import platform
import sys
import sysconfig
INTERPRETER_SHORT_NAMES = {
"python": "py", # Generic.
"cpython": "cp",
"pypy": "pp",
"ironpython": "ip",
"jython": "jy",
}
_32_BIT_INTERPRETER = sys.maxsize <= 2 ** 32
# A dataclass would be better, but Python 2.7. :(
class Tag:
"""Representation of the interpreter/ABI/platform tag triple as specified by PEP 425."""
def __init__(self, interpreter, abi, platform):
"""Initialize the instance attributes.
All values are lowercased.
"""
self._tags = interpreter.lower(), abi.lower(), platform.lower()
def __eq__(self, other):
return self._tags == other._tags
def __hash__(self):
return hash(self._tags)
def __str__(self):
return "-".join(self._tags)
def __repr__(self):
return "<{self} @ {self_id}>".format(self=self, self_id=id(self))
@property
def interpreter(self):
return self._tags[0]
@property
def abi(self):
return self._tags[1]
@property
def platform(self):
return self._tags[2]
def parse_tag(tag):
"""Parse the tag triple.
The result can be more than one tag triple due to the possibility of
compressed tag triples.
"""
tags = set()
interpreters, abis, platforms = tag.split("-")
for interpreter in interpreters.split("."):
for abi in abis.split("."):
for platform in platforms.split("."):
tags.add(Tag(interpreter, abi, platform))
return frozenset(tags)
def parse_wheel_tag(path):
"""Parse the path of a wheel file for its tag triple(s)."""
name = os.path.splitext(path)[0]
parts = 3
index = len(name)
while parts:
index = name.rindex("-", 0, index)
parts -= 1
return parse_tag(name[index + 1 :])
def _normalize_string(string):
"""Convert 'string' to be compatible as a tag."""
return string.replace(".", "_").replace("-", "_")
def _cpython_interpreter(py_version):
# TODO: Is using py_version_nodot for interpreter version critical?
return "cp{major}{minor}".format(major=py_version[0], minor=py_version[1])
def _cpython_abi(py_version):
"""Calcuate the ABI for this CPython interpreter."""
soabi = sysconfig.get_config_var("SOABI")
if soabi:
_, options, _ = soabi.split("-", 2)
else:
found_options = [str(py_version[0]), str(py_version[1])]
if sysconfig.get_config_var("Py_DEBUG"):
found_options.append("d")
if sysconfig.get_config_var("WITH_PYMALLOC"):
found_options.append("m")
if sysconfig.get_config_var("Py_UNICODE_SIZE") == 4:
found_options.append("u")
options = "".join(found_options)
return "cp{options}".format(options=options)
def _cpython_tags(py_version, interpreter, abi, platforms):
for tag in (Tag(interpreter, abi, platform) for platform in platforms):
yield tag
# TODO: Make sure doing this on Windows isn't horrible.
for tag in (Tag(interpreter, "abi3", platform) for platform in platforms):
yield tag
for tag in (Tag(interpreter, "none", platform) for platform in platforms):
yield tag
# PEP 384 was first implemented in Python 3.2.
for minor_version in range(py_version[1] - 1, 1, -1):
for platform in platforms:
yield Tag(
"cp{major}{minor}".format(major=py_version[0], minor=minor_version),
"abi3",
platform,
)
def _pypy_interpreter():
return "pp{py_major}{pypy_major}{pypy_minor}".format(
py_major=sys.version_info[0],
pypy_major=sys.pypy_version_info.major,
pypy_minor=sys.pypy_version_info.minor,
)
def _generic_abi():
"""Get the ABI version for this interpreter."""
abi = sysconfig.get_config_var("SOABI")
if abi:
return _normalize_string(abi)
else:
return "none"
def _pypy_tags(py_version, interpreter, abi, platforms):
for tag in (Tag(interpreter, abi, platform) for platform in platforms):
yield tag
for tag in (Tag(interpreter, "none", platform) for platform in platforms):
yield tag
def _generic_tags(interpreter, py_version, abi, platforms):
for tag in (Tag(interpreter, abi, platform) for platform in platforms):
yield tag
if abi != "none":
for tag in (Tag(interpreter, "none", platform) for platform in platforms):
yield tag
def _py_interpreter_range(py_version):
"""Yield Python versions in descending order.
After the latest version, the major-only version will be yielded, and then
all following versions up to 'end'.
"""
yield "py{major}{minor}".format(major=py_version[0], minor=py_version[1])
yield "py{major}".format(major=py_version[0])
for minor in range(py_version[1] - 1, -1, -1):
yield "py{major}{minor}".format(major=py_version[0], minor=minor)
def _independent_tags(interpreter, py_version, platforms):
"""Return the sequence of tags that are consistent across implementations.
The tags consist of:
- py*-none-<platform>
- <interpreter>-none-any
- py*-none-any
"""
for version in _py_interpreter_range(py_version):
for platform in platforms:
yield Tag(version, "none", platform)
yield Tag(interpreter, "none", "any")
for version in _py_interpreter_range(py_version):
yield Tag(version, "none", "any")
def _mac_arch(arch, is_32bit=_32_BIT_INTERPRETER):
"""Calculate the CPU architecture for the interpreter on macOS."""
if is_32bit:
if arch.startswith("ppc"):
return "ppc"
else:
return "i386"
else:
return arch
def _mac_binary_formats(version, cpu_arch):
"""Calculate the supported binary formats for the specified macOS version and architecture."""
formats = [cpu_arch]
if cpu_arch == "x86_64":
if version >= (10, 4):
formats.extend(["intel", "fat64", "fat32"])
else:
return []
elif cpu_arch == "i386":
if version >= (10, 4):
formats.extend(["intel", "fat32", "fat"])
else:
return []
elif cpu_arch == "ppc64":
# TODO: Need to care about 32-bit PPC for ppc64 through 10.2?
if version > (10, 5) or version < (10, 4):
return []
else:
formats.append("fat64")
elif cpu_arch == "ppc":
if version <= (10, 6):
formats.extend(["fat32", "fat"])
else:
return []
formats.append("universal")
return formats
def _mac_platforms(version=None, arch=None):
"""Calculate the platform tags for macOS."""
version_str, _, cpu_arch = platform.mac_ver()
if version is None:
version = tuple(map(int, version_str.split(".")[:2]))
if arch is None:
arch = _mac_arch(cpu_arch)
platforms = []
for minor_version in range(version[1], -1, -1):
compat_version = version[0], minor_version
binary_formats = _mac_binary_formats(compat_version, arch)
for binary_format in binary_formats:
platforms.append(
"macosx_{major}_{minor}_{binary_format}".format(
major=compat_version[0],
minor=compat_version[1],
binary_format=binary_format,
)
)
return platforms
# From PEP 513.
def _is_manylinux_compatible(name, glibc_version):
# Check for presence of _manylinux module.
try:
import _manylinux
return bool(getattr(_manylinux, name + "_compatible"))
except (ImportError, AttributeError):
# Fall through to heuristic check below.
pass
return _have_compatible_glibc(*glibc_version)
# From PEP 513.
def _have_compatible_glibc(major, minimum_minor):
import ctypes
process_namespace = ctypes.CDLL(None)
try:
gnu_get_libc_version = process_namespace.gnu_get_libc_version
except AttributeError:
# Symbol doesn't exist -> therefore, we are not linked to
# glibc.
return False
# Call gnu_get_libc_version, which returns a string like "2.5".
gnu_get_libc_version.restype = ctypes.c_char_p
version_str = gnu_get_libc_version()
# py2 / py3 compatibility:
if not isinstance(version_str, str):
version_str = version_str.decode("ascii")
# Parse string and check against requested version.
version = [int(piece) for piece in version_str.split(".")]
assert len(version) == 2
if major != version[0]:
return False
if minimum_minor > version[1]:
return False
return True
def _linux_platforms(is_32bit=_32_BIT_INTERPRETER):
"""Return the supported platforms on Linux."""
linux = _normalize_string(distutils.util.get_platform())
if linux == "linux_x86_64" and is_32bit:
linux = "linux_i686"
# manylinux1: CentOS 5 w/ glibc 2.5.
# manylinux2010: CentOS 6 w/ glibc 2.12.
manylinux_support = ("manylinux2010", (2, 12)), ("manylinux1", (2, 5))
manylinux_support_iter = iter(manylinux_support)
for name, glibc_version in manylinux_support_iter:
if _is_manylinux_compatible(name, glibc_version):
platforms = [linux.replace("linux", name)]
break
else:
platforms = []
# Support for a later manylinux implies support for an earlier version.
platforms += [linux.replace("linux", name) for name, _ in manylinux_support_iter]
platforms.append(linux)
return platforms
def _generic_platforms():
platform = _normalize_string(distutils.util.get_platform())
return [platform]
def _interpreter_name():
"""Return the name of the running interpreter."""
name = platform.python_implementation().lower()
return INTERPRETER_SHORT_NAMES.get(name) or name
def _generic_interpreter(name, py_version):
version = sysconfig.get_config_var("py_version_nodot")
if not version:
version = "".join(py_version[:2])
return "{name}{version}".format(name=name, version=version)
def sys_tags():
"""Return the sequence of tag triples for the running interpreter.
The order of the sequence corresponds to priority order for the interpreter,
from most to least important.
"""
py_version = sys.version_info[:2]
interpreter_name = _interpreter_name()
if platform.system() == "Darwin":
platforms = _mac_platforms()
elif platform.system() == "Linux":
platforms = _linux_platforms()
else:
# TODO: Does Windows care if running under 32-bit Python on 64-bit OS?
platforms = _generic_platforms()
if interpreter_name == "cp":
interpreter = _cpython_interpreter(py_version)
abi = _cpython_abi(py_version)
for tag in _cpython_tags(py_version, interpreter, abi, platforms):
yield tag
elif interpreter_name == "pp":
interpreter = _pypy_interpreter()
abi = _generic_abi()
for tag in _pypy_tags(py_version, interpreter, abi, platforms):
yield tag
else:
interpreter = _generic_interpreter(interpreter_name, py_version)
abi = _generic_abi()
for tag in _generic_tags(interpreter, py_version, abi, platforms):
yield tag
for tag in _independent_tags(interpreter, py_version, platforms):
yield tag
| 31.107817 | 98 | 0.642059 |
import distutils.util
import os
import os.path
import platform
import sys
import sysconfig
INTERPRETER_SHORT_NAMES = {
"python": "py",
"cpython": "cp",
"pypy": "pp",
"ironpython": "ip",
"jython": "jy",
}
_32_BIT_INTERPRETER = sys.maxsize <= 2 ** 32
class Tag:
def __init__(self, interpreter, abi, platform):
self._tags = interpreter.lower(), abi.lower(), platform.lower()
def __eq__(self, other):
return self._tags == other._tags
def __hash__(self):
return hash(self._tags)
def __str__(self):
return "-".join(self._tags)
def __repr__(self):
return "<{self} @ {self_id}>".format(self=self, self_id=id(self))
@property
def interpreter(self):
return self._tags[0]
@property
def abi(self):
return self._tags[1]
@property
def platform(self):
return self._tags[2]
def parse_tag(tag):
tags = set()
interpreters, abis, platforms = tag.split("-")
for interpreter in interpreters.split("."):
for abi in abis.split("."):
for platform in platforms.split("."):
tags.add(Tag(interpreter, abi, platform))
return frozenset(tags)
def parse_wheel_tag(path):
name = os.path.splitext(path)[0]
parts = 3
index = len(name)
while parts:
index = name.rindex("-", 0, index)
parts -= 1
return parse_tag(name[index + 1 :])
def _normalize_string(string):
return string.replace(".", "_").replace("-", "_")
def _cpython_interpreter(py_version):
return "cp{major}{minor}".format(major=py_version[0], minor=py_version[1])
def _cpython_abi(py_version):
soabi = sysconfig.get_config_var("SOABI")
if soabi:
_, options, _ = soabi.split("-", 2)
else:
found_options = [str(py_version[0]), str(py_version[1])]
if sysconfig.get_config_var("Py_DEBUG"):
found_options.append("d")
if sysconfig.get_config_var("WITH_PYMALLOC"):
found_options.append("m")
if sysconfig.get_config_var("Py_UNICODE_SIZE") == 4:
found_options.append("u")
options = "".join(found_options)
return "cp{options}".format(options=options)
def _cpython_tags(py_version, interpreter, abi, platforms):
for tag in (Tag(interpreter, abi, platform) for platform in platforms):
yield tag
for tag in (Tag(interpreter, "abi3", platform) for platform in platforms):
yield tag
for tag in (Tag(interpreter, "none", platform) for platform in platforms):
yield tag
# PEP 384 was first implemented in Python 3.2.
for minor_version in range(py_version[1] - 1, 1, -1):
for platform in platforms:
yield Tag(
"cp{major}{minor}".format(major=py_version[0], minor=minor_version),
"abi3",
platform,
)
def _pypy_interpreter():
return "pp{py_major}{pypy_major}{pypy_minor}".format(
py_major=sys.version_info[0],
pypy_major=sys.pypy_version_info.major,
pypy_minor=sys.pypy_version_info.minor,
)
def _generic_abi():
abi = sysconfig.get_config_var("SOABI")
if abi:
return _normalize_string(abi)
else:
return "none"
def _pypy_tags(py_version, interpreter, abi, platforms):
for tag in (Tag(interpreter, abi, platform) for platform in platforms):
yield tag
for tag in (Tag(interpreter, "none", platform) for platform in platforms):
yield tag
def _generic_tags(interpreter, py_version, abi, platforms):
for tag in (Tag(interpreter, abi, platform) for platform in platforms):
yield tag
if abi != "none":
for tag in (Tag(interpreter, "none", platform) for platform in platforms):
yield tag
def _py_interpreter_range(py_version):
yield "py{major}{minor}".format(major=py_version[0], minor=py_version[1])
yield "py{major}".format(major=py_version[0])
for minor in range(py_version[1] - 1, -1, -1):
yield "py{major}{minor}".format(major=py_version[0], minor=minor)
def _independent_tags(interpreter, py_version, platforms):
for version in _py_interpreter_range(py_version):
for platform in platforms:
yield Tag(version, "none", platform)
yield Tag(interpreter, "none", "any")
for version in _py_interpreter_range(py_version):
yield Tag(version, "none", "any")
def _mac_arch(arch, is_32bit=_32_BIT_INTERPRETER):
if is_32bit:
if arch.startswith("ppc"):
return "ppc"
else:
return "i386"
else:
return arch
def _mac_binary_formats(version, cpu_arch):
formats = [cpu_arch]
if cpu_arch == "x86_64":
if version >= (10, 4):
formats.extend(["intel", "fat64", "fat32"])
else:
return []
elif cpu_arch == "i386":
if version >= (10, 4):
formats.extend(["intel", "fat32", "fat"])
else:
return []
elif cpu_arch == "ppc64":
# TODO: Need to care about 32-bit PPC for ppc64 through 10.2?
if version > (10, 5) or version < (10, 4):
return []
else:
formats.append("fat64")
elif cpu_arch == "ppc":
if version <= (10, 6):
formats.extend(["fat32", "fat"])
else:
return []
formats.append("universal")
return formats
def _mac_platforms(version=None, arch=None):
version_str, _, cpu_arch = platform.mac_ver()
if version is None:
version = tuple(map(int, version_str.split(".")[:2]))
if arch is None:
arch = _mac_arch(cpu_arch)
platforms = []
for minor_version in range(version[1], -1, -1):
compat_version = version[0], minor_version
binary_formats = _mac_binary_formats(compat_version, arch)
for binary_format in binary_formats:
platforms.append(
"macosx_{major}_{minor}_{binary_format}".format(
major=compat_version[0],
minor=compat_version[1],
binary_format=binary_format,
)
)
return platforms
# From PEP 513.
def _is_manylinux_compatible(name, glibc_version):
# Check for presence of _manylinux module.
try:
import _manylinux
return bool(getattr(_manylinux, name + "_compatible"))
except (ImportError, AttributeError):
# Fall through to heuristic check below.
pass
return _have_compatible_glibc(*glibc_version)
# From PEP 513.
def _have_compatible_glibc(major, minimum_minor):
import ctypes
process_namespace = ctypes.CDLL(None)
try:
gnu_get_libc_version = process_namespace.gnu_get_libc_version
except AttributeError:
# Symbol doesn't exist -> therefore, we are not linked to
return False
gnu_get_libc_version.restype = ctypes.c_char_p
version_str = gnu_get_libc_version()
if not isinstance(version_str, str):
version_str = version_str.decode("ascii")
version = [int(piece) for piece in version_str.split(".")]
assert len(version) == 2
if major != version[0]:
return False
if minimum_minor > version[1]:
return False
return True
def _linux_platforms(is_32bit=_32_BIT_INTERPRETER):
linux = _normalize_string(distutils.util.get_platform())
if linux == "linux_x86_64" and is_32bit:
linux = "linux_i686"
manylinux_support = ("manylinux2010", (2, 12)), ("manylinux1", (2, 5))
manylinux_support_iter = iter(manylinux_support)
for name, glibc_version in manylinux_support_iter:
if _is_manylinux_compatible(name, glibc_version):
platforms = [linux.replace("linux", name)]
break
else:
platforms = []
platforms += [linux.replace("linux", name) for name, _ in manylinux_support_iter]
platforms.append(linux)
return platforms
def _generic_platforms():
platform = _normalize_string(distutils.util.get_platform())
return [platform]
def _interpreter_name():
name = platform.python_implementation().lower()
return INTERPRETER_SHORT_NAMES.get(name) or name
def _generic_interpreter(name, py_version):
version = sysconfig.get_config_var("py_version_nodot")
if not version:
version = "".join(py_version[:2])
return "{name}{version}".format(name=name, version=version)
def sys_tags():
py_version = sys.version_info[:2]
interpreter_name = _interpreter_name()
if platform.system() == "Darwin":
platforms = _mac_platforms()
elif platform.system() == "Linux":
platforms = _linux_platforms()
else:
platforms = _generic_platforms()
if interpreter_name == "cp":
interpreter = _cpython_interpreter(py_version)
abi = _cpython_abi(py_version)
for tag in _cpython_tags(py_version, interpreter, abi, platforms):
yield tag
elif interpreter_name == "pp":
interpreter = _pypy_interpreter()
abi = _generic_abi()
for tag in _pypy_tags(py_version, interpreter, abi, platforms):
yield tag
else:
interpreter = _generic_interpreter(interpreter_name, py_version)
abi = _generic_abi()
for tag in _generic_tags(interpreter, py_version, abi, platforms):
yield tag
for tag in _independent_tags(interpreter, py_version, platforms):
yield tag
| true | true |
f73ba46818a5b829e4973856551bf743bdf50939 | 7,575 | py | Python | compilation/python/Lib/site-packages/pyflakes/messages.py | BodoMinea/blocklino | fa51a882cdf1ce3e9cbf7ef0f2b1bc0423bd051e | [
"CC0-1.0"
] | 11 | 2019-08-31T23:40:06.000Z | 2021-06-01T06:31:53.000Z | compilation/python/Lib/site-packages/pyflakes/messages.py | BodoMinea/blocklino | fa51a882cdf1ce3e9cbf7ef0f2b1bc0423bd051e | [
"CC0-1.0"
] | 301 | 2020-10-03T10:46:31.000Z | 2022-03-27T23:46:23.000Z | compilation/python/Lib/site-packages/pyflakes/messages.py | BodoMinea/blocklino | fa51a882cdf1ce3e9cbf7ef0f2b1bc0423bd051e | [
"CC0-1.0"
] | 12 | 2019-02-24T17:42:14.000Z | 2021-12-09T10:03:27.000Z | """
Provide the class Message and its subclasses.
"""
class Message(object):
message = ''
message_args = ()
def __init__(self, filename, loc):
self.filename = filename
self.lineno = loc.lineno
self.col = getattr(loc, 'col_offset', 0)
def __str__(self):
return '%s:%s: %s' % (self.filename, self.lineno,
self.message % self.message_args)
class UnusedImport(Message):
message = '%r imported but unused'
def __init__(self, filename, loc, name):
Message.__init__(self, filename, loc)
self.message_args = (name,)
class RedefinedWhileUnused(Message):
message = 'redefinition of unused %r from line %r'
def __init__(self, filename, loc, name, orig_loc):
Message.__init__(self, filename, loc)
self.message_args = (name, orig_loc.lineno)
class RedefinedInListComp(Message):
message = 'list comprehension redefines %r from line %r'
def __init__(self, filename, loc, name, orig_loc):
Message.__init__(self, filename, loc)
self.message_args = (name, orig_loc.lineno)
class ImportShadowedByLoopVar(Message):
message = 'import %r from line %r shadowed by loop variable'
def __init__(self, filename, loc, name, orig_loc):
Message.__init__(self, filename, loc)
self.message_args = (name, orig_loc.lineno)
class ImportStarNotPermitted(Message):
message = "'from %s import *' only allowed at module level"
def __init__(self, filename, loc, modname):
Message.__init__(self, filename, loc)
self.message_args = (modname,)
class ImportStarUsed(Message):
message = "'from %s import *' used; unable to detect undefined names"
def __init__(self, filename, loc, modname):
Message.__init__(self, filename, loc)
self.message_args = (modname,)
class ImportStarUsage(Message):
message = "%r may be undefined, or defined from star imports: %s"
def __init__(self, filename, loc, name, from_list):
Message.__init__(self, filename, loc)
self.message_args = (name, from_list)
class UndefinedName(Message):
message = 'undefined name %r'
def __init__(self, filename, loc, name):
Message.__init__(self, filename, loc)
self.message_args = (name,)
class DoctestSyntaxError(Message):
message = 'syntax error in doctest'
def __init__(self, filename, loc, position=None):
Message.__init__(self, filename, loc)
if position:
(self.lineno, self.col) = position
self.message_args = ()
class UndefinedExport(Message):
message = 'undefined name %r in __all__'
def __init__(self, filename, loc, name):
Message.__init__(self, filename, loc)
self.message_args = (name,)
class UndefinedLocal(Message):
message = 'local variable %r {0} referenced before assignment'
default = 'defined in enclosing scope on line %r'
builtin = 'defined as a builtin'
def __init__(self, filename, loc, name, orig_loc):
Message.__init__(self, filename, loc)
if orig_loc is None:
self.message = self.message.format(self.builtin)
self.message_args = name
else:
self.message = self.message.format(self.default)
self.message_args = (name, orig_loc.lineno)
class DuplicateArgument(Message):
message = 'duplicate argument %r in function definition'
def __init__(self, filename, loc, name):
Message.__init__(self, filename, loc)
self.message_args = (name,)
class MultiValueRepeatedKeyLiteral(Message):
message = 'dictionary key %r repeated with different values'
def __init__(self, filename, loc, key):
Message.__init__(self, filename, loc)
self.message_args = (key,)
class MultiValueRepeatedKeyVariable(Message):
message = 'dictionary key variable %s repeated with different values'
def __init__(self, filename, loc, key):
Message.__init__(self, filename, loc)
self.message_args = (key,)
class LateFutureImport(Message):
message = 'from __future__ imports must occur at the beginning of the file'
def __init__(self, filename, loc, names):
Message.__init__(self, filename, loc)
self.message_args = ()
class FutureFeatureNotDefined(Message):
"""An undefined __future__ feature name was imported."""
message = 'future feature %s is not defined'
def __init__(self, filename, loc, name):
Message.__init__(self, filename, loc)
self.message_args = (name,)
class UnusedVariable(Message):
"""
Indicates that a variable has been explicitly assigned to but not actually
used.
"""
message = 'local variable %r is assigned to but never used'
def __init__(self, filename, loc, names):
Message.__init__(self, filename, loc)
self.message_args = (names,)
class ReturnWithArgsInsideGenerator(Message):
"""
Indicates a return statement with arguments inside a generator.
"""
message = '\'return\' with argument inside generator'
class ReturnOutsideFunction(Message):
"""
Indicates a return statement outside of a function/method.
"""
message = '\'return\' outside function'
class YieldOutsideFunction(Message):
"""
Indicates a yield or yield from statement outside of a function/method.
"""
message = '\'yield\' outside function'
# For whatever reason, Python gives different error messages for these two. We
# match the Python error message exactly.
class ContinueOutsideLoop(Message):
"""
Indicates a continue statement outside of a while or for loop.
"""
message = '\'continue\' not properly in loop'
class BreakOutsideLoop(Message):
"""
Indicates a break statement outside of a while or for loop.
"""
message = '\'break\' outside loop'
class ContinueInFinally(Message):
"""
Indicates a continue statement in a finally block in a while or for loop.
"""
message = '\'continue\' not supported inside \'finally\' clause'
class DefaultExceptNotLast(Message):
"""
Indicates an except: block as not the last exception handler.
"""
message = 'default \'except:\' must be last'
class TwoStarredExpressions(Message):
"""
Two or more starred expressions in an assignment (a, *b, *c = d).
"""
message = 'two starred expressions in assignment'
class TooManyExpressionsInStarredAssignment(Message):
"""
Too many expressions in an assignment with star-unpacking
"""
message = 'too many expressions in star-unpacking assignment'
class AssertTuple(Message):
"""
Assertion test is a tuple, which are always True.
"""
message = 'assertion is always true, perhaps remove parentheses?'
class ForwardAnnotationSyntaxError(Message):
message = 'syntax error in forward annotation %r'
def __init__(self, filename, loc, annotation):
Message.__init__(self, filename, loc)
self.message_args = (annotation,)
class CommentAnnotationSyntaxError(Message):
message = 'syntax error in type comment %r'
def __init__(self, filename, loc, annotation):
Message.__init__(self, filename, loc)
self.message_args = (annotation,)
class RaiseNotImplemented(Message):
message = "'raise NotImplemented' should be 'raise NotImplementedError'"
class InvalidPrintSyntax(Message):
message = 'use of >> is invalid with print function'
class IsLiteral(Message):
message = 'use ==/!= to compare str, bytes, and int literals'
| 28.159851 | 79 | 0.674587 |
class Message(object):
message = ''
message_args = ()
def __init__(self, filename, loc):
self.filename = filename
self.lineno = loc.lineno
self.col = getattr(loc, 'col_offset', 0)
def __str__(self):
return '%s:%s: %s' % (self.filename, self.lineno,
self.message % self.message_args)
class UnusedImport(Message):
message = '%r imported but unused'
def __init__(self, filename, loc, name):
Message.__init__(self, filename, loc)
self.message_args = (name,)
class RedefinedWhileUnused(Message):
message = 'redefinition of unused %r from line %r'
def __init__(self, filename, loc, name, orig_loc):
Message.__init__(self, filename, loc)
self.message_args = (name, orig_loc.lineno)
class RedefinedInListComp(Message):
message = 'list comprehension redefines %r from line %r'
def __init__(self, filename, loc, name, orig_loc):
Message.__init__(self, filename, loc)
self.message_args = (name, orig_loc.lineno)
class ImportShadowedByLoopVar(Message):
message = 'import %r from line %r shadowed by loop variable'
def __init__(self, filename, loc, name, orig_loc):
Message.__init__(self, filename, loc)
self.message_args = (name, orig_loc.lineno)
class ImportStarNotPermitted(Message):
message = "'from %s import *' only allowed at module level"
def __init__(self, filename, loc, modname):
Message.__init__(self, filename, loc)
self.message_args = (modname,)
class ImportStarUsed(Message):
message = "'from %s import *' used; unable to detect undefined names"
def __init__(self, filename, loc, modname):
Message.__init__(self, filename, loc)
self.message_args = (modname,)
class ImportStarUsage(Message):
message = "%r may be undefined, or defined from star imports: %s"
def __init__(self, filename, loc, name, from_list):
Message.__init__(self, filename, loc)
self.message_args = (name, from_list)
class UndefinedName(Message):
message = 'undefined name %r'
def __init__(self, filename, loc, name):
Message.__init__(self, filename, loc)
self.message_args = (name,)
class DoctestSyntaxError(Message):
message = 'syntax error in doctest'
def __init__(self, filename, loc, position=None):
Message.__init__(self, filename, loc)
if position:
(self.lineno, self.col) = position
self.message_args = ()
class UndefinedExport(Message):
message = 'undefined name %r in __all__'
def __init__(self, filename, loc, name):
Message.__init__(self, filename, loc)
self.message_args = (name,)
class UndefinedLocal(Message):
message = 'local variable %r {0} referenced before assignment'
default = 'defined in enclosing scope on line %r'
builtin = 'defined as a builtin'
def __init__(self, filename, loc, name, orig_loc):
Message.__init__(self, filename, loc)
if orig_loc is None:
self.message = self.message.format(self.builtin)
self.message_args = name
else:
self.message = self.message.format(self.default)
self.message_args = (name, orig_loc.lineno)
class DuplicateArgument(Message):
message = 'duplicate argument %r in function definition'
def __init__(self, filename, loc, name):
Message.__init__(self, filename, loc)
self.message_args = (name,)
class MultiValueRepeatedKeyLiteral(Message):
message = 'dictionary key %r repeated with different values'
def __init__(self, filename, loc, key):
Message.__init__(self, filename, loc)
self.message_args = (key,)
class MultiValueRepeatedKeyVariable(Message):
message = 'dictionary key variable %s repeated with different values'
def __init__(self, filename, loc, key):
Message.__init__(self, filename, loc)
self.message_args = (key,)
class LateFutureImport(Message):
message = 'from __future__ imports must occur at the beginning of the file'
def __init__(self, filename, loc, names):
Message.__init__(self, filename, loc)
self.message_args = ()
class FutureFeatureNotDefined(Message):
message = 'future feature %s is not defined'
def __init__(self, filename, loc, name):
Message.__init__(self, filename, loc)
self.message_args = (name,)
class UnusedVariable(Message):
message = 'local variable %r is assigned to but never used'
def __init__(self, filename, loc, names):
Message.__init__(self, filename, loc)
self.message_args = (names,)
class ReturnWithArgsInsideGenerator(Message):
message = '\'return\' with argument inside generator'
class ReturnOutsideFunction(Message):
message = '\'return\' outside function'
class YieldOutsideFunction(Message):
message = '\'yield\' outside function'
class ContinueOutsideLoop(Message):
message = '\'continue\' not properly in loop'
class BreakOutsideLoop(Message):
message = '\'break\' outside loop'
class ContinueInFinally(Message):
message = '\'continue\' not supported inside \'finally\' clause'
class DefaultExceptNotLast(Message):
message = 'default \'except:\' must be last'
class TwoStarredExpressions(Message):
message = 'two starred expressions in assignment'
class TooManyExpressionsInStarredAssignment(Message):
message = 'too many expressions in star-unpacking assignment'
class AssertTuple(Message):
message = 'assertion is always true, perhaps remove parentheses?'
class ForwardAnnotationSyntaxError(Message):
message = 'syntax error in forward annotation %r'
def __init__(self, filename, loc, annotation):
Message.__init__(self, filename, loc)
self.message_args = (annotation,)
class CommentAnnotationSyntaxError(Message):
message = 'syntax error in type comment %r'
def __init__(self, filename, loc, annotation):
Message.__init__(self, filename, loc)
self.message_args = (annotation,)
class RaiseNotImplemented(Message):
message = "'raise NotImplemented' should be 'raise NotImplementedError'"
class InvalidPrintSyntax(Message):
message = 'use of >> is invalid with print function'
class IsLiteral(Message):
message = 'use ==/!= to compare str, bytes, and int literals'
| true | true |
f73ba491c7a25490b7735db2bebda9b7c1b333c2 | 67,424 | py | Python | dependencies/rdflib/graph.py | situx/geowebannotation | 1c4f27226913ae45f8943ee5fb2cabed494f3273 | [
"MIT"
] | 8 | 2019-05-29T09:38:30.000Z | 2021-01-20T03:36:59.000Z | dependencies/rdflib/graph.py | situx/geowebannotation | 1c4f27226913ae45f8943ee5fb2cabed494f3273 | [
"MIT"
] | 12 | 2021-03-09T03:01:16.000Z | 2022-03-11T23:59:36.000Z | dependencies/rdflib/graph.py | situx/geowebannotation | 1c4f27226913ae45f8943ee5fb2cabed494f3273 | [
"MIT"
] | 4 | 2021-06-10T18:54:16.000Z | 2021-10-25T00:42:22.000Z | from rdflib.term import Literal # required for doctests
assert Literal # avoid warning
from rdflib.namespace import Namespace # required for doctests
assert Namespace # avoid warning
from rdflib.py3compat import format_doctest_out
__doc__ = format_doctest_out("""\
RDFLib defines the following kinds of Graphs:
* :class:`~rdflib.graph.Graph`
* :class:`~rdflib.graph.QuotedGraph`
* :class:`~rdflib.graph.ConjunctiveGraph`
* :class:`~rdflib.graph.Dataset`
Graph
-----
An RDF graph is a set of RDF triples. Graphs support the python ``in``
operator, as well as iteration and some operations like union,
difference and intersection.
see :class:`~rdflib.graph.Graph`
Conjunctive Graph
-----------------
A Conjunctive Graph is the most relevant collection of graphs that are
considered to be the boundary for closed world assumptions. This
boundary is equivalent to that of the store instance (which is itself
uniquely identified and distinct from other instances of
:class:`Store` that signify other Conjunctive Graphs). It is
equivalent to all the named graphs within it and associated with a
``_default_`` graph which is automatically assigned a :class:`BNode`
for an identifier - if one isn't given.
see :class:`~rdflib.graph.ConjunctiveGraph`
Quoted graph
------------
The notion of an RDF graph [14] is extended to include the concept of
a formula node. A formula node may occur wherever any other kind of
node can appear. Associated with a formula node is an RDF graph that
is completely disjoint from all other graphs; i.e. has no nodes in
common with any other graph. (It may contain the same labels as other
RDF graphs; because this is, by definition, a separate graph,
considerations of tidiness do not apply between the graph at a formula
node and any other graph.)
This is intended to map the idea of "{ N3-expression }" that is used
by N3 into an RDF graph upon which RDF semantics is defined.
see :class:`~rdflib.graph.QuotedGraph`
Dataset
-------
The RDF 1.1 Dataset, a small extension to the Conjunctive Graph. The
primary term is "graphs in the datasets" and not "contexts with quads"
so there is a separate method to set/retrieve a graph in a dataset and
to operate with dataset graphs. As a consequence of this approach,
dataset graphs cannot be identified with blank nodes, a name is always
required (RDFLib will automatically add a name if one is not provided
at creation time). This implementation includes a convenience method
to directly add a single quad to a dataset graph.
see :class:`~rdflib.graph.Dataset`
Working with graphs
===================
Instantiating Graphs with default store (IOMemory) and default identifier
(a BNode):
>>> g = Graph()
>>> g.store.__class__
<class 'rdflib.plugins.memory.IOMemory'>
>>> g.identifier.__class__
<class 'rdflib.term.BNode'>
Instantiating Graphs with a IOMemory store and an identifier -
<http://rdflib.net>:
>>> g = Graph('IOMemory', URIRef("http://rdflib.net"))
>>> g.identifier
rdflib.term.URIRef(%(u)s'http://rdflib.net')
>>> str(g) # doctest: +NORMALIZE_WHITESPACE
"<http://rdflib.net> a rdfg:Graph;rdflib:storage
[a rdflib:Store;rdfs:label 'IOMemory']."
Creating a ConjunctiveGraph - The top level container for all named Graphs
in a 'database':
>>> g = ConjunctiveGraph()
>>> str(g.default_context)
"[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'IOMemory']]."
Adding / removing reified triples to Graph and iterating over it directly or
via triple pattern:
>>> g = Graph()
>>> statementId = BNode()
>>> print(len(g))
0
>>> g.add((statementId, RDF.type, RDF.Statement))
>>> g.add((statementId, RDF.subject,
... URIRef(%(u)s'http://rdflib.net/store/ConjunctiveGraph')))
>>> g.add((statementId, RDF.predicate, RDFS.label))
>>> g.add((statementId, RDF.object, Literal("Conjunctive Graph")))
>>> print(len(g))
4
>>> for s, p, o in g:
... print(type(s))
...
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
>>> for s, p, o in g.triples((None, RDF.object, None)):
... print(o)
...
Conjunctive Graph
>>> g.remove((statementId, RDF.type, RDF.Statement))
>>> print(len(g))
3
``None`` terms in calls to :meth:`~rdflib.graph.Graph.triples` can be
thought of as "open variables".
Graph support set-theoretic operators, you can add/subtract graphs, as
well as intersection (with multiplication operator g1*g2) and xor (g1
^ g2).
Note that BNode IDs are kept when doing set-theoretic operations, this
may or may not be what you want. Two named graphs within the same
application probably want share BNode IDs, two graphs with data from
different sources probably not. If your BNode IDs are all generated
by RDFLib they are UUIDs and unique.
>>> g1 = Graph()
>>> g2 = Graph()
>>> u = URIRef(%(u)s'http://example.com/foo')
>>> g1.add([u, RDFS.label, Literal('foo')])
>>> g1.add([u, RDFS.label, Literal('bar')])
>>> g2.add([u, RDFS.label, Literal('foo')])
>>> g2.add([u, RDFS.label, Literal('bing')])
>>> len(g1 + g2) # adds bing as label
3
>>> len(g1 - g2) # removes foo
1
>>> len(g1 * g2) # only foo
1
>>> g1 += g2 # now g1 contains everything
Graph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within
the same store:
>>> store = plugin.get('IOMemory', Store)()
>>> g1 = Graph(store)
>>> g2 = Graph(store)
>>> g3 = Graph(store)
>>> stmt1 = BNode()
>>> stmt2 = BNode()
>>> stmt3 = BNode()
>>> g1.add((stmt1, RDF.type, RDF.Statement))
>>> g1.add((stmt1, RDF.subject,
... URIRef(%(u)s'http://rdflib.net/store/ConjunctiveGraph')))
>>> g1.add((stmt1, RDF.predicate, RDFS.label))
>>> g1.add((stmt1, RDF.object, Literal("Conjunctive Graph")))
>>> g2.add((stmt2, RDF.type, RDF.Statement))
>>> g2.add((stmt2, RDF.subject,
... URIRef(%(u)s'http://rdflib.net/store/ConjunctiveGraph')))
>>> g2.add((stmt2, RDF.predicate, RDF.type))
>>> g2.add((stmt2, RDF.object, RDFS.Class))
>>> g3.add((stmt3, RDF.type, RDF.Statement))
>>> g3.add((stmt3, RDF.subject,
... URIRef(%(u)s'http://rdflib.net/store/ConjunctiveGraph')))
>>> g3.add((stmt3, RDF.predicate, RDFS.comment))
>>> g3.add((stmt3, RDF.object, Literal(
... "The top-level aggregate graph - The sum " +
... "of all named graphs within a Store")))
>>> len(list(ConjunctiveGraph(store).subjects(RDF.type, RDF.Statement)))
3
>>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects(
... RDF.type, RDF.Statement)))
2
ConjunctiveGraphs have a :meth:`~rdflib.graph.ConjunctiveGraph.quads` method
which returns quads instead of triples, where the fourth item is the Graph
(or subclass thereof) instance in which the triple was asserted:
>>> uniqueGraphNames = set(
... [graph.identifier for s, p, o, graph in ConjunctiveGraph(store
... ).quads((None, RDF.predicate, None))])
>>> len(uniqueGraphNames)
3
>>> unionGraph = ReadOnlyGraphAggregate([g1, g2])
>>> uniqueGraphNames = set(
... [graph.identifier for s, p, o, graph in unionGraph.quads(
... (None, RDF.predicate, None))])
>>> len(uniqueGraphNames)
2
Parsing N3 from a string
>>> g2 = Graph()
>>> src = '''
... @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
... [ a rdf:Statement ;
... rdf:subject <http://rdflib.net/store#ConjunctiveGraph>;
... rdf:predicate rdfs:label;
... rdf:object "Conjunctive Graph" ] .
... '''
>>> g2 = g2.parse(data=src, format='n3')
>>> print(len(g2))
4
Using Namespace class:
>>> RDFLib = Namespace('http://rdflib.net/')
>>> RDFLib.ConjunctiveGraph
rdflib.term.URIRef(%(u)s'http://rdflib.net/ConjunctiveGraph')
>>> RDFLib['Graph']
rdflib.term.URIRef(%(u)s'http://rdflib.net/Graph')
""")
import logging
logger = logging.getLogger(__name__)
# import md5
import random
import warnings
from hashlib import md5
try:
from io import BytesIO
assert BytesIO
except ImportError:
try:
from io import StringIO as BytesIO
assert BytesIO
except ImportError:
from io import StringIO as BytesIO
assert BytesIO
from rdflib.namespace import RDF, RDFS, SKOS
from rdflib import plugin, exceptions, query
from rdflib.term import Node, URIRef, Genid
from rdflib.term import BNode
import rdflib.term
from rdflib.paths import Path
from rdflib.store import Store
from rdflib.serializer import Serializer
from rdflib.parser import Parser
from rdflib.parser import create_input_source
from rdflib.namespace import NamespaceManager
from rdflib.resource import Resource
from rdflib.collection import Collection
from rdflib import py3compat
b = py3compat.b
import os
import shutil
import tempfile
from urllib.parse import urlparse
__all__ = [
'Graph', 'ConjunctiveGraph', 'QuotedGraph', 'Seq',
'ModificationException', 'Dataset',
'UnSupportedAggregateOperation', 'ReadOnlyGraphAggregate']
class Graph(Node):
"""An RDF Graph
The constructor accepts one argument, the 'store'
that will be used to store the graph data (see the 'store'
package for stores currently shipped with rdflib).
Stores can be context-aware or unaware. Unaware stores take up
(some) less space but cannot support features that require
context, such as true merging/demerging of sub-graphs and
provenance.
The Graph constructor can take an identifier which identifies the Graph
by name. If none is given, the graph is assigned a BNode for its
identifier.
For more on named graphs, see: http://www.w3.org/2004/03/trix/
"""
def __init__(self, store='default', identifier=None,
namespace_manager=None):
super(Graph, self).__init__()
self.__identifier = identifier or BNode()
if not isinstance(self.__identifier, Node):
self.__identifier = URIRef(self.__identifier)
if not isinstance(store, Store):
# TODO: error handling
self.__store = store = plugin.get(store, Store)()
else:
self.__store = store
self.__namespace_manager = namespace_manager
self.context_aware = False
self.formula_aware = False
self.default_union = False
def __get_store(self):
return self.__store
store = property(__get_store) # read-only attr
def __get_identifier(self):
return self.__identifier
identifier = property(__get_identifier) # read-only attr
def _get_namespace_manager(self):
if self.__namespace_manager is None:
self.__namespace_manager = NamespaceManager(self)
return self.__namespace_manager
def _set_namespace_manager(self, nm):
self.__namespace_manager = nm
namespace_manager = property(_get_namespace_manager,
_set_namespace_manager,
doc="this graph's namespace-manager")
def __repr__(self):
return "<Graph identifier=%s (%s)>" % (self.identifier, type(self))
def __str__(self):
if isinstance(self.identifier, URIRef):
return ("%s a rdfg:Graph;rdflib:storage " +
"[a rdflib:Store;rdfs:label '%s'].") % (
self.identifier.n3(),
self.store.__class__.__name__)
else:
return ("[a rdfg:Graph;rdflib:storage " +
"[a rdflib:Store;rdfs:label '%s']].") % (
self.store.__class__.__name__)
def toPython(self):
return self
def destroy(self, configuration):
"""Destroy the store identified by `configuration` if supported"""
self.__store.destroy(configuration)
# Transactional interfaces (optional)
def commit(self):
"""Commits active transactions"""
self.__store.commit()
def rollback(self):
"""Rollback active transactions"""
self.__store.rollback()
def open(self, configuration, create=False):
"""Open the graph store
Might be necessary for stores that require opening a connection to a
database or acquiring some resource.
"""
return self.__store.open(configuration, create)
def close(self, commit_pending_transaction=False):
"""Close the graph store
Might be necessary for stores that require closing a connection to a
database or releasing some resource.
"""
self.__store.close(
commit_pending_transaction=commit_pending_transaction)
def add(self, xxx_todo_changeme):
"""Add a triple with self as context"""
(s, p, o) = xxx_todo_changeme
assert isinstance(s, Node), \
"Subject %s must be an rdflib term" % (s,)
assert isinstance(p, Node), \
"Predicate %s must be an rdflib term" % (p,)
assert isinstance(o, Node), \
"Object %s must be an rdflib term" % (o,)
self.__store.add((s, p, o), self, quoted=False)
def addN(self, quads):
"""Add a sequence of triple with context"""
self.__store.addN((s, p, o, c) for s, p, o, c in quads
if isinstance(c, Graph)
and c.identifier is self.identifier
and _assertnode(s,p,o)
)
def remove(self, xxx_todo_changeme1):
"""Remove a triple from the graph
If the triple does not provide a context attribute, removes the triple
from all contexts.
"""
(s, p, o) = xxx_todo_changeme1
self.__store.remove((s, p, o), context=self)
def triples(self, xxx_todo_changeme2):
"""Generator over the triple store
Returns triples that match the given triple pattern. If triple pattern
does not provide a context, all contexts will be searched.
"""
(s, p, o) = xxx_todo_changeme2
if isinstance(p, Path):
for _s, _o in p.eval(self, s, o):
yield (_s, p, _o)
else:
for (s, p, o), cg in self.__store.triples((s, p, o), context=self):
yield (s, p, o)
@py3compat.format_doctest_out
def __getitem__(self, item):
"""
A graph can be "sliced" as a shortcut for the triples method
The python slice syntax is (ab)used for specifying triples.
A generator over matches is returned,
the returned tuples include only the parts not given
>>> import rdflib
>>> g = rdflib.Graph()
>>> g.add((rdflib.URIRef('urn:bob'), rdflib.RDFS.label, rdflib.Literal('Bob')))
>>> list(g[rdflib.URIRef('urn:bob')]) # all triples about bob
[(rdflib.term.URIRef(%(u)s'http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Literal(%(u)s'Bob'))]
>>> list(g[:rdflib.RDFS.label]) # all label triples
[(rdflib.term.URIRef(%(u)s'urn:bob'), rdflib.term.Literal(%(u)s'Bob'))]
>>> list(g[::rdflib.Literal('Bob')]) # all triples with bob as object
[(rdflib.term.URIRef(%(u)s'urn:bob'), rdflib.term.URIRef(%(u)s'http://www.w3.org/2000/01/rdf-schema#label'))]
Combined with SPARQL paths, more complex queries can be
written concisely:
Name of all Bobs friends:
g[bob : FOAF.knows/FOAF.name ]
Some label for Bob:
g[bob : DC.title|FOAF.name|RDFS.label]
All friends and friends of friends of Bob
g[bob : FOAF.knows * '+']
etc.
.. versionadded:: 4.0
"""
if isinstance(item, slice):
s,p,o=item.start,item.stop,item.step
if s is None and p is None and o is None:
return self.triples((s,p,o))
elif s is None and p is None:
return self.subject_predicates(o)
elif s is None and o is None:
return self.subject_objects(p)
elif p is None and o is None:
return self.predicate_objects(s)
elif s is None:
return self.subjects(p,o)
elif p is None:
return self.predicates(s,o)
elif o is None:
return self.objects(s,p)
else:
# all given
return (s,p,o) in self
elif isinstance(item, (Path,Node)):
return self.predicate_objects(item)
else:
raise TypeError("You can only index a graph by a single rdflib term or path, or a slice of rdflib terms.")
def __len__(self):
"""Returns the number of triples in the graph
If context is specified then the number of triples in the context is
returned instead.
"""
return self.__store.__len__(context=self)
def __iter__(self):
"""Iterates over all triples in the store"""
return self.triples((None, None, None))
def __contains__(self, triple):
"""Support for 'triple in graph' syntax"""
for triple in self.triples(triple):
return True
return False
def __hash__(self):
return hash(self.identifier)
def md5_term_hash(self):
d = md5(str(self.identifier))
d.update("G")
return d.hexdigest()
def __cmp__(self, other):
if other is None:
return -1
elif isinstance(other, Graph):
return cmp(self.identifier, other.identifier)
else:
# Note if None is considered equivalent to owl:Nothing
# Then perhaps a graph with length 0 should be considered
# equivalent to None (if compared to it)?
return 1
def __eq__(self, other):
return isinstance(other, Graph) \
and self.identifier == other.identifier
def __lt__(self, other):
return (other is None) \
or (isinstance(other, Graph)
and self.identifier < other.identifier)
def __le__(self, other):
return self < other or self == other
def __gt__(self, other):
return (isinstance(other, Graph)
and self.identifier > other.identifier) \
or (other is not None)
def __ge__(self, other):
return self > other or self == other
def __iadd__(self, other):
"""Add all triples in Graph other to Graph.
BNode IDs are not changed."""
self.addN((s, p, o, self) for s, p, o in other)
return self
def __isub__(self, other):
"""Subtract all triples in Graph other from Graph.
BNode IDs are not changed."""
for triple in other:
self.remove(triple)
return self
def __add__(self, other):
"""Set-theoretic union
BNode IDs are not changed."""
retval = Graph()
for (prefix, uri) in set(
list(self.namespaces()) + list(other.namespaces())):
retval.bind(prefix, uri)
for x in self:
retval.add(x)
for y in other:
retval.add(y)
return retval
def __mul__(self, other):
"""Set-theoretic intersection.
BNode IDs are not changed."""
retval = Graph()
for x in other:
if x in self:
retval.add(x)
return retval
def __sub__(self, other):
"""Set-theoretic difference.
BNode IDs are not changed."""
retval = Graph()
for x in self:
if not x in other:
retval.add(x)
return retval
def __xor__(self, other):
"""Set-theoretic XOR.
BNode IDs are not changed."""
return (self - other) + (other - self)
__or__ = __add__
__and__ = __mul__
# Conv. methods
def set(self, triple):
"""Convenience method to update the value of object
Remove any existing triples for subject and predicate before adding
(subject, predicate, object).
"""
(subject, predicate, object_) = triple
assert subject is not None, \
"s can't be None in .set([s,p,o]), as it would remove (*, p, *)"
assert predicate is not None, \
"p can't be None in .set([s,p,o]), as it would remove (s, *, *)"
self.remove((subject, predicate, None))
self.add((subject, predicate, object_))
def subjects(self, predicate=None, object=None):
"""A generator of subjects with the given predicate and object"""
for s, p, o in self.triples((None, predicate, object)):
yield s
def predicates(self, subject=None, object=None):
"""A generator of predicates with the given subject and object"""
for s, p, o in self.triples((subject, None, object)):
yield p
def objects(self, subject=None, predicate=None):
"""A generator of objects with the given subject and predicate"""
for s, p, o in self.triples((subject, predicate, None)):
yield o
def subject_predicates(self, object=None):
"""A generator of (subject, predicate) tuples for the given object"""
for s, p, o in self.triples((None, None, object)):
yield s, p
def subject_objects(self, predicate=None):
"""A generator of (subject, object) tuples for the given predicate"""
for s, p, o in self.triples((None, predicate, None)):
yield s, o
def predicate_objects(self, subject=None):
"""A generator of (predicate, object) tuples for the given subject"""
for s, p, o in self.triples((subject, None, None)):
yield p, o
def triples_choices(self, xxx_todo_changeme3, context=None):
(subject, predicate, object_) = xxx_todo_changeme3
for (s, p, o), cg in self.store.triples_choices(
(subject, predicate, object_), context=self):
yield (s, p, o)
def value(self, subject=None, predicate=RDF.value, object=None,
default=None, any=True):
"""Get a value for a pair of two criteria
Exactly one of subject, predicate, object must be None. Useful if one
knows that there may only be one value.
It is one of those situations that occur a lot, hence this
'macro' like utility
Parameters:
subject, predicate, object -- exactly one must be None
default -- value to be returned if no values found
any -- if True, return any value in the case there is more than one,
else, raise UniquenessError
"""
retval = default
if (subject is None and predicate is None) or \
(subject is None and object is None) or \
(predicate is None and object is None):
return None
if object is None:
values = self.objects(subject, predicate)
if subject is None:
values = self.subjects(predicate, object)
if predicate is None:
values = self.predicates(subject, object)
try:
retval = next(values)
except StopIteration:
retval = default
else:
if any is False:
try:
next(values)
msg = ("While trying to find a value for (%s, %s, %s) the"
" following multiple values where found:\n" %
(subject, predicate, object))
triples = self.store.triples(
(subject, predicate, object), None)
for (s, p, o), contexts in triples:
msg += "(%s, %s, %s)\n (contexts: %s)\n" % (
s, p, o, list(contexts))
raise exceptions.UniquenessError(msg)
except StopIteration:
pass
return retval
def label(self, subject, default=''):
"""Query for the RDFS.label of the subject
Return default if no label exists or any label if multiple exist.
"""
if subject is None:
return default
return self.value(subject, RDFS.label, default=default, any=True)
@py3compat.format_doctest_out
def preferredLabel(self, subject, lang=None, default=None,
labelProperties=(SKOS.prefLabel, RDFS.label)):
"""
Find the preferred label for subject.
By default prefers skos:prefLabels over rdfs:labels. In case at least
one prefLabel is found returns those, else returns labels. In case a
language string (e.g., 'en', 'de' or even '' for no lang-tagged
literals) is given, only such labels will be considered.
Return a list of (labelProp, label) pairs, where labelProp is either
skos:prefLabel or rdfs:label.
>>> from rdflib import ConjunctiveGraph, URIRef, RDFS, Literal
>>> from rdflib.namespace import SKOS
>>> from pprint import pprint
>>> g = ConjunctiveGraph()
>>> u = URIRef(%(u)s'http://example.com/foo')
>>> g.add([u, RDFS.label, Literal('foo')])
>>> g.add([u, RDFS.label, Literal('bar')])
>>> pprint(sorted(g.preferredLabel(u)))
[(rdflib.term.URIRef(%(u)s'http://www.w3.org/2000/01/rdf-schema#label'),
rdflib.term.Literal(%(u)s'bar')),
(rdflib.term.URIRef(%(u)s'http://www.w3.org/2000/01/rdf-schema#label'),
rdflib.term.Literal(%(u)s'foo'))]
>>> g.add([u, SKOS.prefLabel, Literal('bla')])
>>> pprint(g.preferredLabel(u))
[(rdflib.term.URIRef(%(u)s'http://www.w3.org/2004/02/skos/core#prefLabel'),
rdflib.term.Literal(%(u)s'bla'))]
>>> g.add([u, SKOS.prefLabel, Literal('blubb', lang='en')])
>>> sorted(g.preferredLabel(u)) #doctest: +NORMALIZE_WHITESPACE
[(rdflib.term.URIRef(%(u)s'http://www.w3.org/2004/02/skos/core#prefLabel'),
rdflib.term.Literal(%(u)s'bla')),
(rdflib.term.URIRef(%(u)s'http://www.w3.org/2004/02/skos/core#prefLabel'),
rdflib.term.Literal(%(u)s'blubb', lang='en'))]
>>> g.preferredLabel(u, lang='') #doctest: +NORMALIZE_WHITESPACE
[(rdflib.term.URIRef(%(u)s'http://www.w3.org/2004/02/skos/core#prefLabel'),
rdflib.term.Literal(%(u)s'bla'))]
>>> pprint(g.preferredLabel(u, lang='en'))
[(rdflib.term.URIRef(%(u)s'http://www.w3.org/2004/02/skos/core#prefLabel'),
rdflib.term.Literal(%(u)s'blubb', lang='en'))]
"""
if default is None:
default = []
# setup the language filtering
if lang is not None:
if lang == '': # we only want not language-tagged literals
langfilter = lambda l: l.language is None
else:
langfilter = lambda l: l.language == lang
else: # we don't care about language tags
langfilter = lambda l: True
for labelProp in labelProperties:
labels = list(filter(langfilter, self.objects(subject, labelProp)))
if len(labels) == 0:
continue
else:
return [(labelProp, l) for l in labels]
return default
def comment(self, subject, default=''):
"""Query for the RDFS.comment of the subject
Return default if no comment exists
"""
if subject is None:
return default
return self.value(subject, RDFS.comment, default=default, any=True)
def items(self, list):
"""Generator over all items in the resource specified by list
list is an RDF collection.
"""
chain = set([list])
while list:
item = self.value(list, RDF.first)
if item is not None:
yield item
list = self.value(list, RDF.rest)
if list in chain:
raise ValueError("List contains a recursive rdf:rest reference")
chain.add(list)
def transitiveClosure(self, func, arg, seen=None):
"""
Generates transitive closure of a user-defined
function against the graph
>>> from rdflib.collection import Collection
>>> g=Graph()
>>> a=BNode('foo')
>>> b=BNode('bar')
>>> c=BNode('baz')
>>> g.add((a,RDF.first,RDF.type))
>>> g.add((a,RDF.rest,b))
>>> g.add((b,RDF.first,RDFS.label))
>>> g.add((b,RDF.rest,c))
>>> g.add((c,RDF.first,RDFS.comment))
>>> g.add((c,RDF.rest,RDF.nil))
>>> def topList(node,g):
... for s in g.subjects(RDF.rest,node):
... yield s
>>> def reverseList(node,g):
... for f in g.objects(node,RDF.first):
... print(f)
... for s in g.subjects(RDF.rest,node):
... yield s
>>> [rt for rt in g.transitiveClosure(
... topList,RDF.nil)] # doctest: +NORMALIZE_WHITESPACE
[rdflib.term.BNode('baz'),
rdflib.term.BNode('bar'),
rdflib.term.BNode('foo')]
>>> [rt for rt in g.transitiveClosure(
... reverseList,RDF.nil)] # doctest: +NORMALIZE_WHITESPACE
http://www.w3.org/2000/01/rdf-schema#comment
http://www.w3.org/2000/01/rdf-schema#label
http://www.w3.org/1999/02/22-rdf-syntax-ns#type
[rdflib.term.BNode('baz'),
rdflib.term.BNode('bar'),
rdflib.term.BNode('foo')]
"""
if seen is None:
seen = {}
elif arg in seen:
return
seen[arg] = 1
for rt in func(arg, self):
yield rt
for rt_2 in self.transitiveClosure(func, rt, seen):
yield rt_2
def transitive_objects(self, subject, property, remember=None):
"""Transitively generate objects for the ``property`` relationship
Generated objects belong to the depth first transitive closure of the
``property`` relationship starting at ``subject``.
"""
if remember is None:
remember = {}
if subject in remember:
return
remember[subject] = 1
yield subject
for object in self.objects(subject, property):
for o in self.transitive_objects(object, property, remember):
yield o
def transitive_subjects(self, predicate, object, remember=None):
"""Transitively generate objects for the ``property`` relationship
Generated objects belong to the depth first transitive closure of the
``property`` relationship starting at ``subject``.
"""
if remember is None:
remember = {}
if object in remember:
return
remember[object] = 1
yield object
for subject in self.subjects(predicate, object):
for s in self.transitive_subjects(predicate, subject, remember):
yield s
def seq(self, subject):
"""Check if subject is an rdf:Seq
If yes, it returns a Seq class instance, None otherwise.
"""
if (subject, RDF.type, RDF.Seq) in self:
return Seq(self, subject)
else:
return None
def qname(self, uri):
return self.namespace_manager.qname(uri)
def compute_qname(self, uri, generate=True):
return self.namespace_manager.compute_qname(uri, generate)
def bind(self, prefix, namespace, override=True):
"""Bind prefix to namespace
If override is True will bind namespace to given prefix even
if namespace was already bound to a different prefix.
for example: graph.bind('foaf', 'http://xmlns.com/foaf/0.1/')
"""
return self.namespace_manager.bind(
prefix, namespace, override=override)
def namespaces(self):
"""Generator over all the prefix, namespace tuples"""
for prefix, namespace in self.namespace_manager.namespaces():
yield prefix, namespace
def absolutize(self, uri, defrag=1):
"""Turn uri into an absolute URI if it's not one already"""
return self.namespace_manager.absolutize(uri, defrag)
def serialize(self, destination=None, format="xml",
base=None, encoding=None, **args):
"""Serialize the Graph to destination
If destination is None serialize method returns the serialization as a
string. Format defaults to xml (AKA rdf/xml).
Format support can be extended with plugins,
but 'xml', 'n3', 'turtle', 'nt', 'pretty-xml', 'trix', 'trig' and 'nquads' are built in.
"""
serializer = plugin.get(format, Serializer)(self)
if destination is None:
stream = BytesIO()
serializer.serialize(stream, base=base, encoding=encoding, **args)
return stream.getvalue()
if hasattr(destination, "write"):
stream = destination
serializer.serialize(stream, base=base, encoding=encoding, **args)
else:
location = destination
scheme, netloc, path, params, _query, fragment = urlparse(location)
if netloc != "":
print(("WARNING: not saving as location" +
"is not a local file reference"))
return
fd, name = tempfile.mkstemp()
stream = os.fdopen(fd, "wb")
serializer.serialize(stream, base=base, encoding=encoding, **args)
stream.close()
if hasattr(shutil, "move"):
shutil.move(name, path)
else:
shutil.copy(name, path)
os.remove(name)
def parse(self, source=None, publicID=None, format=None,
location=None, file=None, data=None, **args):
"""
Parse source adding the resulting triples to the Graph.
The source is specified using one of source, location, file or
data.
:Parameters:
- `source`: An InputSource, file-like object, or string. In the case
of a string the string is the location of the source.
- `location`: A string indicating the relative or absolute URL of the
source. Graph's absolutize method is used if a relative location
is specified.
- `file`: A file-like object.
- `data`: A string containing the data to be parsed.
- `format`: Used if format can not be determined from source.
Defaults to rdf/xml. Format support can be extended with plugins,
but 'xml', 'n3', 'nt', 'trix', 'rdfa' are built in.
- `publicID`: the logical URI to use as the document base. If None
specified the document location is used (at least in the case where
there is a document location).
:Returns:
- self, the graph instance.
Examples:
>>> my_data = '''
... <rdf:RDF
... xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'
... xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema#'
... >
... <rdf:Description>
... <rdfs:label>Example</rdfs:label>
... <rdfs:comment>This is really just an example.</rdfs:comment>
... </rdf:Description>
... </rdf:RDF>
... '''
>>> import tempfile
>>> fd, file_name = tempfile.mkstemp()
>>> f = os.fdopen(fd, 'w')
>>> dummy = f.write(my_data) # Returns num bytes written on py3
>>> f.close()
>>> g = Graph()
>>> result = g.parse(data=my_data, format="application/rdf+xml")
>>> len(g)
2
>>> g = Graph()
>>> result = g.parse(location=file_name, format="application/rdf+xml")
>>> len(g)
2
>>> g = Graph()
>>> with open(file_name, "r") as f:
... result = g.parse(f, format="application/rdf+xml")
>>> len(g)
2
>>> os.remove(file_name)
"""
source = create_input_source(source=source, publicID=publicID,
location=location, file=file,
data=data, format=format)
if format is None:
format = source.content_type
if format is None:
# raise Exception("Could not determine format for %r. You can" + \
# "expicitly specify one with the format argument." % source)
format = "application/rdf+xml"
parser = plugin.get(format, Parser)()
try:
parser.parse(source, self, **args)
finally:
if source.auto_close:
source.close()
return self
def load(self, source, publicID=None, format="xml"):
self.parse(source, publicID, format)
def query(self, query_object, processor='sparql',
result='sparql', initNs=None, initBindings=None,
use_store_provided=True, **kwargs):
"""
Query this graph.
A type of 'prepared queries' can be realised by providing
initial variable bindings with initBindings
Initial namespaces are used to resolve prefixes used in the query,
if none are given, the namespaces from the graph's namespace manager
are used.
:returntype: rdflib.query.QueryResult
"""
initBindings = initBindings or {}
initNs = initNs or dict(self.namespaces())
if hasattr(self.store, "query") and use_store_provided:
try:
return self.store.query(
query_object, initNs, initBindings,
self.default_union
and '__UNION__'
or self.identifier,
**kwargs)
except NotImplementedError:
pass # store has no own implementation
if not isinstance(result, query.Result):
result = plugin.get(result, query.Result)
if not isinstance(processor, query.Processor):
processor = plugin.get(processor, query.Processor)(self)
return result(processor.query(
query_object, initBindings, initNs, **kwargs))
def update(self, update_object, processor='sparql',
initNs=None, initBindings=None,
use_store_provided=True, **kwargs):
"""Update this graph with the given update query."""
initBindings = initBindings or {}
initNs = initNs or dict(self.namespaces())
if hasattr(self.store, "update") and use_store_provided:
try:
return self.store.update(
update_object, initNs, initBindings,
self.default_union
and '__UNION__'
or self.identifier,
**kwargs)
except NotImplementedError:
pass # store has no own implementation
if not isinstance(processor, query.UpdateProcessor):
processor = plugin.get(processor, query.UpdateProcessor)(self)
return processor.update(update_object, initBindings, initNs, **kwargs)
def n3(self):
"""return an n3 identifier for the Graph"""
return "[%s]" % self.identifier.n3()
def __reduce__(self):
return (Graph, (self.store, self.identifier,))
def isomorphic(self, other):
"""
does a very basic check if these graphs are the same
If no BNodes are involved, this is accurate.
See rdflib.compare for a correct implementation of isomorphism checks
"""
# TODO: this is only an approximation.
if len(self) != len(other):
return False
for s, p, o in self:
if not isinstance(s, BNode) and not isinstance(o, BNode):
if not (s, p, o) in other:
return False
for s, p, o in other:
if not isinstance(s, BNode) and not isinstance(o, BNode):
if not (s, p, o) in self:
return False
# TODO: very well could be a false positive at this point yet.
return True
def connected(self):
"""Check if the Graph is connected
The Graph is considered undirectional.
Performs a search on the Graph, starting from a random node. Then
iteratively goes depth-first through the triplets where the node is
subject and object. Return True if all nodes have been visited and
False if it cannot continue and there are still unvisited nodes left.
"""
all_nodes = list(self.all_nodes())
discovered = []
# take a random one, could also always take the first one, doesn't
# really matter.
if not all_nodes:
return False
visiting = [all_nodes[random.randrange(len(all_nodes))]]
while visiting:
x = visiting.pop()
if x not in discovered:
discovered.append(x)
for new_x in self.objects(subject=x):
if new_x not in discovered and new_x not in visiting:
visiting.append(new_x)
for new_x in self.subjects(object=x):
if new_x not in discovered and new_x not in visiting:
visiting.append(new_x)
# optimisation by only considering length, since no new objects can
# be introduced anywhere.
if len(all_nodes) == len(discovered):
return True
else:
return False
def all_nodes(self):
res = set(self.objects())
res.update(self.subjects())
return res
def collection(self, identifier):
"""Create a new ``Collection`` instance.
Parameters:
- ``identifier``: a URIRef or BNode instance.
Example::
>>> graph = Graph()
>>> uri = URIRef("http://example.org/resource")
>>> collection = graph.collection(uri)
>>> assert isinstance(collection, Collection)
>>> assert collection.uri is uri
>>> assert collection.graph is graph
>>> collection += [ Literal(1), Literal(2) ]
"""
return Collection(self, identifier)
def resource(self, identifier):
"""Create a new ``Resource`` instance.
Parameters:
- ``identifier``: a URIRef or BNode instance.
Example::
>>> graph = Graph()
>>> uri = URIRef("http://example.org/resource")
>>> resource = graph.resource(uri)
>>> assert isinstance(resource, Resource)
>>> assert resource.identifier is uri
>>> assert resource.graph is graph
"""
if not isinstance(identifier, Node):
identifier = URIRef(identifier)
return Resource(self, identifier)
def _process_skolem_tuples(self, target, func):
for t in self.triples((None, None, None)):
target.add(func(t))
def skolemize(self, new_graph=None, bnode=None):
def do_skolemize(bnode, t):
(s, p, o) = t
if s == bnode:
s = s.skolemize()
if o == bnode:
o = o.skolemize()
return (s, p, o)
def do_skolemize2(t):
(s, p, o) = t
if isinstance(s, BNode):
s = s.skolemize()
if isinstance(o, BNode):
o = o.skolemize()
return (s, p, o)
retval = Graph() if new_graph is None else new_graph
if bnode is None:
self._process_skolem_tuples(retval, do_skolemize2)
elif isinstance(bnode, BNode):
self._process_skolem_tuples(
retval, lambda t: do_skolemize(bnode, t))
return retval
def de_skolemize(self, new_graph=None, uriref=None):
def do_de_skolemize(uriref, t):
(s, p, o) = t
if s == uriref:
s = s.de_skolemize()
if o == uriref:
o = o.de_skolemize()
return (s, p, o)
def do_de_skolemize2(t):
(s, p, o) = t
if isinstance(s, Genid):
s = s.de_skolemize()
if isinstance(o, Genid):
o = o.de_skolemize()
return (s, p, o)
retval = Graph() if new_graph is None else new_graph
if uriref is None:
self._process_skolem_tuples(retval, do_de_skolemize2)
elif isinstance(uriref, Genid):
self._process_skolem_tuples(
retval, lambda t: do_de_skolemize(uriref, t))
return retval
class ConjunctiveGraph(Graph):
"""
A ConjunctiveGraph is an (unnamed) aggregation of all the named
graphs in a store.
It has a ``default`` graph, whose name is associated with the
graph throughout its life. :meth:`__init__` can take an identifier
to use as the name of this default graph or it will assign a
BNode.
All methods that add triples work against this default graph.
All queries are carried out against the union of all graphs.
"""
def __init__(self, store='default', identifier=None):
super(ConjunctiveGraph, self).__init__(store, identifier=identifier)
assert self.store.context_aware, ("ConjunctiveGraph must be backed by"
" a context aware store.")
self.context_aware = True
self.default_union = True # Conjunctive!
self.default_context = Graph(store=self.store,
identifier=identifier or BNode())
def __str__(self):
pattern = ("[a rdflib:ConjunctiveGraph;rdflib:storage "
"[a rdflib:Store;rdfs:label '%s']]")
return pattern % self.store.__class__.__name__
def _spoc(self, triple_or_quad, default=False):
"""
helper method for having methods that support
either triples or quads
"""
if triple_or_quad is None:
return (None, None, None, self.default_context if default else None)
if len(triple_or_quad) == 3:
c = self.default_context if default else None
(s, p, o) = triple_or_quad
elif len(triple_or_quad) == 4:
(s, p, o, c) = triple_or_quad
c = self._graph(c)
return s,p,o,c
def __contains__(self, triple_or_quad):
"""Support for 'triple/quad in graph' syntax"""
s,p,o,c = self._spoc(triple_or_quad)
for t in self.triples((s,p,o), context=c):
return True
return False
def add(self, triple_or_quad):
"""
Add a triple or quad to the store.
if a triple is given it is added to the default context
"""
s,p,o,c = self._spoc(triple_or_quad, default=True)
_assertnode(s,p,o)
self.store.add((s, p, o), context=c, quoted=False)
def _graph(self, c):
if c is None: return None
if not isinstance(c, Graph):
return self.get_context(c)
else:
return c
def addN(self, quads):
"""Add a sequence of triples with context"""
self.store.addN(
(s, p, o, self._graph(c)) for s, p, o, c in quads if
_assertnode(s, p, o)
)
def remove(self, triple_or_quad):
"""
Removes a triple or quads
if a triple is given it is removed from all contexts
a quad is removed from the given context only
"""
s,p,o,c = self._spoc(triple_or_quad)
self.store.remove((s, p, o), context=c)
def triples(self, triple_or_quad, context=None):
"""
Iterate over all the triples in the entire conjunctive graph
For legacy reasons, this can take the context to query either
as a fourth element of the quad, or as the explicit context
keyword parameter. The kw param takes precedence.
"""
s,p,o,c = self._spoc(triple_or_quad)
context = self._graph(context or c)
if self.default_union:
if context==self.default_context:
context = None
else:
if context is None:
context = self.default_context
if isinstance(p, Path):
if context is None:
context = self
for s, o in p.eval(context, s, o):
yield (s, p, o)
else:
for (s, p, o), cg in self.store.triples((s, p, o), context=context):
yield s, p, o
def quads(self, triple_or_quad=None):
"""Iterate over all the quads in the entire conjunctive graph"""
s,p,o,c = self._spoc(triple_or_quad)
for (s, p, o), cg in self.store.triples((s, p, o), context=c):
for ctx in cg:
yield s, p, o, ctx
def triples_choices(self, xxx_todo_changeme4, context=None):
"""Iterate over all the triples in the entire conjunctive graph"""
(s, p, o) = xxx_todo_changeme4
if context is None:
if not self.default_union:
context=self.default_context
else:
context = self._graph(context)
for (s1, p1, o1), cg in self.store.triples_choices((s, p, o),
context=context):
yield (s1, p1, o1)
def __len__(self):
"""Number of triples in the entire conjunctive graph"""
return self.store.__len__()
def contexts(self, triple=None):
"""Iterate over all contexts in the graph
If triple is specified, iterate over all contexts the triple is in.
"""
for context in self.store.contexts(triple):
if isinstance(context, Graph):
# TODO: One of these should never happen and probably
# should raise an exception rather than smoothing over
# the weirdness - see #225
yield context
else:
yield self.get_context(context)
def get_context(self, identifier, quoted=False):
"""Return a context graph for the given identifier
identifier must be a URIRef or BNode.
"""
return Graph(store=self.store, identifier=identifier,
namespace_manager=self)
def remove_context(self, context):
"""Removes the given context from the graph"""
self.store.remove((None, None, None), context)
def context_id(self, uri, context_id=None):
"""URI#context"""
uri = uri.split("#", 1)[0]
if context_id is None:
context_id = "#context"
return URIRef(context_id, base=uri)
def parse(self, source=None, publicID=None, format="xml",
location=None, file=None, data=None, **args):
"""
Parse source adding the resulting triples to its own context
(sub graph of this graph).
See :meth:`rdflib.graph.Graph.parse` for documentation on arguments.
:Returns:
The graph into which the source was parsed. In the case of n3
it returns the root context.
"""
source = create_input_source(
source=source, publicID=publicID, location=location,
file=file, data=data, format=format)
g_id = publicID and publicID or source.getPublicId()
if not isinstance(g_id, Node):
g_id = URIRef(g_id)
context = Graph(store=self.store, identifier=g_id)
context.remove((None, None, None)) # hmm ?
context.parse(source, publicID=publicID, format=format, **args)
return context
def __reduce__(self):
return (ConjunctiveGraph, (self.store, self.identifier))
DATASET_DEFAULT_GRAPH_ID = URIRef('urn:x-rdflib:default')
class Dataset(ConjunctiveGraph):
__doc__ = format_doctest_out("""
RDF 1.1 Dataset. Small extension to the Conjunctive Graph:
- the primary term is graphs in the datasets and not contexts with quads,
so there is a separate method to set/retrieve a graph in a dataset and
operate with graphs
- graphs cannot be identified with blank nodes
- added a method to directly add a single quad
Examples of usage:
>>> # Create a new Dataset
>>> ds = Dataset()
>>> # simple triples goes to default graph
>>> ds.add((URIRef('http://example.org/a'),
... URIRef('http://www.example.org/b'),
... Literal('foo')))
>>>
>>> # Create a graph in the dataset, if the graph name has already been
>>> # used, the corresponding graph will be returned
>>> # (ie, the Dataset keeps track of the constituent graphs)
>>> g = ds.graph(URIRef('http://www.example.com/gr'))
>>>
>>> # add triples to the new graph as usual
>>> g.add(
... (URIRef('http://example.org/x'),
... URIRef('http://example.org/y'),
... Literal('bar')) )
>>> # alternatively: add a quad to the dataset -> goes to the graph
>>> ds.add(
... (URIRef('http://example.org/x'),
... URIRef('http://example.org/z'),
... Literal('foo-bar'),g) )
>>>
>>> # querying triples return them all regardless of the graph
>>> for t in ds.triples((None,None,None)): # doctest: +SKIP
... print(t) # doctest: +NORMALIZE_WHITESPACE
(rdflib.term.URIRef(%(u)s'http://example.org/a'),
rdflib.term.URIRef(%(u)s'http://www.example.org/b'),
rdflib.term.Literal(%(u)s'foo'))
(rdflib.term.URIRef(%(u)s'http://example.org/x'),
rdflib.term.URIRef(%(u)s'http://example.org/z'),
rdflib.term.Literal(%(u)s'foo-bar'))
(rdflib.term.URIRef(%(u)s'http://example.org/x'),
rdflib.term.URIRef(%(u)s'http://example.org/y'),
rdflib.term.Literal(%(u)s'bar'))
>>>
>>> # querying quads return quads; the fourth argument can be unrestricted
>>> # or restricted to a graph
>>> for q in ds.quads((None, None, None, None)): # doctest: +SKIP
... print(q) # doctest: +NORMALIZE_WHITESPACE
(rdflib.term.URIRef(%(u)s'http://example.org/a'),
rdflib.term.URIRef(%(u)s'http://www.example.org/b'),
rdflib.term.Literal(%(u)s'foo'),
None)
(rdflib.term.URIRef(%(u)s'http://example.org/x'),
rdflib.term.URIRef(%(u)s'http://example.org/y'),
rdflib.term.Literal(%(u)s'bar'),
rdflib.term.URIRef(%(u)s'http://www.example.com/gr'))
(rdflib.term.URIRef(%(u)s'http://example.org/x'),
rdflib.term.URIRef(%(u)s'http://example.org/z'),
rdflib.term.Literal(%(u)s'foo-bar'),
rdflib.term.URIRef(%(u)s'http://www.example.com/gr'))
>>>
>>> for q in ds.quads((None,None,None,g)): # doctest: +SKIP
... print(q) # doctest: +NORMALIZE_WHITESPACE
(rdflib.term.URIRef(%(u)s'http://example.org/x'),
rdflib.term.URIRef(%(u)s'http://example.org/y'),
rdflib.term.Literal(%(u)s'bar'),
rdflib.term.URIRef(%(u)s'http://www.example.com/gr'))
(rdflib.term.URIRef(%(u)s'http://example.org/x'),
rdflib.term.URIRef(%(u)s'http://example.org/z'),
rdflib.term.Literal(%(u)s'foo-bar'),
rdflib.term.URIRef(%(u)s'http://www.example.com/gr'))
>>> # Note that in the call above -
>>> # ds.quads((None,None,None,'http://www.example.com/gr'))
>>> # would have been accepted, too
>>>
>>> # graph names in the dataset can be queried:
>>> for c in ds.graphs(): # doctest: +SKIP
... print(c) # doctest:
DEFAULT
http://www.example.com/gr
>>> # A graph can be created without specifying a name; a skolemized genid
>>> # is created on the fly
>>> h = ds.graph()
>>> for c in ds.graphs(): # doctest: +SKIP
... print(c) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
DEFAULT
http://rdlib.net/.well-known/genid/rdflib/N...
http://www.example.com/gr
>>> # Note that the Dataset.graphs() call returns names of empty graphs,
>>> # too. This can be restricted:
>>> for c in ds.graphs(empty=False): # doctest: +SKIP
... print(c) # doctest: +NORMALIZE_WHITESPACE
DEFAULT
http://www.example.com/gr
>>>
>>> # a graph can also be removed from a dataset via ds.remove_graph(g)
.. versionadded:: 4.0
""")
def __init__(self, store='default', default_union=False):
super(Dataset, self).__init__(store=store, identifier=None)
if not self.store.graph_aware:
raise Exception("DataSet must be backed by a graph-aware store!")
self.default_context = Graph(store=self.store, identifier=DATASET_DEFAULT_GRAPH_ID)
self.default_union = default_union
def __str__(self):
pattern = ("[a rdflib:Dataset;rdflib:storage "
"[a rdflib:Store;rdfs:label '%s']]")
return pattern % self.store.__class__.__name__
def graph(self, identifier=None):
if identifier is None:
from rdflib.term import rdflib_skolem_genid
self.bind(
"genid", "http://rdflib.net" + rdflib_skolem_genid,
override=False)
identifier = BNode().skolemize()
g = self._graph(identifier)
self.store.add_graph(g)
return g
def parse(self, source=None, publicID=None, format="xml",
location=None, file=None, data=None, **args):
c = ConjunctiveGraph.parse(self, source, publicID, format, location, file, data, **args)
self.graph(c)
return c
def add_graph(self, g):
"""alias of graph for consistency"""
return self.graph(g)
def remove_graph(self, g):
if not isinstance(g, Graph):
g = self.get_context(g)
self.store.remove_graph(g)
if g is None or g == self.default_context:
# default graph cannot be removed
# only triples deleted, so add it back in
self.store.add_graph(self.default_context)
def contexts(self, triple=None):
default = False
for c in super(Dataset, self).contexts(triple):
default |= c.identifier == DATASET_DEFAULT_GRAPH_ID
yield c
if not default:
yield self.graph(DATASET_DEFAULT_GRAPH_ID)
graphs = contexts
def quads(self, quad):
for s, p, o, c in super(Dataset, self).quads(quad):
if c.identifier==self.default_context:
yield (s, p, o, None)
else:
yield (s, p, o, c.identifier)
class QuotedGraph(Graph):
"""
Quoted Graphs are intended to implement Notation 3 formulae. They are
associated with a required identifier that the N3 parser *must* provide
in order to maintain consistent formulae identification for scenarios
such as implication and other such processing.
"""
def __init__(self, store, identifier):
super(QuotedGraph, self).__init__(store, identifier)
def add(self, xxx_todo_changeme5):
"""Add a triple with self as context"""
(s, p, o) = xxx_todo_changeme5
assert isinstance(s, Node), \
"Subject %s must be an rdflib term" % (s,)
assert isinstance(p, Node), \
"Predicate %s must be an rdflib term" % (p,)
assert isinstance(o, Node), \
"Object %s must be an rdflib term" % (o,)
self.store.add((s, p, o), self, quoted=True)
def addN(self, quads):
"""Add a sequence of triple with context"""
self.store.addN(
(s, p, o, c) for s, p, o, c in quads
if isinstance(c, QuotedGraph)
and c.identifier is self.identifier
and _assertnode(s, p, o)
)
def n3(self):
"""Return an n3 identifier for the Graph"""
return "{%s}" % self.identifier.n3()
def __str__(self):
identifier = self.identifier.n3()
label = self.store.__class__.__name__
pattern = ("{this rdflib.identifier %s;rdflib:storage "
"[a rdflib:Store;rdfs:label '%s']}")
return pattern % (identifier, label)
def __reduce__(self):
return (QuotedGraph, (self.store, self.identifier))
# Make sure QuotedGraph is ordered correctly
# wrt to other Terms.
# this must be done here, as the QuotedGraph cannot be
# circularily imported in term.py
rdflib.term._ORDERING[QuotedGraph]=11
class Seq(object):
"""Wrapper around an RDF Seq resource
It implements a container type in Python with the order of the items
returned corresponding to the Seq content. It is based on the natural
ordering of the predicate names _1, _2, _3, etc, which is the
'implementation' of a sequence in RDF terms.
"""
def __init__(self, graph, subject):
"""Parameters:
- graph:
the graph containing the Seq
- subject:
the subject of a Seq. Note that the init does not
check whether this is a Seq, this is done in whoever
creates this instance!
"""
_list = self._list = list()
LI_INDEX = URIRef(str(RDF) + "_")
for (p, o) in graph.predicate_objects(subject):
if p.startswith(LI_INDEX): # != RDF.Seq: #
i = int(p.replace(LI_INDEX, ''))
_list.append((i, o))
# here is the trick: the predicates are _1, _2, _3, etc. Ie,
# by sorting the keys (by integer) we have what we want!
_list.sort()
def toPython(self):
return self
def __iter__(self):
"""Generator over the items in the Seq"""
for _, item in self._list:
yield item
def __len__(self):
"""Length of the Seq"""
return len(self._list)
def __getitem__(self, index):
"""Item given by index from the Seq"""
index, item = self._list.__getitem__(index)
return item
class ModificationException(Exception):
def __init__(self):
pass
def __str__(self):
return ("Modifications and transactional operations not allowed on "
"ReadOnlyGraphAggregate instances")
class UnSupportedAggregateOperation(Exception):
def __init__(self):
pass
def __str__(self):
return ("This operation is not supported by ReadOnlyGraphAggregate "
"instances")
class ReadOnlyGraphAggregate(ConjunctiveGraph):
"""Utility class for treating a set of graphs as a single graph
Only read operations are supported (hence the name). Essentially a
ConjunctiveGraph over an explicit subset of the entire store.
"""
def __init__(self, graphs, store='default'):
if store is not None:
super(ReadOnlyGraphAggregate, self).__init__(store)
Graph.__init__(self, store)
self.__namespace_manager = None
assert isinstance(graphs, list) \
and graphs \
and [g for g in graphs if isinstance(g, Graph)], \
"graphs argument must be a list of Graphs!!"
self.graphs = graphs
def __repr__(self):
return "<ReadOnlyGraphAggregate: %s graphs>" % len(self.graphs)
def destroy(self, configuration):
raise ModificationException()
# Transactional interfaces (optional)
def commit(self):
raise ModificationException()
def rollback(self):
raise ModificationException()
def open(self, configuration, create=False):
# TODO: is there a use case for this method?
for graph in self.graphs:
graph.open(self, configuration, create)
def close(self):
for graph in self.graphs:
graph.close()
def add(self, xxx_todo_changeme6):
(s, p, o) = xxx_todo_changeme6
raise ModificationException()
def addN(self, quads):
raise ModificationException()
def remove(self, xxx_todo_changeme7):
(s, p, o) = xxx_todo_changeme7
raise ModificationException()
def triples(self, xxx_todo_changeme8):
(s, p, o) = xxx_todo_changeme8
for graph in self.graphs:
if isinstance(p, Path):
for s, o in p.eval(self, s, o):
yield s, p, o
else:
for s1, p1, o1 in graph.triples((s, p, o)):
yield (s1, p1, o1)
def __contains__(self, triple_or_quad):
context = None
if len(triple_or_quad) == 4:
context = triple_or_quad[3]
for graph in self.graphs:
if context is None or graph.identifier == context.identifier:
if triple_or_quad[:3] in graph:
return True
return False
def quads(self, xxx_todo_changeme9):
"""Iterate over all the quads in the entire aggregate graph"""
(s, p, o) = xxx_todo_changeme9
for graph in self.graphs:
for s1, p1, o1 in graph.triples((s, p, o)):
yield (s1, p1, o1, graph)
def __len__(self):
return sum(len(g) for g in self.graphs)
def __hash__(self):
raise UnSupportedAggregateOperation()
def __cmp__(self, other):
if other is None:
return -1
elif isinstance(other, Graph):
return -1
elif isinstance(other, ReadOnlyGraphAggregate):
return cmp(self.graphs, other.graphs)
else:
return -1
def __iadd__(self, other):
raise ModificationException()
def __isub__(self, other):
raise ModificationException()
# Conv. methods
def triples_choices(self, xxx_todo_changeme10, context=None):
(subject, predicate, object_) = xxx_todo_changeme10
for graph in self.graphs:
choices = graph.triples_choices((subject, predicate, object_))
for (s, p, o) in choices:
yield (s, p, o)
def qname(self, uri):
if hasattr(self, 'namespace_manager') and self.namespace_manager:
return self.namespace_manager.qname(uri)
raise UnSupportedAggregateOperation()
def compute_qname(self, uri, generate=True):
if hasattr(self, 'namespace_manager') and self.namespace_manager:
return self.namespace_manager.compute_qname(uri, generate)
raise UnSupportedAggregateOperation()
def bind(self, prefix, namespace, override=True):
raise UnSupportedAggregateOperation()
def namespaces(self):
if hasattr(self, 'namespace_manager'):
for prefix, namespace in self.namespace_manager.namespaces():
yield prefix, namespace
else:
for graph in self.graphs:
for prefix, namespace in graph.namespaces():
yield prefix, namespace
def absolutize(self, uri, defrag=1):
raise UnSupportedAggregateOperation()
def parse(self, source, publicID=None, format="xml", **args):
raise ModificationException()
def n3(self):
raise UnSupportedAggregateOperation()
def __reduce__(self):
raise UnSupportedAggregateOperation()
def _assertnode(*terms):
for t in terms:
assert isinstance(t, Node), \
'Term %s must be an rdflib term' % (t,)
return True
def test():
import doctest
doctest.testmod()
if __name__ == '__main__':
test()
| 34.48798 | 118 | 0.592623 | from rdflib.term import Literal
assert Literal
from rdflib.namespace import Namespace
assert Namespace
from rdflib.py3compat import format_doctest_out
__doc__ = format_doctest_out("""\
RDFLib defines the following kinds of Graphs:
* :class:`~rdflib.graph.Graph`
* :class:`~rdflib.graph.QuotedGraph`
* :class:`~rdflib.graph.ConjunctiveGraph`
* :class:`~rdflib.graph.Dataset`
Graph
-----
An RDF graph is a set of RDF triples. Graphs support the python ``in``
operator, as well as iteration and some operations like union,
difference and intersection.
see :class:`~rdflib.graph.Graph`
Conjunctive Graph
-----------------
A Conjunctive Graph is the most relevant collection of graphs that are
considered to be the boundary for closed world assumptions. This
boundary is equivalent to that of the store instance (which is itself
uniquely identified and distinct from other instances of
:class:`Store` that signify other Conjunctive Graphs). It is
equivalent to all the named graphs within it and associated with a
``_default_`` graph which is automatically assigned a :class:`BNode`
for an identifier - if one isn't given.
see :class:`~rdflib.graph.ConjunctiveGraph`
Quoted graph
------------
The notion of an RDF graph [14] is extended to include the concept of
a formula node. A formula node may occur wherever any other kind of
node can appear. Associated with a formula node is an RDF graph that
is completely disjoint from all other graphs; i.e. has no nodes in
common with any other graph. (It may contain the same labels as other
RDF graphs; because this is, by definition, a separate graph,
considerations of tidiness do not apply between the graph at a formula
node and any other graph.)
This is intended to map the idea of "{ N3-expression }" that is used
by N3 into an RDF graph upon which RDF semantics is defined.
see :class:`~rdflib.graph.QuotedGraph`
Dataset
-------
The RDF 1.1 Dataset, a small extension to the Conjunctive Graph. The
primary term is "graphs in the datasets" and not "contexts with quads"
so there is a separate method to set/retrieve a graph in a dataset and
to operate with dataset graphs. As a consequence of this approach,
dataset graphs cannot be identified with blank nodes, a name is always
required (RDFLib will automatically add a name if one is not provided
at creation time). This implementation includes a convenience method
to directly add a single quad to a dataset graph.
see :class:`~rdflib.graph.Dataset`
Working with graphs
===================
Instantiating Graphs with default store (IOMemory) and default identifier
(a BNode):
>>> g = Graph()
>>> g.store.__class__
<class 'rdflib.plugins.memory.IOMemory'>
>>> g.identifier.__class__
<class 'rdflib.term.BNode'>
Instantiating Graphs with a IOMemory store and an identifier -
<http://rdflib.net>:
>>> g = Graph('IOMemory', URIRef("http://rdflib.net"))
>>> g.identifier
rdflib.term.URIRef(%(u)s'http://rdflib.net')
>>> str(g) # doctest: +NORMALIZE_WHITESPACE
"<http://rdflib.net> a rdfg:Graph;rdflib:storage
[a rdflib:Store;rdfs:label 'IOMemory']."
Creating a ConjunctiveGraph - The top level container for all named Graphs
in a 'database':
>>> g = ConjunctiveGraph()
>>> str(g.default_context)
"[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'IOMemory']]."
Adding / removing reified triples to Graph and iterating over it directly or
via triple pattern:
>>> g = Graph()
>>> statementId = BNode()
>>> print(len(g))
0
>>> g.add((statementId, RDF.type, RDF.Statement))
>>> g.add((statementId, RDF.subject,
... URIRef(%(u)s'http://rdflib.net/store/ConjunctiveGraph')))
>>> g.add((statementId, RDF.predicate, RDFS.label))
>>> g.add((statementId, RDF.object, Literal("Conjunctive Graph")))
>>> print(len(g))
4
>>> for s, p, o in g:
... print(type(s))
...
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
>>> for s, p, o in g.triples((None, RDF.object, None)):
... print(o)
...
Conjunctive Graph
>>> g.remove((statementId, RDF.type, RDF.Statement))
>>> print(len(g))
3
``None`` terms in calls to :meth:`~rdflib.graph.Graph.triples` can be
thought of as "open variables".
Graph support set-theoretic operators, you can add/subtract graphs, as
well as intersection (with multiplication operator g1*g2) and xor (g1
^ g2).
Note that BNode IDs are kept when doing set-theoretic operations, this
may or may not be what you want. Two named graphs within the same
application probably want share BNode IDs, two graphs with data from
different sources probably not. If your BNode IDs are all generated
by RDFLib they are UUIDs and unique.
>>> g1 = Graph()
>>> g2 = Graph()
>>> u = URIRef(%(u)s'http://example.com/foo')
>>> g1.add([u, RDFS.label, Literal('foo')])
>>> g1.add([u, RDFS.label, Literal('bar')])
>>> g2.add([u, RDFS.label, Literal('foo')])
>>> g2.add([u, RDFS.label, Literal('bing')])
>>> len(g1 + g2) # adds bing as label
3
>>> len(g1 - g2) # removes foo
1
>>> len(g1 * g2) # only foo
1
>>> g1 += g2 # now g1 contains everything
Graph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within
the same store:
>>> store = plugin.get('IOMemory', Store)()
>>> g1 = Graph(store)
>>> g2 = Graph(store)
>>> g3 = Graph(store)
>>> stmt1 = BNode()
>>> stmt2 = BNode()
>>> stmt3 = BNode()
>>> g1.add((stmt1, RDF.type, RDF.Statement))
>>> g1.add((stmt1, RDF.subject,
... URIRef(%(u)s'http://rdflib.net/store/ConjunctiveGraph')))
>>> g1.add((stmt1, RDF.predicate, RDFS.label))
>>> g1.add((stmt1, RDF.object, Literal("Conjunctive Graph")))
>>> g2.add((stmt2, RDF.type, RDF.Statement))
>>> g2.add((stmt2, RDF.subject,
... URIRef(%(u)s'http://rdflib.net/store/ConjunctiveGraph')))
>>> g2.add((stmt2, RDF.predicate, RDF.type))
>>> g2.add((stmt2, RDF.object, RDFS.Class))
>>> g3.add((stmt3, RDF.type, RDF.Statement))
>>> g3.add((stmt3, RDF.subject,
... URIRef(%(u)s'http://rdflib.net/store/ConjunctiveGraph')))
>>> g3.add((stmt3, RDF.predicate, RDFS.comment))
>>> g3.add((stmt3, RDF.object, Literal(
... "The top-level aggregate graph - The sum " +
... "of all named graphs within a Store")))
>>> len(list(ConjunctiveGraph(store).subjects(RDF.type, RDF.Statement)))
3
>>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects(
... RDF.type, RDF.Statement)))
2
ConjunctiveGraphs have a :meth:`~rdflib.graph.ConjunctiveGraph.quads` method
which returns quads instead of triples, where the fourth item is the Graph
(or subclass thereof) instance in which the triple was asserted:
>>> uniqueGraphNames = set(
... [graph.identifier for s, p, o, graph in ConjunctiveGraph(store
... ).quads((None, RDF.predicate, None))])
>>> len(uniqueGraphNames)
3
>>> unionGraph = ReadOnlyGraphAggregate([g1, g2])
>>> uniqueGraphNames = set(
... [graph.identifier for s, p, o, graph in unionGraph.quads(
... (None, RDF.predicate, None))])
>>> len(uniqueGraphNames)
2
Parsing N3 from a string
>>> g2 = Graph()
>>> src = '''
... @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
... [ a rdf:Statement ;
... rdf:subject <http://rdflib.net/store#ConjunctiveGraph>;
... rdf:predicate rdfs:label;
... rdf:object "Conjunctive Graph" ] .
... '''
>>> g2 = g2.parse(data=src, format='n3')
>>> print(len(g2))
4
Using Namespace class:
>>> RDFLib = Namespace('http://rdflib.net/')
>>> RDFLib.ConjunctiveGraph
rdflib.term.URIRef(%(u)s'http://rdflib.net/ConjunctiveGraph')
>>> RDFLib['Graph']
rdflib.term.URIRef(%(u)s'http://rdflib.net/Graph')
""")
import logging
logger = logging.getLogger(__name__)
# import md5
import random
import warnings
from hashlib import md5
try:
from io import BytesIO
assert BytesIO
except ImportError:
try:
from io import StringIO as BytesIO
assert BytesIO
except ImportError:
from io import StringIO as BytesIO
assert BytesIO
from rdflib.namespace import RDF, RDFS, SKOS
from rdflib import plugin, exceptions, query
from rdflib.term import Node, URIRef, Genid
from rdflib.term import BNode
import rdflib.term
from rdflib.paths import Path
from rdflib.store import Store
from rdflib.serializer import Serializer
from rdflib.parser import Parser
from rdflib.parser import create_input_source
from rdflib.namespace import NamespaceManager
from rdflib.resource import Resource
from rdflib.collection import Collection
from rdflib import py3compat
b = py3compat.b
import os
import shutil
import tempfile
from urllib.parse import urlparse
__all__ = [
'Graph', 'ConjunctiveGraph', 'QuotedGraph', 'Seq',
'ModificationException', 'Dataset',
'UnSupportedAggregateOperation', 'ReadOnlyGraphAggregate']
class Graph(Node):
def __init__(self, store='default', identifier=None,
namespace_manager=None):
super(Graph, self).__init__()
self.__identifier = identifier or BNode()
if not isinstance(self.__identifier, Node):
self.__identifier = URIRef(self.__identifier)
if not isinstance(store, Store):
# TODO: error handling
self.__store = store = plugin.get(store, Store)()
else:
self.__store = store
self.__namespace_manager = namespace_manager
self.context_aware = False
self.formula_aware = False
self.default_union = False
def __get_store(self):
return self.__store
store = property(__get_store) # read-only attr
def __get_identifier(self):
return self.__identifier
identifier = property(__get_identifier) # read-only attr
def _get_namespace_manager(self):
if self.__namespace_manager is None:
self.__namespace_manager = NamespaceManager(self)
return self.__namespace_manager
def _set_namespace_manager(self, nm):
self.__namespace_manager = nm
namespace_manager = property(_get_namespace_manager,
_set_namespace_manager,
doc="this graph's namespace-manager")
def __repr__(self):
return "<Graph identifier=%s (%s)>" % (self.identifier, type(self))
def __str__(self):
if isinstance(self.identifier, URIRef):
return ("%s a rdfg:Graph;rdflib:storage " +
"[a rdflib:Store;rdfs:label '%s'].") % (
self.identifier.n3(),
self.store.__class__.__name__)
else:
return ("[a rdfg:Graph;rdflib:storage " +
"[a rdflib:Store;rdfs:label '%s']].") % (
self.store.__class__.__name__)
def toPython(self):
return self
def destroy(self, configuration):
self.__store.destroy(configuration)
def commit(self):
self.__store.commit()
def rollback(self):
self.__store.rollback()
def open(self, configuration, create=False):
return self.__store.open(configuration, create)
def close(self, commit_pending_transaction=False):
self.__store.close(
commit_pending_transaction=commit_pending_transaction)
def add(self, xxx_todo_changeme):
(s, p, o) = xxx_todo_changeme
assert isinstance(s, Node), \
"Subject %s must be an rdflib term" % (s,)
assert isinstance(p, Node), \
"Predicate %s must be an rdflib term" % (p,)
assert isinstance(o, Node), \
"Object %s must be an rdflib term" % (o,)
self.__store.add((s, p, o), self, quoted=False)
def addN(self, quads):
self.__store.addN((s, p, o, c) for s, p, o, c in quads
if isinstance(c, Graph)
and c.identifier is self.identifier
and _assertnode(s,p,o)
)
def remove(self, xxx_todo_changeme1):
(s, p, o) = xxx_todo_changeme1
self.__store.remove((s, p, o), context=self)
def triples(self, xxx_todo_changeme2):
(s, p, o) = xxx_todo_changeme2
if isinstance(p, Path):
for _s, _o in p.eval(self, s, o):
yield (_s, p, _o)
else:
for (s, p, o), cg in self.__store.triples((s, p, o), context=self):
yield (s, p, o)
@py3compat.format_doctest_out
def __getitem__(self, item):
if isinstance(item, slice):
s,p,o=item.start,item.stop,item.step
if s is None and p is None and o is None:
return self.triples((s,p,o))
elif s is None and p is None:
return self.subject_predicates(o)
elif s is None and o is None:
return self.subject_objects(p)
elif p is None and o is None:
return self.predicate_objects(s)
elif s is None:
return self.subjects(p,o)
elif p is None:
return self.predicates(s,o)
elif o is None:
return self.objects(s,p)
else:
return (s,p,o) in self
elif isinstance(item, (Path,Node)):
return self.predicate_objects(item)
else:
raise TypeError("You can only index a graph by a single rdflib term or path, or a slice of rdflib terms.")
def __len__(self):
return self.__store.__len__(context=self)
def __iter__(self):
return self.triples((None, None, None))
def __contains__(self, triple):
for triple in self.triples(triple):
return True
return False
def __hash__(self):
return hash(self.identifier)
def md5_term_hash(self):
d = md5(str(self.identifier))
d.update("G")
return d.hexdigest()
def __cmp__(self, other):
if other is None:
return -1
elif isinstance(other, Graph):
return cmp(self.identifier, other.identifier)
else:
return 1
def __eq__(self, other):
return isinstance(other, Graph) \
and self.identifier == other.identifier
def __lt__(self, other):
return (other is None) \
or (isinstance(other, Graph)
and self.identifier < other.identifier)
def __le__(self, other):
return self < other or self == other
def __gt__(self, other):
return (isinstance(other, Graph)
and self.identifier > other.identifier) \
or (other is not None)
def __ge__(self, other):
return self > other or self == other
def __iadd__(self, other):
self.addN((s, p, o, self) for s, p, o in other)
return self
def __isub__(self, other):
for triple in other:
self.remove(triple)
return self
def __add__(self, other):
retval = Graph()
for (prefix, uri) in set(
list(self.namespaces()) + list(other.namespaces())):
retval.bind(prefix, uri)
for x in self:
retval.add(x)
for y in other:
retval.add(y)
return retval
def __mul__(self, other):
retval = Graph()
for x in other:
if x in self:
retval.add(x)
return retval
def __sub__(self, other):
retval = Graph()
for x in self:
if not x in other:
retval.add(x)
return retval
def __xor__(self, other):
return (self - other) + (other - self)
__or__ = __add__
__and__ = __mul__
def set(self, triple):
(subject, predicate, object_) = triple
assert subject is not None, \
"s can't be None in .set([s,p,o]), as it would remove (*, p, *)"
assert predicate is not None, \
"p can't be None in .set([s,p,o]), as it would remove (s, *, *)"
self.remove((subject, predicate, None))
self.add((subject, predicate, object_))
def subjects(self, predicate=None, object=None):
for s, p, o in self.triples((None, predicate, object)):
yield s
def predicates(self, subject=None, object=None):
for s, p, o in self.triples((subject, None, object)):
yield p
def objects(self, subject=None, predicate=None):
for s, p, o in self.triples((subject, predicate, None)):
yield o
def subject_predicates(self, object=None):
for s, p, o in self.triples((None, None, object)):
yield s, p
def subject_objects(self, predicate=None):
for s, p, o in self.triples((None, predicate, None)):
yield s, o
def predicate_objects(self, subject=None):
for s, p, o in self.triples((subject, None, None)):
yield p, o
def triples_choices(self, xxx_todo_changeme3, context=None):
(subject, predicate, object_) = xxx_todo_changeme3
for (s, p, o), cg in self.store.triples_choices(
(subject, predicate, object_), context=self):
yield (s, p, o)
def value(self, subject=None, predicate=RDF.value, object=None,
default=None, any=True):
retval = default
if (subject is None and predicate is None) or \
(subject is None and object is None) or \
(predicate is None and object is None):
return None
if object is None:
values = self.objects(subject, predicate)
if subject is None:
values = self.subjects(predicate, object)
if predicate is None:
values = self.predicates(subject, object)
try:
retval = next(values)
except StopIteration:
retval = default
else:
if any is False:
try:
next(values)
msg = ("While trying to find a value for (%s, %s, %s) the"
" following multiple values where found:\n" %
(subject, predicate, object))
triples = self.store.triples(
(subject, predicate, object), None)
for (s, p, o), contexts in triples:
msg += "(%s, %s, %s)\n (contexts: %s)\n" % (
s, p, o, list(contexts))
raise exceptions.UniquenessError(msg)
except StopIteration:
pass
return retval
def label(self, subject, default=''):
if subject is None:
return default
return self.value(subject, RDFS.label, default=default, any=True)
@py3compat.format_doctest_out
def preferredLabel(self, subject, lang=None, default=None,
labelProperties=(SKOS.prefLabel, RDFS.label)):
if default is None:
default = []
if lang is not None:
if lang == '':
langfilter = lambda l: l.language is None
else:
langfilter = lambda l: l.language == lang
else:
langfilter = lambda l: True
for labelProp in labelProperties:
labels = list(filter(langfilter, self.objects(subject, labelProp)))
if len(labels) == 0:
continue
else:
return [(labelProp, l) for l in labels]
return default
def comment(self, subject, default=''):
if subject is None:
return default
return self.value(subject, RDFS.comment, default=default, any=True)
def items(self, list):
chain = set([list])
while list:
item = self.value(list, RDF.first)
if item is not None:
yield item
list = self.value(list, RDF.rest)
if list in chain:
raise ValueError("List contains a recursive rdf:rest reference")
chain.add(list)
def transitiveClosure(self, func, arg, seen=None):
if seen is None:
seen = {}
elif arg in seen:
return
seen[arg] = 1
for rt in func(arg, self):
yield rt
for rt_2 in self.transitiveClosure(func, rt, seen):
yield rt_2
def transitive_objects(self, subject, property, remember=None):
if remember is None:
remember = {}
if subject in remember:
return
remember[subject] = 1
yield subject
for object in self.objects(subject, property):
for o in self.transitive_objects(object, property, remember):
yield o
def transitive_subjects(self, predicate, object, remember=None):
if remember is None:
remember = {}
if object in remember:
return
remember[object] = 1
yield object
for subject in self.subjects(predicate, object):
for s in self.transitive_subjects(predicate, subject, remember):
yield s
def seq(self, subject):
if (subject, RDF.type, RDF.Seq) in self:
return Seq(self, subject)
else:
return None
def qname(self, uri):
return self.namespace_manager.qname(uri)
def compute_qname(self, uri, generate=True):
return self.namespace_manager.compute_qname(uri, generate)
def bind(self, prefix, namespace, override=True):
return self.namespace_manager.bind(
prefix, namespace, override=override)
def namespaces(self):
for prefix, namespace in self.namespace_manager.namespaces():
yield prefix, namespace
def absolutize(self, uri, defrag=1):
return self.namespace_manager.absolutize(uri, defrag)
def serialize(self, destination=None, format="xml",
base=None, encoding=None, **args):
serializer = plugin.get(format, Serializer)(self)
if destination is None:
stream = BytesIO()
serializer.serialize(stream, base=base, encoding=encoding, **args)
return stream.getvalue()
if hasattr(destination, "write"):
stream = destination
serializer.serialize(stream, base=base, encoding=encoding, **args)
else:
location = destination
scheme, netloc, path, params, _query, fragment = urlparse(location)
if netloc != "":
print(("WARNING: not saving as location" +
"is not a local file reference"))
return
fd, name = tempfile.mkstemp()
stream = os.fdopen(fd, "wb")
serializer.serialize(stream, base=base, encoding=encoding, **args)
stream.close()
if hasattr(shutil, "move"):
shutil.move(name, path)
else:
shutil.copy(name, path)
os.remove(name)
def parse(self, source=None, publicID=None, format=None,
location=None, file=None, data=None, **args):
source = create_input_source(source=source, publicID=publicID,
location=location, file=file,
data=data, format=format)
if format is None:
format = source.content_type
if format is None:
# raise Exception("Could not determine format for %r. You can" + \
# "expicitly specify one with the format argument." % source)
format = "application/rdf+xml"
parser = plugin.get(format, Parser)()
try:
parser.parse(source, self, **args)
finally:
if source.auto_close:
source.close()
return self
def load(self, source, publicID=None, format="xml"):
self.parse(source, publicID, format)
def query(self, query_object, processor='sparql',
result='sparql', initNs=None, initBindings=None,
use_store_provided=True, **kwargs):
initBindings = initBindings or {}
initNs = initNs or dict(self.namespaces())
if hasattr(self.store, "query") and use_store_provided:
try:
return self.store.query(
query_object, initNs, initBindings,
self.default_union
and '__UNION__'
or self.identifier,
**kwargs)
except NotImplementedError:
pass # store has no own implementation
if not isinstance(result, query.Result):
result = plugin.get(result, query.Result)
if not isinstance(processor, query.Processor):
processor = plugin.get(processor, query.Processor)(self)
return result(processor.query(
query_object, initBindings, initNs, **kwargs))
def update(self, update_object, processor='sparql',
initNs=None, initBindings=None,
use_store_provided=True, **kwargs):
initBindings = initBindings or {}
initNs = initNs or dict(self.namespaces())
if hasattr(self.store, "update") and use_store_provided:
try:
return self.store.update(
update_object, initNs, initBindings,
self.default_union
and '__UNION__'
or self.identifier,
**kwargs)
except NotImplementedError:
pass # store has no own implementation
if not isinstance(processor, query.UpdateProcessor):
processor = plugin.get(processor, query.UpdateProcessor)(self)
return processor.update(update_object, initBindings, initNs, **kwargs)
def n3(self):
return "[%s]" % self.identifier.n3()
def __reduce__(self):
return (Graph, (self.store, self.identifier,))
def isomorphic(self, other):
# TODO: this is only an approximation.
if len(self) != len(other):
return False
for s, p, o in self:
if not isinstance(s, BNode) and not isinstance(o, BNode):
if not (s, p, o) in other:
return False
for s, p, o in other:
if not isinstance(s, BNode) and not isinstance(o, BNode):
if not (s, p, o) in self:
return False
# TODO: very well could be a false positive at this point yet.
return True
def connected(self):
all_nodes = list(self.all_nodes())
discovered = []
# take a random one, could also always take the first one, doesn't
if not all_nodes:
return False
visiting = [all_nodes[random.randrange(len(all_nodes))]]
while visiting:
x = visiting.pop()
if x not in discovered:
discovered.append(x)
for new_x in self.objects(subject=x):
if new_x not in discovered and new_x not in visiting:
visiting.append(new_x)
for new_x in self.subjects(object=x):
if new_x not in discovered and new_x not in visiting:
visiting.append(new_x)
if len(all_nodes) == len(discovered):
return True
else:
return False
def all_nodes(self):
res = set(self.objects())
res.update(self.subjects())
return res
def collection(self, identifier):
return Collection(self, identifier)
def resource(self, identifier):
if not isinstance(identifier, Node):
identifier = URIRef(identifier)
return Resource(self, identifier)
def _process_skolem_tuples(self, target, func):
for t in self.triples((None, None, None)):
target.add(func(t))
def skolemize(self, new_graph=None, bnode=None):
def do_skolemize(bnode, t):
(s, p, o) = t
if s == bnode:
s = s.skolemize()
if o == bnode:
o = o.skolemize()
return (s, p, o)
def do_skolemize2(t):
(s, p, o) = t
if isinstance(s, BNode):
s = s.skolemize()
if isinstance(o, BNode):
o = o.skolemize()
return (s, p, o)
retval = Graph() if new_graph is None else new_graph
if bnode is None:
self._process_skolem_tuples(retval, do_skolemize2)
elif isinstance(bnode, BNode):
self._process_skolem_tuples(
retval, lambda t: do_skolemize(bnode, t))
return retval
def de_skolemize(self, new_graph=None, uriref=None):
def do_de_skolemize(uriref, t):
(s, p, o) = t
if s == uriref:
s = s.de_skolemize()
if o == uriref:
o = o.de_skolemize()
return (s, p, o)
def do_de_skolemize2(t):
(s, p, o) = t
if isinstance(s, Genid):
s = s.de_skolemize()
if isinstance(o, Genid):
o = o.de_skolemize()
return (s, p, o)
retval = Graph() if new_graph is None else new_graph
if uriref is None:
self._process_skolem_tuples(retval, do_de_skolemize2)
elif isinstance(uriref, Genid):
self._process_skolem_tuples(
retval, lambda t: do_de_skolemize(uriref, t))
return retval
class ConjunctiveGraph(Graph):
def __init__(self, store='default', identifier=None):
super(ConjunctiveGraph, self).__init__(store, identifier=identifier)
assert self.store.context_aware, ("ConjunctiveGraph must be backed by"
" a context aware store.")
self.context_aware = True
self.default_union = True
self.default_context = Graph(store=self.store,
identifier=identifier or BNode())
def __str__(self):
pattern = ("[a rdflib:ConjunctiveGraph;rdflib:storage "
"[a rdflib:Store;rdfs:label '%s']]")
return pattern % self.store.__class__.__name__
def _spoc(self, triple_or_quad, default=False):
if triple_or_quad is None:
return (None, None, None, self.default_context if default else None)
if len(triple_or_quad) == 3:
c = self.default_context if default else None
(s, p, o) = triple_or_quad
elif len(triple_or_quad) == 4:
(s, p, o, c) = triple_or_quad
c = self._graph(c)
return s,p,o,c
def __contains__(self, triple_or_quad):
s,p,o,c = self._spoc(triple_or_quad)
for t in self.triples((s,p,o), context=c):
return True
return False
def add(self, triple_or_quad):
s,p,o,c = self._spoc(triple_or_quad, default=True)
_assertnode(s,p,o)
self.store.add((s, p, o), context=c, quoted=False)
def _graph(self, c):
if c is None: return None
if not isinstance(c, Graph):
return self.get_context(c)
else:
return c
def addN(self, quads):
self.store.addN(
(s, p, o, self._graph(c)) for s, p, o, c in quads if
_assertnode(s, p, o)
)
def remove(self, triple_or_quad):
s,p,o,c = self._spoc(triple_or_quad)
self.store.remove((s, p, o), context=c)
def triples(self, triple_or_quad, context=None):
s,p,o,c = self._spoc(triple_or_quad)
context = self._graph(context or c)
if self.default_union:
if context==self.default_context:
context = None
else:
if context is None:
context = self.default_context
if isinstance(p, Path):
if context is None:
context = self
for s, o in p.eval(context, s, o):
yield (s, p, o)
else:
for (s, p, o), cg in self.store.triples((s, p, o), context=context):
yield s, p, o
def quads(self, triple_or_quad=None):
s,p,o,c = self._spoc(triple_or_quad)
for (s, p, o), cg in self.store.triples((s, p, o), context=c):
for ctx in cg:
yield s, p, o, ctx
def triples_choices(self, xxx_todo_changeme4, context=None):
(s, p, o) = xxx_todo_changeme4
if context is None:
if not self.default_union:
context=self.default_context
else:
context = self._graph(context)
for (s1, p1, o1), cg in self.store.triples_choices((s, p, o),
context=context):
yield (s1, p1, o1)
def __len__(self):
return self.store.__len__()
def contexts(self, triple=None):
for context in self.store.contexts(triple):
if isinstance(context, Graph):
yield context
else:
yield self.get_context(context)
def get_context(self, identifier, quoted=False):
return Graph(store=self.store, identifier=identifier,
namespace_manager=self)
def remove_context(self, context):
self.store.remove((None, None, None), context)
def context_id(self, uri, context_id=None):
uri = uri.split("#", 1)[0]
if context_id is None:
context_id = "#context"
return URIRef(context_id, base=uri)
def parse(self, source=None, publicID=None, format="xml",
location=None, file=None, data=None, **args):
source = create_input_source(
source=source, publicID=publicID, location=location,
file=file, data=data, format=format)
g_id = publicID and publicID or source.getPublicId()
if not isinstance(g_id, Node):
g_id = URIRef(g_id)
context = Graph(store=self.store, identifier=g_id)
context.remove((None, None, None))
context.parse(source, publicID=publicID, format=format, **args)
return context
def __reduce__(self):
return (ConjunctiveGraph, (self.store, self.identifier))
DATASET_DEFAULT_GRAPH_ID = URIRef('urn:x-rdflib:default')
class Dataset(ConjunctiveGraph):
__doc__ = format_doctest_out("""
RDF 1.1 Dataset. Small extension to the Conjunctive Graph:
- the primary term is graphs in the datasets and not contexts with quads,
so there is a separate method to set/retrieve a graph in a dataset and
operate with graphs
- graphs cannot be identified with blank nodes
- added a method to directly add a single quad
Examples of usage:
>>> # Create a new Dataset
>>> ds = Dataset()
>>> # simple triples goes to default graph
>>> ds.add((URIRef('http://example.org/a'),
... URIRef('http://www.example.org/b'),
... Literal('foo')))
>>>
>>> # Create a graph in the dataset, if the graph name has already been
>>> # used, the corresponding graph will be returned
>>> # (ie, the Dataset keeps track of the constituent graphs)
>>> g = ds.graph(URIRef('http://www.example.com/gr'))
>>>
>>> # add triples to the new graph as usual
>>> g.add(
... (URIRef('http://example.org/x'),
... URIRef('http://example.org/y'),
... Literal('bar')) )
>>> # alternatively: add a quad to the dataset -> goes to the graph
>>> ds.add(
... (URIRef('http://example.org/x'),
... URIRef('http://example.org/z'),
... Literal('foo-bar'),g) )
>>>
>>> # querying triples return them all regardless of the graph
>>> for t in ds.triples((None,None,None)): # doctest: +SKIP
... print(t) # doctest: +NORMALIZE_WHITESPACE
(rdflib.term.URIRef(%(u)s'http://example.org/a'),
rdflib.term.URIRef(%(u)s'http://www.example.org/b'),
rdflib.term.Literal(%(u)s'foo'))
(rdflib.term.URIRef(%(u)s'http://example.org/x'),
rdflib.term.URIRef(%(u)s'http://example.org/z'),
rdflib.term.Literal(%(u)s'foo-bar'))
(rdflib.term.URIRef(%(u)s'http://example.org/x'),
rdflib.term.URIRef(%(u)s'http://example.org/y'),
rdflib.term.Literal(%(u)s'bar'))
>>>
>>> # querying quads return quads; the fourth argument can be unrestricted
>>> # or restricted to a graph
>>> for q in ds.quads((None, None, None, None)): # doctest: +SKIP
... print(q) # doctest: +NORMALIZE_WHITESPACE
(rdflib.term.URIRef(%(u)s'http://example.org/a'),
rdflib.term.URIRef(%(u)s'http://www.example.org/b'),
rdflib.term.Literal(%(u)s'foo'),
None)
(rdflib.term.URIRef(%(u)s'http://example.org/x'),
rdflib.term.URIRef(%(u)s'http://example.org/y'),
rdflib.term.Literal(%(u)s'bar'),
rdflib.term.URIRef(%(u)s'http://www.example.com/gr'))
(rdflib.term.URIRef(%(u)s'http://example.org/x'),
rdflib.term.URIRef(%(u)s'http://example.org/z'),
rdflib.term.Literal(%(u)s'foo-bar'),
rdflib.term.URIRef(%(u)s'http://www.example.com/gr'))
>>>
>>> for q in ds.quads((None,None,None,g)): # doctest: +SKIP
... print(q) # doctest: +NORMALIZE_WHITESPACE
(rdflib.term.URIRef(%(u)s'http://example.org/x'),
rdflib.term.URIRef(%(u)s'http://example.org/y'),
rdflib.term.Literal(%(u)s'bar'),
rdflib.term.URIRef(%(u)s'http://www.example.com/gr'))
(rdflib.term.URIRef(%(u)s'http://example.org/x'),
rdflib.term.URIRef(%(u)s'http://example.org/z'),
rdflib.term.Literal(%(u)s'foo-bar'),
rdflib.term.URIRef(%(u)s'http://www.example.com/gr'))
>>> # Note that in the call above -
>>> # ds.quads((None,None,None,'http://www.example.com/gr'))
>>> # would have been accepted, too
>>>
>>> # graph names in the dataset can be queried:
>>> for c in ds.graphs(): # doctest: +SKIP
... print(c) # doctest:
DEFAULT
http://www.example.com/gr
>>> # A graph can be created without specifying a name; a skolemized genid
>>> # is created on the fly
>>> h = ds.graph()
>>> for c in ds.graphs(): # doctest: +SKIP
... print(c) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
DEFAULT
http://rdlib.net/.well-known/genid/rdflib/N...
http://www.example.com/gr
>>> # Note that the Dataset.graphs() call returns names of empty graphs,
>>> # too. This can be restricted:
>>> for c in ds.graphs(empty=False): # doctest: +SKIP
... print(c) # doctest: +NORMALIZE_WHITESPACE
DEFAULT
http://www.example.com/gr
>>>
>>> # a graph can also be removed from a dataset via ds.remove_graph(g)
.. versionadded:: 4.0
""")
def __init__(self, store='default', default_union=False):
super(Dataset, self).__init__(store=store, identifier=None)
if not self.store.graph_aware:
raise Exception("DataSet must be backed by a graph-aware store!")
self.default_context = Graph(store=self.store, identifier=DATASET_DEFAULT_GRAPH_ID)
self.default_union = default_union
def __str__(self):
pattern = ("[a rdflib:Dataset;rdflib:storage "
"[a rdflib:Store;rdfs:label '%s']]")
return pattern % self.store.__class__.__name__
def graph(self, identifier=None):
if identifier is None:
from rdflib.term import rdflib_skolem_genid
self.bind(
"genid", "http://rdflib.net" + rdflib_skolem_genid,
override=False)
identifier = BNode().skolemize()
g = self._graph(identifier)
self.store.add_graph(g)
return g
def parse(self, source=None, publicID=None, format="xml",
location=None, file=None, data=None, **args):
c = ConjunctiveGraph.parse(self, source, publicID, format, location, file, data, **args)
self.graph(c)
return c
def add_graph(self, g):
return self.graph(g)
def remove_graph(self, g):
if not isinstance(g, Graph):
g = self.get_context(g)
self.store.remove_graph(g)
if g is None or g == self.default_context:
self.store.add_graph(self.default_context)
def contexts(self, triple=None):
default = False
for c in super(Dataset, self).contexts(triple):
default |= c.identifier == DATASET_DEFAULT_GRAPH_ID
yield c
if not default:
yield self.graph(DATASET_DEFAULT_GRAPH_ID)
graphs = contexts
def quads(self, quad):
for s, p, o, c in super(Dataset, self).quads(quad):
if c.identifier==self.default_context:
yield (s, p, o, None)
else:
yield (s, p, o, c.identifier)
class QuotedGraph(Graph):
def __init__(self, store, identifier):
super(QuotedGraph, self).__init__(store, identifier)
def add(self, xxx_todo_changeme5):
(s, p, o) = xxx_todo_changeme5
assert isinstance(s, Node), \
"Subject %s must be an rdflib term" % (s,)
assert isinstance(p, Node), \
"Predicate %s must be an rdflib term" % (p,)
assert isinstance(o, Node), \
"Object %s must be an rdflib term" % (o,)
self.store.add((s, p, o), self, quoted=True)
def addN(self, quads):
self.store.addN(
(s, p, o, c) for s, p, o, c in quads
if isinstance(c, QuotedGraph)
and c.identifier is self.identifier
and _assertnode(s, p, o)
)
def n3(self):
return "{%s}" % self.identifier.n3()
def __str__(self):
identifier = self.identifier.n3()
label = self.store.__class__.__name__
pattern = ("{this rdflib.identifier %s;rdflib:storage "
"[a rdflib:Store;rdfs:label '%s']}")
return pattern % (identifier, label)
def __reduce__(self):
return (QuotedGraph, (self.store, self.identifier))
rdflib.term._ORDERING[QuotedGraph]=11
class Seq(object):
def __init__(self, graph, subject):
_list = self._list = list()
LI_INDEX = URIRef(str(RDF) + "_")
for (p, o) in graph.predicate_objects(subject):
if p.startswith(LI_INDEX): i = int(p.replace(LI_INDEX, ''))
_list.append((i, o))
_list.sort()
def toPython(self):
return self
def __iter__(self):
for _, item in self._list:
yield item
def __len__(self):
return len(self._list)
def __getitem__(self, index):
index, item = self._list.__getitem__(index)
return item
class ModificationException(Exception):
def __init__(self):
pass
def __str__(self):
return ("Modifications and transactional operations not allowed on "
"ReadOnlyGraphAggregate instances")
class UnSupportedAggregateOperation(Exception):
def __init__(self):
pass
def __str__(self):
return ("This operation is not supported by ReadOnlyGraphAggregate "
"instances")
class ReadOnlyGraphAggregate(ConjunctiveGraph):
def __init__(self, graphs, store='default'):
if store is not None:
super(ReadOnlyGraphAggregate, self).__init__(store)
Graph.__init__(self, store)
self.__namespace_manager = None
assert isinstance(graphs, list) \
and graphs \
and [g for g in graphs if isinstance(g, Graph)], \
"graphs argument must be a list of Graphs!!"
self.graphs = graphs
def __repr__(self):
return "<ReadOnlyGraphAggregate: %s graphs>" % len(self.graphs)
def destroy(self, configuration):
raise ModificationException()
def commit(self):
raise ModificationException()
def rollback(self):
raise ModificationException()
def open(self, configuration, create=False):
for graph in self.graphs:
graph.open(self, configuration, create)
def close(self):
for graph in self.graphs:
graph.close()
def add(self, xxx_todo_changeme6):
(s, p, o) = xxx_todo_changeme6
raise ModificationException()
def addN(self, quads):
raise ModificationException()
def remove(self, xxx_todo_changeme7):
(s, p, o) = xxx_todo_changeme7
raise ModificationException()
def triples(self, xxx_todo_changeme8):
(s, p, o) = xxx_todo_changeme8
for graph in self.graphs:
if isinstance(p, Path):
for s, o in p.eval(self, s, o):
yield s, p, o
else:
for s1, p1, o1 in graph.triples((s, p, o)):
yield (s1, p1, o1)
def __contains__(self, triple_or_quad):
context = None
if len(triple_or_quad) == 4:
context = triple_or_quad[3]
for graph in self.graphs:
if context is None or graph.identifier == context.identifier:
if triple_or_quad[:3] in graph:
return True
return False
def quads(self, xxx_todo_changeme9):
(s, p, o) = xxx_todo_changeme9
for graph in self.graphs:
for s1, p1, o1 in graph.triples((s, p, o)):
yield (s1, p1, o1, graph)
def __len__(self):
return sum(len(g) for g in self.graphs)
def __hash__(self):
raise UnSupportedAggregateOperation()
def __cmp__(self, other):
if other is None:
return -1
elif isinstance(other, Graph):
return -1
elif isinstance(other, ReadOnlyGraphAggregate):
return cmp(self.graphs, other.graphs)
else:
return -1
def __iadd__(self, other):
raise ModificationException()
def __isub__(self, other):
raise ModificationException()
def triples_choices(self, xxx_todo_changeme10, context=None):
(subject, predicate, object_) = xxx_todo_changeme10
for graph in self.graphs:
choices = graph.triples_choices((subject, predicate, object_))
for (s, p, o) in choices:
yield (s, p, o)
def qname(self, uri):
if hasattr(self, 'namespace_manager') and self.namespace_manager:
return self.namespace_manager.qname(uri)
raise UnSupportedAggregateOperation()
def compute_qname(self, uri, generate=True):
if hasattr(self, 'namespace_manager') and self.namespace_manager:
return self.namespace_manager.compute_qname(uri, generate)
raise UnSupportedAggregateOperation()
def bind(self, prefix, namespace, override=True):
raise UnSupportedAggregateOperation()
def namespaces(self):
if hasattr(self, 'namespace_manager'):
for prefix, namespace in self.namespace_manager.namespaces():
yield prefix, namespace
else:
for graph in self.graphs:
for prefix, namespace in graph.namespaces():
yield prefix, namespace
def absolutize(self, uri, defrag=1):
raise UnSupportedAggregateOperation()
def parse(self, source, publicID=None, format="xml", **args):
raise ModificationException()
def n3(self):
raise UnSupportedAggregateOperation()
def __reduce__(self):
raise UnSupportedAggregateOperation()
def _assertnode(*terms):
for t in terms:
assert isinstance(t, Node), \
'Term %s must be an rdflib term' % (t,)
return True
def test():
import doctest
doctest.testmod()
if __name__ == '__main__':
test()
| true | true |
f73ba4ba51bfdd01baa8cb1a9af3a424cb7000e1 | 5,836 | py | Python | src/MagnumPlugins/KtxImporter/formatMapping.py | janbajana/magnum-plugins | 809fc1829db8e41d52fd7d299a3bc511b7ba9d83 | [
"MIT"
] | 90 | 2015-05-13T23:57:41.000Z | 2022-03-09T12:16:11.000Z | src/MagnumPlugins/KtxImporter/formatMapping.py | janbajana/magnum-plugins | 809fc1829db8e41d52fd7d299a3bc511b7ba9d83 | [
"MIT"
] | 108 | 2015-08-09T16:30:44.000Z | 2022-02-04T15:56:50.000Z | src/MagnumPlugins/KtxImporter/formatMapping.py | janbajana/magnum-plugins | 809fc1829db8e41d52fd7d299a3bc511b7ba9d83 | [
"MIT"
] | 67 | 2015-05-12T07:36:38.000Z | 2022-03-13T16:41:10.000Z | #!/usr/bin/env python3
#
# This file is part of Magnum.
#
# Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
# 2020, 2021 Vladimír Vondruš <mosra@centrum.cz>
# Copyright © 2021 Pablo Escobar <mail@rvrs.in>
#
# 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
from collections import namedtuple
import itertools
import os
import re
parser = argparse.ArgumentParser()
parser.add_argument('magnum_source')
args = parser.parse_args()
magnum_dir = args.magnum_source
vulkan_header = os.path.join(magnum_dir, 'src/MagnumExternal/Vulkan/flextVk.h')
vulkan_formats = {}
with open(vulkan_header, encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
# Get numeric VkFormat values so we can dereference them directly
# This also finds VK_FORMAT_FEATURE_* but that's no big deal since
# there are no formats that start with FEATURE_
match = re.search('^\s+VK_FORMAT_(\w+) = (\d+),?$', line)
if match:
assert(not match.group(1) in vulkan_formats)
vulkan_formats[match.group(1)] = match.group(2)
Format = namedtuple('Format', 'compressed magnum vulkan_name vulkan suffix')
formats = []
format_header = os.path.join(magnum_dir, 'src/Magnum/Vk/PixelFormat.h')
with open(format_header, encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
# Get mapping from VkFormat to Magnum::Vk::PixelFormat
# PixelFormat and Vk::PixelFormat names are identical
match = re.search('^\s+(Compressed)?(\w+) = VK_FORMAT_(\w+),?$', line)
if match:
compressed = match.group(1) != None
magnum_name = match.group(2)
vulkan_name = match.group(3)
assert(vulkan_name in vulkan_formats)
suffix = re.search('\w+_([U|S](NORM|INT|FLOAT|RGB))\w*', vulkan_name)
assert suffix != None
assert suffix.group(1) != 'URGB'
formats.append(Format(compressed, magnum_name, vulkan_name, vulkan_formats[vulkan_name], suffix.group(1)))
if len(formats) != 135:
print('Unexpected number of formats')
# https://docs.python.org/dev/library/itertools.html#itertools-recipes
def partition(pred, iterable):
t1, t2 = itertools.tee(iterable)
return itertools.filterfalse(pred, t1), filter(pred, t2)
compressed = lambda f : f.compressed
formats, compressed_formats = partition(compressed, formats)
# There's no PVRTC2 in CompressedPixelFormat
compressed_formats = [f for f in compressed_formats if not f.magnum.startswith('Pvrtc2')]
header = '''/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021 Vladimír Vondruš <mosra@centrum.cz>
Copyright © 2021 Pablo Escobar <mail@rvrs.in>
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.
*/
/* Autogenerated from formatMapping.py! Do not edit! */
'''
with open('formatMapping.hpp', 'w', encoding='utf-8') as outfile:
outfile.write(header)
outfile.write('/* VkFormat, PixelFormat, Implementation::VkFormatSuffix */\n')
outfile.write('#ifdef _c\n')
for format in formats:
outfile.write('_c({}, {}, {}) /* VK_FORMAT_{} */\n'.format(format.vulkan , format.magnum, format.suffix, format.vulkan_name))
outfile.write('#endif\n')
with open('compressedFormatMapping.hpp', 'w', encoding='utf-8') as outfile:
outfile.write(header)
outfile.write('/* VkFormat, CompressedPixelFormat, Implementation::VkFormatSuffix */\n')
outfile.write('#ifdef _c\n')
for format in compressed_formats:
outfile.write('_c({}, {}, {}) /* VK_FORMAT_{} */\n'.format(format.vulkan , format.magnum, format.suffix, format.vulkan_name))
outfile.write('#endif\n')
| 42.59854 | 133 | 0.705278 |
import argparse
from collections import namedtuple
import itertools
import os
import re
parser = argparse.ArgumentParser()
parser.add_argument('magnum_source')
args = parser.parse_args()
magnum_dir = args.magnum_source
vulkan_header = os.path.join(magnum_dir, 'src/MagnumExternal/Vulkan/flextVk.h')
vulkan_formats = {}
with open(vulkan_header, encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
# there are no formats that start with FEATURE_
match = re.search('^\s+VK_FORMAT_(\w+) = (\d+),?$', line)
if match:
assert(not match.group(1) in vulkan_formats)
vulkan_formats[match.group(1)] = match.group(2)
Format = namedtuple('Format', 'compressed magnum vulkan_name vulkan suffix')
formats = []
format_header = os.path.join(magnum_dir, 'src/Magnum/Vk/PixelFormat.h')
with open(format_header, encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
# Get mapping from VkFormat to Magnum::Vk::PixelFormat
# PixelFormat and Vk::PixelFormat names are identical
match = re.search('^\s+(Compressed)?(\w+) = VK_FORMAT_(\w+),?$', line)
if match:
compressed = match.group(1) != None
magnum_name = match.group(2)
vulkan_name = match.group(3)
assert(vulkan_name in vulkan_formats)
suffix = re.search('\w+_([U|S](NORM|INT|FLOAT|RGB))\w*', vulkan_name)
assert suffix != None
assert suffix.group(1) != 'URGB'
formats.append(Format(compressed, magnum_name, vulkan_name, vulkan_formats[vulkan_name], suffix.group(1)))
if len(formats) != 135:
print('Unexpected number of formats')
# https://docs.python.org/dev/library/itertools.html#itertools-recipes
def partition(pred, iterable):
t1, t2 = itertools.tee(iterable)
return itertools.filterfalse(pred, t1), filter(pred, t2)
compressed = lambda f : f.compressed
formats, compressed_formats = partition(compressed, formats)
# There's no PVRTC2 in CompressedPixelFormat
compressed_formats = [f for f in compressed_formats if not f.magnum.startswith('Pvrtc2')]
header = '''/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021 Vladimír Vondruš <mosra@centrum.cz>
Copyright © 2021 Pablo Escobar <mail@rvrs.in>
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.
*/
/* Autogenerated from formatMapping.py! Do not edit! */
'''
with open('formatMapping.hpp', 'w', encoding='utf-8') as outfile:
outfile.write(header)
outfile.write('/* VkFormat, PixelFormat, Implementation::VkFormatSuffix */\n')
outfile.write('#ifdef _c\n')
for format in formats:
outfile.write('_c({}, {}, {}) /* VK_FORMAT_{} */\n'.format(format.vulkan , format.magnum, format.suffix, format.vulkan_name))
outfile.write('#endif\n')
with open('compressedFormatMapping.hpp', 'w', encoding='utf-8') as outfile:
outfile.write(header)
outfile.write('/* VkFormat, CompressedPixelFormat, Implementation::VkFormatSuffix */\n')
outfile.write('#ifdef _c\n')
for format in compressed_formats:
outfile.write('_c({}, {}, {}) /* VK_FORMAT_{} */\n'.format(format.vulkan , format.magnum, format.suffix, format.vulkan_name))
outfile.write('#endif\n')
| true | true |
f73ba8c42e38717d499fd2a17864c6aa09928041 | 1,743 | py | Python | GoogleKickstart/kickstart2021/ex1.py | XavierDELPIERRE/Competitiveprogramming | c04a6c81d26c5f44003cfec5768468e183155e65 | [
"Unlicense"
] | null | null | null | GoogleKickstart/kickstart2021/ex1.py | XavierDELPIERRE/Competitiveprogramming | c04a6c81d26c5f44003cfec5768468e183155e65 | [
"Unlicense"
] | null | null | null | GoogleKickstart/kickstart2021/ex1.py | XavierDELPIERRE/Competitiveprogramming | c04a6c81d26c5f44003cfec5768468e183155e65 | [
"Unlicense"
] | null | null | null | # input() reads a string with a line of input, stripping the ' ' (newline) at the end.
# This is all you need for most problems.
import os
os.system('cls')
file = open('shuffled_anagrams_sample_ts1_input.txt', 'r')
#overwrite input to mimic google input
def input():
line = file.readline()
return line
import math
import random
stringimp = 'IMPOSSIBLE'
t = int(input()) # read a line with a single integer
for i in range(1, t + 1):
n = [str(s) for s in input()] # read a list of integers, 2 in this case
if '\n' in n :
n.remove('\n')
a = [0]*26
res = ''
for index in n:
a[ord(index)-ord('a')] = a[ord(index)-ord('a')]+1
if (max(a) > math.floor(len(n)/2)) :
res = stringimp
else:
test = True
while test :
possibilite = set(n)
test = False
for index in n :
possibiliten = set(possibilite)
if index in possibiliten:
possibiliten.remove(index)
if len(possibiliten) == 0 :
test=True
a = [0]*26
res = ''
for index in n:
a[ord(index)-ord('a')] = a[ord(index)-ord('a')]+1
break
else:
remove = random.choice(list(possibiliten))
res += remove
a[ord(remove)-ord('a')] = a[ord(remove)-ord('a')]-1
if a[ord(remove)-ord('a')] == 0:
possibilite.remove(remove)
print("Case #{}: {}".format(i, res))
# check out .format's specification for more formatting options | 32.886792 | 87 | 0.481354 |
import os
os.system('cls')
file = open('shuffled_anagrams_sample_ts1_input.txt', 'r')
def input():
line = file.readline()
return line
import math
import random
stringimp = 'IMPOSSIBLE'
t = int(input())
for i in range(1, t + 1):
n = [str(s) for s in input()]
if '\n' in n :
n.remove('\n')
a = [0]*26
res = ''
for index in n:
a[ord(index)-ord('a')] = a[ord(index)-ord('a')]+1
if (max(a) > math.floor(len(n)/2)) :
res = stringimp
else:
test = True
while test :
possibilite = set(n)
test = False
for index in n :
possibiliten = set(possibilite)
if index in possibiliten:
possibiliten.remove(index)
if len(possibiliten) == 0 :
test=True
a = [0]*26
res = ''
for index in n:
a[ord(index)-ord('a')] = a[ord(index)-ord('a')]+1
break
else:
remove = random.choice(list(possibiliten))
res += remove
a[ord(remove)-ord('a')] = a[ord(remove)-ord('a')]-1
if a[ord(remove)-ord('a')] == 0:
possibilite.remove(remove)
print("Case #{}: {}".format(i, res))
| true | true |
f73ba8e9807ecd80a25b4141cf6f374c31a144ae | 4,369 | py | Python | tensorflow/python/kernel_tests/py_func_test.py | jylinman/tensorflow | 5248d111c3aeaf9f560cd77bff0f183f38e31e0b | [
"Apache-2.0"
] | 1 | 2016-02-25T06:47:21.000Z | 2016-02-25T06:47:21.000Z | tensorflow/python/kernel_tests/py_func_test.py | jylinman/tensorflow | 5248d111c3aeaf9f560cd77bff0f183f38e31e0b | [
"Apache-2.0"
] | null | null | null | tensorflow/python/kernel_tests/py_func_test.py | jylinman/tensorflow | 5248d111c3aeaf9f560cd77bff0f183f38e31e0b | [
"Apache-2.0"
] | 1 | 2020-10-21T09:39:19.000Z | 2020-10-21T09:39:19.000Z | # Copyright 2015 Google 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.
# ==============================================================================
"""Tests for py_func op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.python.framework import errors
from tensorflow.python.ops import script_ops
class PyOpTest(tf.test.TestCase):
def testBasic(self):
def my_func(x, y):
return np.sinh(x) + np.cosh(y)
# scalar
with self.test_session():
x = tf.constant(1.0, tf.float32)
y = tf.constant(2.0, tf.float32)
z = tf.py_func(my_func, [x, y], [tf.float32])
self.assertEqual(z[0].eval(), my_func(1.0, 2.0).astype(np.float32))
# array
with self.test_session():
x = tf.constant([1.0, 2.0], tf.float64)
y = tf.constant([2.0, 3.0], tf.float64)
z = tf.py_func(my_func, [x, y], [tf.float64])
self.assertAllEqual(
z[0].eval(),
my_func([1.0, 2.0], [2.0, 3.0]).astype(np.float64))
# a bit exotic type (complex64)
with self.test_session():
x = tf.constant(1+2j, tf.complex64)
y = tf.constant(3+4j, tf.complex64)
z, = tf.py_func(my_func, [x, y], [tf.complex64])
self.assertAllClose(z.eval(), my_func(1+2j, 3+4j))
# a bit excotic function (rfft)
with self.test_session():
x = tf.constant([1., 2., 3., 4.], tf.float32)
def rfft(x):
return np.fft.rfft(x).astype(np.complex64)
y, = tf.py_func(rfft, [x], [tf.complex64])
self.assertAllClose(y.eval(), np.fft.rfft([1., 2., 3., 4.]))
# returns a python literal.
with self.test_session():
def literal(x):
return 1.0 if x == 0.0 else 0.0
x = tf.constant(0.0, tf.float64)
y, = tf.py_func(literal, [x], [tf.float64])
self.assertAllClose(y.eval(), 1.0)
def testStrings(self):
def read_fixed_length_numpy_strings():
return np.array([b" there"])
def read_and_return_strings(x, y):
return x + y
with self.test_session():
x = tf.constant([b"hello", b"hi"], tf.string)
y, = tf.py_func(read_fixed_length_numpy_strings, [], [tf.string])
z, = tf.py_func(read_and_return_strings, [x, y], [tf.string])
self.assertListEqual(list(z.eval()), [b"hello there", b"hi there"])
def testLarge(self):
with self.test_session() as sess:
x = tf.zeros([1000000], dtype=np.float32)
y = tf.py_func(lambda x: x + 1, [x], [tf.float32])
z = tf.py_func(lambda x: x * 2, [x], [tf.float32])
for _ in xrange(100):
sess.run([y[0].op, z[0].op])
def testNoInput(self):
with self.test_session():
x, = tf.py_func(lambda: 42.0, [], [tf.float64])
self.assertAllClose(x.eval(), 42.0)
def testCleanup(self):
for _ in xrange(1000):
g = tf.Graph()
with g.as_default():
c = tf.constant([1.], tf.float32)
_ = tf.py_func(lambda x: x + 1, [c], [tf.float32])
self.assertTrue(script_ops._py_funcs.size() < 100)
def testError(self):
with self.test_session():
def bad1():
# Structured numpy arrays aren't supported.
return np.array([], dtype=[("foo", np.float32)])
def bad2():
# Non-string python objects aren't supported.
return tf.float32
y, = tf.py_func(bad1, [], [tf.string])
z, = tf.py_func(bad2, [], [tf.float64])
with self.assertRaisesRegexp(errors.UnimplementedError,
"Unsupported numpy type"):
y.eval()
with self.assertRaisesRegexp(errors.UnimplementedError,
"Unsupported object type"):
z.eval()
if __name__ == "__main__":
tf.test.main()
| 33.098485 | 80 | 0.610666 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from six.moves import xrange
import tensorflow as tf
from tensorflow.python.framework import errors
from tensorflow.python.ops import script_ops
class PyOpTest(tf.test.TestCase):
def testBasic(self):
def my_func(x, y):
return np.sinh(x) + np.cosh(y)
with self.test_session():
x = tf.constant(1.0, tf.float32)
y = tf.constant(2.0, tf.float32)
z = tf.py_func(my_func, [x, y], [tf.float32])
self.assertEqual(z[0].eval(), my_func(1.0, 2.0).astype(np.float32))
with self.test_session():
x = tf.constant([1.0, 2.0], tf.float64)
y = tf.constant([2.0, 3.0], tf.float64)
z = tf.py_func(my_func, [x, y], [tf.float64])
self.assertAllEqual(
z[0].eval(),
my_func([1.0, 2.0], [2.0, 3.0]).astype(np.float64))
with self.test_session():
x = tf.constant(1+2j, tf.complex64)
y = tf.constant(3+4j, tf.complex64)
z, = tf.py_func(my_func, [x, y], [tf.complex64])
self.assertAllClose(z.eval(), my_func(1+2j, 3+4j))
with self.test_session():
x = tf.constant([1., 2., 3., 4.], tf.float32)
def rfft(x):
return np.fft.rfft(x).astype(np.complex64)
y, = tf.py_func(rfft, [x], [tf.complex64])
self.assertAllClose(y.eval(), np.fft.rfft([1., 2., 3., 4.]))
with self.test_session():
def literal(x):
return 1.0 if x == 0.0 else 0.0
x = tf.constant(0.0, tf.float64)
y, = tf.py_func(literal, [x], [tf.float64])
self.assertAllClose(y.eval(), 1.0)
def testStrings(self):
def read_fixed_length_numpy_strings():
return np.array([b" there"])
def read_and_return_strings(x, y):
return x + y
with self.test_session():
x = tf.constant([b"hello", b"hi"], tf.string)
y, = tf.py_func(read_fixed_length_numpy_strings, [], [tf.string])
z, = tf.py_func(read_and_return_strings, [x, y], [tf.string])
self.assertListEqual(list(z.eval()), [b"hello there", b"hi there"])
def testLarge(self):
with self.test_session() as sess:
x = tf.zeros([1000000], dtype=np.float32)
y = tf.py_func(lambda x: x + 1, [x], [tf.float32])
z = tf.py_func(lambda x: x * 2, [x], [tf.float32])
for _ in xrange(100):
sess.run([y[0].op, z[0].op])
def testNoInput(self):
with self.test_session():
x, = tf.py_func(lambda: 42.0, [], [tf.float64])
self.assertAllClose(x.eval(), 42.0)
def testCleanup(self):
for _ in xrange(1000):
g = tf.Graph()
with g.as_default():
c = tf.constant([1.], tf.float32)
_ = tf.py_func(lambda x: x + 1, [c], [tf.float32])
self.assertTrue(script_ops._py_funcs.size() < 100)
def testError(self):
with self.test_session():
def bad1():
return np.array([], dtype=[("foo", np.float32)])
def bad2():
# Non-string python objects aren't supported.
return tf.float32
y, = tf.py_func(bad1, [], [tf.string])
z, = tf.py_func(bad2, [], [tf.float64])
with self.assertRaisesRegexp(errors.UnimplementedError,
"Unsupported numpy type"):
y.eval()
with self.assertRaisesRegexp(errors.UnimplementedError,
"Unsupported object type"):
z.eval()
if __name__ == "__main__":
tf.test.main()
| true | true |
f73ba9e2451db3fc795a845770ccf32819862881 | 6,707 | py | Python | mhr_api/src/mhr_api/services/payment/payment.py | cameron-freshworks/ppr | 01d6f5d300c791aebad5e58bb4601e9be2ccfc46 | [
"Apache-2.0"
] | null | null | null | mhr_api/src/mhr_api/services/payment/payment.py | cameron-freshworks/ppr | 01d6f5d300c791aebad5e58bb4601e9be2ccfc46 | [
"Apache-2.0"
] | null | null | null | mhr_api/src/mhr_api/services/payment/payment.py | cameron-freshworks/ppr | 01d6f5d300c791aebad5e58bb4601e9be2ccfc46 | [
"Apache-2.0"
] | null | null | null | # Copyright © 2021 Province of British Columbia
#
# 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.
"""This module exposes all pay-api operations used by the PPR api."""
from flask import current_app
from .client import ApiRequestError, SBCPaymentClient
from .exceptions import SBCPaymentException
class Payment:
"""Interface for the pay-api service."""
def __init__(self, jwt=None, account_id=None, api_key=None, details=None):
"""Initialize, set api url from env variable."""
self.api_url = None
self.jwt = jwt
self.account_id = account_id
self.api_key = api_key
self.details = details
def create_payment( # pylint: disable=too-many-arguments
self,
transaction_type,
quantity,
transaction_id=None,
client_reference_id=None,
processing_fee=None
):
"""Submit a payment request for the account_id-jwt pair.
Quantity is by default is 1.
Transaction type is one of the Payment TransactionTypes.
Transaction ID is the mhr GUID reference for the payment transaction: either the
registration_id or the search_id if available.
Client reference ID if present maps to the pay api folio number.
Details label and value if they exist will show up on the account transaction report.
"""
try:
api_instance = SBCPaymentClient(self.jwt,
self.account_id,
self.api_key,
self.details)
if self.api_url:
api_instance.api_url = self.api_url
api_response = api_instance.create_payment(transaction_type,
quantity,
transaction_id,
client_reference_id,
processing_fee)
current_app.logger.debug(api_response)
return api_response
except ApiRequestError as api_err:
raise SBCPaymentException(api_err, json_data=api_err.json_data)
except Exception as err: # noqa: B902; wrapping exception
raise SBCPaymentException(err)
def cancel_payment(self, invoice_id):
"""Submit a request to cancel a payment using the invoice ID from the create_payment response.
Cancel_payment should only be called if a post payment database commit fails.
"""
try:
api_instance = SBCPaymentClient(self.jwt, self.account_id, self.api_key)
if self.api_url:
api_instance.api_url = self.api_url
api_response = api_instance.cancel_payment(invoice_id)
return api_response
except Exception as err: # noqa: B902; wrapping exception
raise SBCPaymentException(err)
def create_payment_search(self, selections, transaction_id=None, client_reference_id=None, staff_gov=False):
"""Submit a non-staff search payment request for the account_id-jwt pair.
Quantity is by default is 1, but increments with each selected search match.
Payment filing type(s) and quantity are dynamically derived based on the search selection.
Possible combinations are search MHR only, search MHR and PPR only, or both.
Selections is an array of selected search matches.
Transaction ID is the mhr GUID reference for the payment transaction: either the
registration_id or the search_id if available.
Client reference ID if present maps to the pay api folio number.
Staff_gov is the government staff flag (different filing type).
Details label and value if they exist will show up on the account transaction report.
"""
try:
api_instance = SBCPaymentClient(self.jwt,
self.account_id,
self.api_key,
self.details)
if self.api_url:
api_instance.api_url = self.api_url
api_response = api_instance.create_payment_search(selections,
transaction_id,
client_reference_id,
staff_gov)
current_app.logger.debug(api_response)
return api_response
except ApiRequestError as api_err:
raise SBCPaymentException(api_err, json_data=api_err.json_data)
except Exception as err: # noqa: B902; wrapping exception
raise SBCPaymentException(err)
def create_payment_staff_search(self, selections, transaction_info, transaction_id=None, client_reference_id=None):
"""Submit a staff payment request for the transaction_info. Token must have a staff role.
Payment info transaction type is one of the Payment TransactionTypes.
Client reference ID if present maps to the pay api folio number.
Details label and value if they exist will show up on the account transaction report.
"""
try:
api_instance = SBCPaymentClient(self.jwt,
self.account_id,
self.api_key,
self.details)
if self.api_url:
api_instance.api_url = self.api_url
api_response = api_instance.create_payment_staff_search(selections,
transaction_info,
transaction_id,
client_reference_id)
current_app.logger.debug(api_response)
return api_response
except Exception as err: # noqa: B902; wrapping exception
raise SBCPaymentException(err)
| 47.907143 | 119 | 0.590726 |
from flask import current_app
from .client import ApiRequestError, SBCPaymentClient
from .exceptions import SBCPaymentException
class Payment:
def __init__(self, jwt=None, account_id=None, api_key=None, details=None):
self.api_url = None
self.jwt = jwt
self.account_id = account_id
self.api_key = api_key
self.details = details
def create_payment(
self,
transaction_type,
quantity,
transaction_id=None,
client_reference_id=None,
processing_fee=None
):
try:
api_instance = SBCPaymentClient(self.jwt,
self.account_id,
self.api_key,
self.details)
if self.api_url:
api_instance.api_url = self.api_url
api_response = api_instance.create_payment(transaction_type,
quantity,
transaction_id,
client_reference_id,
processing_fee)
current_app.logger.debug(api_response)
return api_response
except ApiRequestError as api_err:
raise SBCPaymentException(api_err, json_data=api_err.json_data)
except Exception as err:
raise SBCPaymentException(err)
def cancel_payment(self, invoice_id):
try:
api_instance = SBCPaymentClient(self.jwt, self.account_id, self.api_key)
if self.api_url:
api_instance.api_url = self.api_url
api_response = api_instance.cancel_payment(invoice_id)
return api_response
except Exception as err:
raise SBCPaymentException(err)
def create_payment_search(self, selections, transaction_id=None, client_reference_id=None, staff_gov=False):
try:
api_instance = SBCPaymentClient(self.jwt,
self.account_id,
self.api_key,
self.details)
if self.api_url:
api_instance.api_url = self.api_url
api_response = api_instance.create_payment_search(selections,
transaction_id,
client_reference_id,
staff_gov)
current_app.logger.debug(api_response)
return api_response
except ApiRequestError as api_err:
raise SBCPaymentException(api_err, json_data=api_err.json_data)
except Exception as err:
raise SBCPaymentException(err)
def create_payment_staff_search(self, selections, transaction_info, transaction_id=None, client_reference_id=None):
try:
api_instance = SBCPaymentClient(self.jwt,
self.account_id,
self.api_key,
self.details)
if self.api_url:
api_instance.api_url = self.api_url
api_response = api_instance.create_payment_staff_search(selections,
transaction_info,
transaction_id,
client_reference_id)
current_app.logger.debug(api_response)
return api_response
except Exception as err:
raise SBCPaymentException(err)
| true | true |
f73ba9fd2b2b6d4288c30f167c9eaab179bde683 | 2,746 | py | Python | tests/validator12/validate_spec_test.py | stevesimmons/swagger_spec_validator | 219dd57fb4480d789b3ad381f69c1e9e03f926b7 | [
"Apache-2.0"
] | null | null | null | tests/validator12/validate_spec_test.py | stevesimmons/swagger_spec_validator | 219dd57fb4480d789b3ad381f69c1e9e03f926b7 | [
"Apache-2.0"
] | null | null | null | tests/validator12/validate_spec_test.py | stevesimmons/swagger_spec_validator | 219dd57fb4480d789b3ad381f69c1e9e03f926b7 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import mock
import pytest
from .validate_spec_url_test import make_mock_responses
from .validate_spec_url_test import read_contents
from swagger_spec_validator.common import get_uri_from_file_path
from swagger_spec_validator.common import SwaggerValidationError
from swagger_spec_validator.validator12 import validate_data_type
from swagger_spec_validator.validator12 import validate_model
from swagger_spec_validator.validator12 import validate_parameter
from swagger_spec_validator.validator12 import validate_spec
RESOURCE_LISTING_FILE = os.path.abspath('tests/data/v1.2/foo/swagger_api.json')
API_DECLARATION_FILE = os.path.abspath('tests/data/v1.2/foo/foo.json')
def get_resource_listing():
return read_contents(RESOURCE_LISTING_FILE)
def test_http_success():
mock_responses = make_mock_responses([API_DECLARATION_FILE])
with mock.patch(
'swagger_spec_validator.validator12.read_url',
side_effect=mock_responses
) as mock_read_url:
validate_spec(get_resource_listing(), 'http://localhost/api-docs')
mock_read_url.assert_called_once_with('http://localhost/api-docs/foo')
def test_file_uri_success():
mock_string = 'swagger_spec_validator.validator12.validate_api_declaration'
with mock.patch(mock_string) as mock_api:
validate_spec(
get_resource_listing(),
get_uri_from_file_path(RESOURCE_LISTING_FILE),
)
expected = read_contents(API_DECLARATION_FILE)
mock_api.assert_called_once_with(expected)
def test_validate_parameter_type_file_in_form():
parameter = {
'paramType': 'form',
'name': 'what',
'type': 'File',
}
# lack of errors is success
validate_parameter(parameter, [])
def test_validate_parameter_type_file_in_body():
parameter = {
'paramType': 'body',
'name': 'what',
'type': 'File',
}
with pytest.raises(SwaggerValidationError, match='Type "File" is only valid for form parameters'):
validate_parameter(parameter, [])
def test_validate_data_type_is_model():
model_id = 'MyModelId'
model_ids = [model_id, 'OtherModelId']
obj = {'type': model_id}
# lack of error is success
validate_data_type(obj, model_ids, allow_refs=False)
def test_validate_model_matches_id():
model = {"id": "mysupermodel"}
model_name = "mymodel"
model_ids = ""
with pytest.raises(SwaggerValidationError, match='model name: mymodel does not match model id: mysupermodel'):
validate_model(model, model_name, model_ids)
| 31.204545 | 114 | 0.747269 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import mock
import pytest
from .validate_spec_url_test import make_mock_responses
from .validate_spec_url_test import read_contents
from swagger_spec_validator.common import get_uri_from_file_path
from swagger_spec_validator.common import SwaggerValidationError
from swagger_spec_validator.validator12 import validate_data_type
from swagger_spec_validator.validator12 import validate_model
from swagger_spec_validator.validator12 import validate_parameter
from swagger_spec_validator.validator12 import validate_spec
RESOURCE_LISTING_FILE = os.path.abspath('tests/data/v1.2/foo/swagger_api.json')
API_DECLARATION_FILE = os.path.abspath('tests/data/v1.2/foo/foo.json')
def get_resource_listing():
return read_contents(RESOURCE_LISTING_FILE)
def test_http_success():
mock_responses = make_mock_responses([API_DECLARATION_FILE])
with mock.patch(
'swagger_spec_validator.validator12.read_url',
side_effect=mock_responses
) as mock_read_url:
validate_spec(get_resource_listing(), 'http://localhost/api-docs')
mock_read_url.assert_called_once_with('http://localhost/api-docs/foo')
def test_file_uri_success():
mock_string = 'swagger_spec_validator.validator12.validate_api_declaration'
with mock.patch(mock_string) as mock_api:
validate_spec(
get_resource_listing(),
get_uri_from_file_path(RESOURCE_LISTING_FILE),
)
expected = read_contents(API_DECLARATION_FILE)
mock_api.assert_called_once_with(expected)
def test_validate_parameter_type_file_in_form():
parameter = {
'paramType': 'form',
'name': 'what',
'type': 'File',
}
validate_parameter(parameter, [])
def test_validate_parameter_type_file_in_body():
parameter = {
'paramType': 'body',
'name': 'what',
'type': 'File',
}
with pytest.raises(SwaggerValidationError, match='Type "File" is only valid for form parameters'):
validate_parameter(parameter, [])
def test_validate_data_type_is_model():
model_id = 'MyModelId'
model_ids = [model_id, 'OtherModelId']
obj = {'type': model_id}
validate_data_type(obj, model_ids, allow_refs=False)
def test_validate_model_matches_id():
model = {"id": "mysupermodel"}
model_name = "mymodel"
model_ids = ""
with pytest.raises(SwaggerValidationError, match='model name: mymodel does not match model id: mysupermodel'):
validate_model(model, model_name, model_ids)
| true | true |
f73baa04cb819f5f2be842f3c1db945ca2386b7b | 8,262 | py | Python | pollution_A_data_maker.py | cat-astrophic/pollution_growth | 3f245a8dd957bce5aebec41a8b984f0d7aab036d | [
"MIT"
] | null | null | null | pollution_A_data_maker.py | cat-astrophic/pollution_growth | 3f245a8dd957bce5aebec41a8b984f0d7aab036d | [
"MIT"
] | null | null | null | pollution_A_data_maker.py | cat-astrophic/pollution_growth | 3f245a8dd957bce5aebec41a8b984f0d7aab036d | [
"MIT"
] | null | null | null | # This script creates the competition intensity values for the weighted total trade networks
# Importing required modules
import numpy as np
import pandas as pd
# Reading in the data
main_data = pd.read_csv('C:/Users/User/Documents/Data/Pollution/pollution_data.csv')
# Creating a list of all nations
nations = sorted(main_data.Country.unique().tolist())
# Initializing some dataframes
CO2_df = pd.DataFrame()
CH4_df = pd.DataFrame()
NOX_df = pd.DataFrame()
GHG_df = pd.DataFrame()
# Defining two helper functions for subsetting nations to only those with viable data
# This fucntion restricts nations to those with trade network data
def emissions_lists(xxx_nations, ccc_nations, nations):
for c in nations:
if c not in ccc_nations: # this will be comp_nations in our case
xxx_nations.remove(c)
return xxx_nations
# This function further restricts nations to those with intensity data
def extant_intensity(ydat, listy, emission):
listy2 = [l for l in listy]
for n in listy2:
if (ydat[emission][ydat.Country.tolist().index(n)] > 0) == False:
listy.remove(n)
return listy
# A list of years to iterate through
yrs = [i for i in range(1970,2015)]
# The main loop
for y in yrs:
# Cute message
print('Creating data for year ' + str(y) + '.......')
# Refresh lists of nations to pare down
comp_nations = sorted(main_data.Country.unique().tolist())
co2_nations = sorted(main_data.Country.unique().tolist())
ch4_nations = sorted(main_data.Country.unique().tolist())
nox_nations = sorted(main_data.Country.unique().tolist())
ghg_nations = sorted(main_data.Country.unique().tolist())
# Load W matrix for year y
A_co2 = pd.read_csv('C:/Users/User/Documents/Data/Pollution/Networks/A_' + str(y) + '.csv')
A_ch4 = pd.read_csv('C:/Users/User/Documents/Data/Pollution/Networks/A_' + str(y) + '.csv')
A_nox = pd.read_csv('C:/Users/User/Documents/Data/Pollution/Networks/A_' + str(y) + '.csv')
A_ghg = pd.read_csv('C:/Users/User/Documents/Data/Pollution/Networks/A_' + str(y) + '.csv')
# Determining which countries have all data for current year
# Subset to current year
ydata = main_data[main_data['Year'] == y].reset_index().drop('index', axis = 1)
# Check that each country engaged in competitive behavior
for n in nations:
if (n in A_co2.columns.tolist()) == False:
comp_nations.remove(n)
elif sum(A_co2[n]) == 0:
comp_nations.remove(n)
# Creating a beginning for emissions lists
co2_nations = emissions_lists(co2_nations, comp_nations, nations)
ch4_nations = emissions_lists(ch4_nations, comp_nations, nations)
nox_nations = emissions_lists(nox_nations, comp_nations, nations)
ghg_nations = emissions_lists(ghg_nations, comp_nations, nations)
# Further paring down emissions lists based on the existence of intensities data
co2_nations = extant_intensity(ydata, co2_nations, 'co2_intensity')
ch4_nations = extant_intensity(ydata, ch4_nations, 'ch4_intensity')
nox_nations = extant_intensity(ydata, nox_nations, 'nox_intensity')
ghg_nations = extant_intensity(ydata, ghg_nations, 'ghg_intensity')
# Remove extra rows and columns from TC - for each intensity
co2_indices = A_co2.columns.tolist()
ch4_indices = A_ch4.columns.tolist()
nox_indices = A_nox.columns.tolist()
ghg_indices = A_ghg.columns.tolist()
co2_indices.reverse()
ch4_indices.reverse()
nox_indices.reverse()
ghg_indices.reverse()
for col in co2_indices:
if col not in co2_nations:
A_co2 = A_co2.drop(A_co2.columns.tolist().index(col), axis = 0)
A_co2 = A_co2.drop(col, axis = 1)
for col in ch4_indices:
if col not in ch4_nations:
A_ch4 = A_ch4.drop(A_ch4.columns.tolist().index(col), axis = 0)
A_ch4 = A_ch4.drop(col, axis = 1)
for col in nox_indices:
if col not in nox_nations:
A_nox = A_nox.drop(A_nox.columns.tolist().index(col), axis = 0)
A_nox = A_nox.drop(col, axis = 1)
for col in ghg_indices:
if col not in ghg_nations:
A_ghg = A_ghg.drop(A_ghg.columns.tolist().index(col), axis = 0)
A_ghg = A_ghg.drop(col, axis = 1)
# Normalize TC - for each intensity
# This creates a row normalized matrix -- normalized exports!
co2_sums = [sum(A_co2.iloc[row]) for row in range(len(A_co2))]
ch4_sums = [sum(A_ch4.iloc[row]) for row in range(len(A_ch4))]
nox_sums = [sum(A_nox.iloc[row]) for row in range(len(A_nox))]
ghg_sums = [sum(A_ghg.iloc[row]) for row in range(len(A_ghg))]
M_co2 = np.matrix(A_co2)
M_ch4 = np.matrix(A_ch4)
M_nox = np.matrix(A_nox)
M_ghg = np.matrix(A_ghg)
for row in range(len(co2_sums)):
M_co2[row,:] = M_co2[row,:] / co2_sums[row]
for row in range(len(ch4_sums)):
M_ch4[row,:] = M_ch4[row,:] / ch4_sums[row]
for row in range(len(nox_sums)):
M_nox[row,:] = M_nox[row,:] / nox_sums[row]
for row in range(len(ghg_sums)):
M_ghg[row,:] = M_ghg[row,:] / ghg_sums[row]
# Create vector of actual emissions intensities
co2_ints = np.matrix([ydata.co2_intensity[ydata.Country.tolist().index(n)] for n in co2_nations]).T
ch4_ints = np.matrix([ydata.ch4_intensity[ydata.Country.tolist().index(n)] for n in ch4_nations]).T
nox_ints = np.matrix([ydata.nox_intensity[ydata.Country.tolist().index(n)] for n in nox_nations]).T
ghg_ints = np.matrix([ydata.ghg_intensity[ydata.Country.tolist().index(n)] for n in ghg_nations]).T
# Multpliy matrix X vector - for each intensity
co2_data = np.matmul(M_co2,co2_ints)
ch4_data = np.matmul(M_ch4,ch4_ints)
nox_data = np.matmul(M_nox,nox_ints)
ghg_data = np.matmul(M_ghg,ghg_ints)
# Append to DataFrame
current_year = [y for c in co2_nations]
next_year = [y+1 for c in co2_nations]
co2_d = [x[0] for x in co2_data.tolist()]
temp_co2 = pd.DataFrame({'Current Year':current_year, 'Next Year':next_year,
'Nation':co2_nations, 'CO2 Data':co2_d})
CO2_df = pd.concat([CO2_df, temp_co2], axis = 0)
current_year = [y for c in ch4_nations]
next_year = [y+1 for c in ch4_nations]
ch4_d = [x[0] for x in ch4_data.tolist()]
temp_ch4 = pd.DataFrame({'Current Year':current_year, 'Next Year':next_year,
'Nation':ch4_nations, 'CH4 Data':ch4_d})
CH4_df = pd.concat([CH4_df, temp_ch4], axis = 0)
current_year = [y for c in nox_nations]
next_year = [y+1 for c in nox_nations]
nox_d = [x[0] for x in nox_data.tolist()]
temp_nox = pd.DataFrame({'Current Year':current_year, 'Next Year':next_year,
'Nation':nox_nations, 'NOX Data':nox_d})
NOX_df = pd.concat([NOX_df, temp_nox], axis = 0)
current_year = [y for c in ghg_nations]
next_year = [y+1 for c in ghg_nations]
ghg_d = [x[0] for x in ghg_data.tolist()]
temp_ghg = pd.DataFrame({'Current Year':current_year, 'Next Year':next_year,
'Nation':ghg_nations, 'GHG Data':ghg_d})
GHG_df = pd.concat([GHG_df, temp_ghg], axis = 0)
# Write dataframe to file
CO2_df.to_csv('C:/Users/User/Documents/Data/Pollution/A_DATA_CO2.csv', index = False)
CH4_df.to_csv('C:/Users/User/Documents/Data/Pollution/A_DATA_CH4.csv', index = False)
NOX_df.to_csv('C:/Users/User/Documents/Data/Pollution/A_DATA_NOX.csv', index = False)
GHG_df.to_csv('C:/Users/User/Documents/Data/Pollution/A_DATA_GHG.csv', index = False)
| 35.766234 | 104 | 0.618494 |
import numpy as np
import pandas as pd
main_data = pd.read_csv('C:/Users/User/Documents/Data/Pollution/pollution_data.csv')
nations = sorted(main_data.Country.unique().tolist())
CO2_df = pd.DataFrame()
CH4_df = pd.DataFrame()
NOX_df = pd.DataFrame()
GHG_df = pd.DataFrame()
def emissions_lists(xxx_nations, ccc_nations, nations):
for c in nations:
if c not in ccc_nations:
xxx_nations.remove(c)
return xxx_nations
def extant_intensity(ydat, listy, emission):
listy2 = [l for l in listy]
for n in listy2:
if (ydat[emission][ydat.Country.tolist().index(n)] > 0) == False:
listy.remove(n)
return listy
yrs = [i for i in range(1970,2015)]
for y in yrs:
print('Creating data for year ' + str(y) + '.......')
comp_nations = sorted(main_data.Country.unique().tolist())
co2_nations = sorted(main_data.Country.unique().tolist())
ch4_nations = sorted(main_data.Country.unique().tolist())
nox_nations = sorted(main_data.Country.unique().tolist())
ghg_nations = sorted(main_data.Country.unique().tolist())
A_co2 = pd.read_csv('C:/Users/User/Documents/Data/Pollution/Networks/A_' + str(y) + '.csv')
A_ch4 = pd.read_csv('C:/Users/User/Documents/Data/Pollution/Networks/A_' + str(y) + '.csv')
A_nox = pd.read_csv('C:/Users/User/Documents/Data/Pollution/Networks/A_' + str(y) + '.csv')
A_ghg = pd.read_csv('C:/Users/User/Documents/Data/Pollution/Networks/A_' + str(y) + '.csv')
ydata = main_data[main_data['Year'] == y].reset_index().drop('index', axis = 1)
for n in nations:
if (n in A_co2.columns.tolist()) == False:
comp_nations.remove(n)
elif sum(A_co2[n]) == 0:
comp_nations.remove(n)
co2_nations = emissions_lists(co2_nations, comp_nations, nations)
ch4_nations = emissions_lists(ch4_nations, comp_nations, nations)
nox_nations = emissions_lists(nox_nations, comp_nations, nations)
ghg_nations = emissions_lists(ghg_nations, comp_nations, nations)
co2_nations = extant_intensity(ydata, co2_nations, 'co2_intensity')
ch4_nations = extant_intensity(ydata, ch4_nations, 'ch4_intensity')
nox_nations = extant_intensity(ydata, nox_nations, 'nox_intensity')
ghg_nations = extant_intensity(ydata, ghg_nations, 'ghg_intensity')
co2_indices = A_co2.columns.tolist()
ch4_indices = A_ch4.columns.tolist()
nox_indices = A_nox.columns.tolist()
ghg_indices = A_ghg.columns.tolist()
co2_indices.reverse()
ch4_indices.reverse()
nox_indices.reverse()
ghg_indices.reverse()
for col in co2_indices:
if col not in co2_nations:
A_co2 = A_co2.drop(A_co2.columns.tolist().index(col), axis = 0)
A_co2 = A_co2.drop(col, axis = 1)
for col in ch4_indices:
if col not in ch4_nations:
A_ch4 = A_ch4.drop(A_ch4.columns.tolist().index(col), axis = 0)
A_ch4 = A_ch4.drop(col, axis = 1)
for col in nox_indices:
if col not in nox_nations:
A_nox = A_nox.drop(A_nox.columns.tolist().index(col), axis = 0)
A_nox = A_nox.drop(col, axis = 1)
for col in ghg_indices:
if col not in ghg_nations:
A_ghg = A_ghg.drop(A_ghg.columns.tolist().index(col), axis = 0)
A_ghg = A_ghg.drop(col, axis = 1)
co2_sums = [sum(A_co2.iloc[row]) for row in range(len(A_co2))]
ch4_sums = [sum(A_ch4.iloc[row]) for row in range(len(A_ch4))]
nox_sums = [sum(A_nox.iloc[row]) for row in range(len(A_nox))]
ghg_sums = [sum(A_ghg.iloc[row]) for row in range(len(A_ghg))]
M_co2 = np.matrix(A_co2)
M_ch4 = np.matrix(A_ch4)
M_nox = np.matrix(A_nox)
M_ghg = np.matrix(A_ghg)
for row in range(len(co2_sums)):
M_co2[row,:] = M_co2[row,:] / co2_sums[row]
for row in range(len(ch4_sums)):
M_ch4[row,:] = M_ch4[row,:] / ch4_sums[row]
for row in range(len(nox_sums)):
M_nox[row,:] = M_nox[row,:] / nox_sums[row]
for row in range(len(ghg_sums)):
M_ghg[row,:] = M_ghg[row,:] / ghg_sums[row]
co2_ints = np.matrix([ydata.co2_intensity[ydata.Country.tolist().index(n)] for n in co2_nations]).T
ch4_ints = np.matrix([ydata.ch4_intensity[ydata.Country.tolist().index(n)] for n in ch4_nations]).T
nox_ints = np.matrix([ydata.nox_intensity[ydata.Country.tolist().index(n)] for n in nox_nations]).T
ghg_ints = np.matrix([ydata.ghg_intensity[ydata.Country.tolist().index(n)] for n in ghg_nations]).T
co2_data = np.matmul(M_co2,co2_ints)
ch4_data = np.matmul(M_ch4,ch4_ints)
nox_data = np.matmul(M_nox,nox_ints)
ghg_data = np.matmul(M_ghg,ghg_ints)
current_year = [y for c in co2_nations]
next_year = [y+1 for c in co2_nations]
co2_d = [x[0] for x in co2_data.tolist()]
temp_co2 = pd.DataFrame({'Current Year':current_year, 'Next Year':next_year,
'Nation':co2_nations, 'CO2 Data':co2_d})
CO2_df = pd.concat([CO2_df, temp_co2], axis = 0)
current_year = [y for c in ch4_nations]
next_year = [y+1 for c in ch4_nations]
ch4_d = [x[0] for x in ch4_data.tolist()]
temp_ch4 = pd.DataFrame({'Current Year':current_year, 'Next Year':next_year,
'Nation':ch4_nations, 'CH4 Data':ch4_d})
CH4_df = pd.concat([CH4_df, temp_ch4], axis = 0)
current_year = [y for c in nox_nations]
next_year = [y+1 for c in nox_nations]
nox_d = [x[0] for x in nox_data.tolist()]
temp_nox = pd.DataFrame({'Current Year':current_year, 'Next Year':next_year,
'Nation':nox_nations, 'NOX Data':nox_d})
NOX_df = pd.concat([NOX_df, temp_nox], axis = 0)
current_year = [y for c in ghg_nations]
next_year = [y+1 for c in ghg_nations]
ghg_d = [x[0] for x in ghg_data.tolist()]
temp_ghg = pd.DataFrame({'Current Year':current_year, 'Next Year':next_year,
'Nation':ghg_nations, 'GHG Data':ghg_d})
GHG_df = pd.concat([GHG_df, temp_ghg], axis = 0)
CO2_df.to_csv('C:/Users/User/Documents/Data/Pollution/A_DATA_CO2.csv', index = False)
CH4_df.to_csv('C:/Users/User/Documents/Data/Pollution/A_DATA_CH4.csv', index = False)
NOX_df.to_csv('C:/Users/User/Documents/Data/Pollution/A_DATA_NOX.csv', index = False)
GHG_df.to_csv('C:/Users/User/Documents/Data/Pollution/A_DATA_GHG.csv', index = False)
| true | true |
f73bab442c5d2973e3cb2f6e90739b441342cb3b | 5,949 | py | Python | sacred/observers/sql.py | daliasen/sacred | e7ea9422c7172818cbce3d0703556e12faf3ac8e | [
"MIT"
] | null | null | null | sacred/observers/sql.py | daliasen/sacred | e7ea9422c7172818cbce3d0703556e12faf3ac8e | [
"MIT"
] | null | null | null | sacred/observers/sql.py | daliasen/sacred | e7ea9422c7172818cbce3d0703556e12faf3ac8e | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# coding=utf-8
import json
from threading import Lock
import warnings
from sacred.commandline_options import cli_option
from sacred.observers.base import RunObserver
from sacred.serializer import flatten
DEFAULT_SQL_PRIORITY = 40
# ############################# Observer #################################### #
class SqlObserver(RunObserver):
@classmethod
def create(cls, url, echo=False, priority=DEFAULT_SQL_PRIORITY):
warnings.warn(
"SqlObserver.create(...) is deprecated. Please use"
" SqlObserver(...) instead.",
DeprecationWarning,
)
return cls(url, echo, priority)
def __init__(self, url, echo=False, priority=DEFAULT_SQL_PRIORITY):
from sqlalchemy.orm import sessionmaker, scoped_session
import sqlalchemy as sa
engine = sa.create_engine(url, echo=echo)
session_factory = sessionmaker(bind=engine)
# make session thread-local to avoid problems with sqlite (see #275)
session = scoped_session(session_factory)
self.engine = engine
self.session = session
self.priority = priority
self.run = None
self.lock = Lock()
@classmethod
def create_from(cls, engine, session, priority=DEFAULT_SQL_PRIORITY):
"""Instantiate a SqlObserver with an existing engine and session."""
self = cls.__new__(cls) # skip __init__ call
self.engine = engine
self.session = session
self.priority = priority
self.run = None
self.lock = Lock()
return self
def started_event(
self, ex_info, command, host_info, start_time, config, meta_info, _id
):
return self._add_event(
ex_info,
command,
host_info,
config,
meta_info,
_id,
"RUNNING",
start_time=start_time,
)
def queued_event(
self, ex_info, command, host_info, queue_time, config, meta_info, _id
):
return self._add_event(
ex_info, command, host_info, config, meta_info, _id, "QUEUED"
)
def _add_event(
self, ex_info, command, host_info, config, meta_info, _id, status, **kwargs
):
from .sql_bases import Base, Experiment, Host, Run
Base.metadata.create_all(self.engine)
sql_exp = Experiment.get_or_create(ex_info, self.session)
sql_host = Host.get_or_create(host_info, self.session)
if _id is None:
while _id is None:
i = self.session.query(Run).order_by(Run.id.desc()).first()
_id = 0 if i is None else i.id + 1
self.run = Run(
run_id=str(_id),
config=json.dumps(flatten(config)),
command=command,
priority=meta_info.get("priority", 0),
comment=meta_info.get("comment", ""),
experiment=sql_exp,
host=sql_host,
status=status,
**kwargs,
)
self.session.add(self.run)
with self.lock:
try:
self.session.commit()
break
except IntegrityError:
self.session.rollback()
_id = None
else:
self.run = Run(
run_id=str(_id),
config=json.dumps(flatten(config)),
command=command,
priority=meta_info.get("priority", 0),
comment=meta_info.get("comment", ""),
experiment=sql_exp,
host=sql_host,
status=status,
**kwargs,
)
self.session.add(self.run)
self.save()
return _id or self.run.run_id
def heartbeat_event(self, info, captured_out, beat_time, result):
self.run.info = json.dumps(flatten(info))
self.run.captured_out = captured_out
self.run.heartbeat = beat_time
self.run.result = result
self.save()
def completed_event(self, stop_time, result):
self.run.stop_time = stop_time
self.run.result = result
self.run.status = "COMPLETED"
self.save()
def interrupted_event(self, interrupt_time, status):
self.run.stop_time = interrupt_time
self.run.status = status
self.save()
def failed_event(self, fail_time, fail_trace):
self.run.stop_time = fail_time
self.run.fail_trace = "\n".join(fail_trace)
self.run.status = "FAILED"
self.save()
def resource_event(self, filename):
from .sql_bases import Resource
res = Resource.get_or_create(filename, self.session)
self.run.resources.append(res)
self.save()
def artifact_event(self, name, filename, metadata=None, content_type=None):
from .sql_bases import Artifact
a = Artifact.create(name, filename)
self.run.artifacts.append(a)
self.save()
def save(self):
with self.lock:
self.session.commit()
def query(self, _id):
from .sql_bases import Run
run = self.session.query(Run).filter_by(id=_id).first()
return run.to_json()
def __eq__(self, other):
if isinstance(other, SqlObserver):
# fixme: this will probably fail to detect two equivalent engines
return self.engine == other.engine and self.session == other.session
return False
# ######################## Commandline Option ############################### #
@cli_option("-s", "--sql")
def sql_option(args, run):
"""Add a SQL Observer to the experiment.
The typical form is: dialect://username:password@host:port/database
"""
run.observers.append(SqlObserver(args))
| 31.310526 | 83 | 0.567827 |
import json
from threading import Lock
import warnings
from sacred.commandline_options import cli_option
from sacred.observers.base import RunObserver
from sacred.serializer import flatten
DEFAULT_SQL_PRIORITY = 40
us,
**kwargs,
)
self.session.add(self.run)
with self.lock:
try:
self.session.commit()
break
except IntegrityError:
self.session.rollback()
_id = None
else:
self.run = Run(
run_id=str(_id),
config=json.dumps(flatten(config)),
command=command,
priority=meta_info.get("priority", 0),
comment=meta_info.get("comment", ""),
experiment=sql_exp,
host=sql_host,
status=status,
**kwargs,
)
self.session.add(self.run)
self.save()
return _id or self.run.run_id
def heartbeat_event(self, info, captured_out, beat_time, result):
self.run.info = json.dumps(flatten(info))
self.run.captured_out = captured_out
self.run.heartbeat = beat_time
self.run.result = result
self.save()
def completed_event(self, stop_time, result):
self.run.stop_time = stop_time
self.run.result = result
self.run.status = "COMPLETED"
self.save()
def interrupted_event(self, interrupt_time, status):
self.run.stop_time = interrupt_time
self.run.status = status
self.save()
def failed_event(self, fail_time, fail_trace):
self.run.stop_time = fail_time
self.run.fail_trace = "\n".join(fail_trace)
self.run.status = "FAILED"
self.save()
def resource_event(self, filename):
from .sql_bases import Resource
res = Resource.get_or_create(filename, self.session)
self.run.resources.append(res)
self.save()
def artifact_event(self, name, filename, metadata=None, content_type=None):
from .sql_bases import Artifact
a = Artifact.create(name, filename)
self.run.artifacts.append(a)
self.save()
def save(self):
with self.lock:
self.session.commit()
def query(self, _id):
from .sql_bases import Run
run = self.session.query(Run).filter_by(id=_id).first()
return run.to_json()
def __eq__(self, other):
if isinstance(other, SqlObserver):
return self.engine == other.engine and self.session == other.session
return False
| true | true |
f73bab60ac3f4dec67323ba8ad64ec2ed8c7607a | 9,108 | py | Python | core/utils/augmentor.py | brianchung0803/GMA | 5c5647ae248f77f47d5b5cf0281933635b37e631 | [
"WTFPL"
] | 155 | 2021-04-06T04:30:35.000Z | 2022-03-29T10:28:41.000Z | core/utils/augmentor.py | brianchung0803/GMA | 5c5647ae248f77f47d5b5cf0281933635b37e631 | [
"WTFPL"
] | 21 | 2021-04-11T09:21:15.000Z | 2022-03-15T06:45:12.000Z | core/utils/augmentor.py | brianchung0803/GMA | 5c5647ae248f77f47d5b5cf0281933635b37e631 | [
"WTFPL"
] | 26 | 2021-04-09T09:57:28.000Z | 2022-02-28T07:49:52.000Z | import numpy as np
import random
import math
from PIL import Image
import cv2
cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)
import torch
from torchvision.transforms import ColorJitter
import torch.nn.functional as F
class FlowAugmentor:
def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=True):
# spatial augmentation params
self.crop_size = crop_size
self.min_scale = min_scale
self.max_scale = max_scale
self.spatial_aug_prob = 0.8
self.stretch_prob = 0.8
self.max_stretch = 0.2
# flip augmentation params
self.do_flip = do_flip
self.h_flip_prob = 0.5
self.v_flip_prob = 0.1
# photometric augmentation params
self.photo_aug = ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.5/3.14)
self.asymmetric_color_aug_prob = 0.2
self.eraser_aug_prob = 0.5
def color_transform(self, img1, img2):
""" Photometric augmentation """
# asymmetric
if np.random.rand() < self.asymmetric_color_aug_prob:
img1 = np.array(self.photo_aug(Image.fromarray(img1)), dtype=np.uint8)
img2 = np.array(self.photo_aug(Image.fromarray(img2)), dtype=np.uint8)
# symmetric
else:
image_stack = np.concatenate([img1, img2], axis=0)
image_stack = np.array(self.photo_aug(Image.fromarray(image_stack)), dtype=np.uint8)
img1, img2 = np.split(image_stack, 2, axis=0)
return img1, img2
def eraser_transform(self, img1, img2, bounds=[50, 100]):
""" Occlusion augmentation """
ht, wd = img1.shape[:2]
if np.random.rand() < self.eraser_aug_prob:
mean_color = np.mean(img2.reshape(-1, 3), axis=0)
for _ in range(np.random.randint(1, 3)):
x0 = np.random.randint(0, wd)
y0 = np.random.randint(0, ht)
dx = np.random.randint(bounds[0], bounds[1])
dy = np.random.randint(bounds[0], bounds[1])
img2[y0:y0+dy, x0:x0+dx, :] = mean_color
return img1, img2
def spatial_transform(self, img1, img2, flow):
# randomly sample scale
ht, wd = img1.shape[:2]
min_scale = np.maximum(
(self.crop_size[0] + 8) / float(ht),
(self.crop_size[1] + 8) / float(wd))
scale = 2 ** np.random.uniform(self.min_scale, self.max_scale)
scale_x = scale
scale_y = scale
if np.random.rand() < self.stretch_prob:
scale_x *= 2 ** np.random.uniform(-self.max_stretch, self.max_stretch)
scale_y *= 2 ** np.random.uniform(-self.max_stretch, self.max_stretch)
scale_x = np.clip(scale_x, min_scale, None)
scale_y = np.clip(scale_y, min_scale, None)
if np.random.rand() < self.spatial_aug_prob:
# rescale the images
img1 = cv2.resize(img1, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)
img2 = cv2.resize(img2, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)
flow = cv2.resize(flow, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)
flow = flow * [scale_x, scale_y]
if self.do_flip:
if np.random.rand() < self.h_flip_prob: # h-flip
img1 = img1[:, ::-1]
img2 = img2[:, ::-1]
flow = flow[:, ::-1] * [-1.0, 1.0]
if np.random.rand() < self.v_flip_prob: # v-flip
img1 = img1[::-1, :]
img2 = img2[::-1, :]
flow = flow[::-1, :] * [1.0, -1.0]
y0 = np.random.randint(0, img1.shape[0] - self.crop_size[0])
x0 = np.random.randint(0, img1.shape[1] - self.crop_size[1])
img1 = img1[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
img2 = img2[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
flow = flow[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
return img1, img2, flow
def __call__(self, img1, img2, flow):
img1, img2 = self.color_transform(img1, img2)
img1, img2 = self.eraser_transform(img1, img2)
img1, img2, flow = self.spatial_transform(img1, img2, flow)
img1 = np.ascontiguousarray(img1)
img2 = np.ascontiguousarray(img2)
flow = np.ascontiguousarray(flow)
return img1, img2, flow
class SparseFlowAugmentor:
def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=False):
# spatial augmentation params
self.crop_size = crop_size
self.min_scale = min_scale
self.max_scale = max_scale
self.spatial_aug_prob = 0.8
self.stretch_prob = 0.8
self.max_stretch = 0.2
# flip augmentation params
self.do_flip = do_flip
self.h_flip_prob = 0.5
self.v_flip_prob = 0.1
# photometric augmentation params
self.photo_aug = ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.3/3.14)
self.asymmetric_color_aug_prob = 0.2
self.eraser_aug_prob = 0.5
def color_transform(self, img1, img2):
image_stack = np.concatenate([img1, img2], axis=0)
image_stack = np.array(self.photo_aug(Image.fromarray(image_stack)), dtype=np.uint8)
img1, img2 = np.split(image_stack, 2, axis=0)
return img1, img2
def eraser_transform(self, img1, img2):
ht, wd = img1.shape[:2]
if np.random.rand() < self.eraser_aug_prob:
mean_color = np.mean(img2.reshape(-1, 3), axis=0)
for _ in range(np.random.randint(1, 3)):
x0 = np.random.randint(0, wd)
y0 = np.random.randint(0, ht)
dx = np.random.randint(50, 100)
dy = np.random.randint(50, 100)
img2[y0:y0+dy, x0:x0+dx, :] = mean_color
return img1, img2
def resize_sparse_flow_map(self, flow, valid, fx=1.0, fy=1.0):
ht, wd = flow.shape[:2]
coords = np.meshgrid(np.arange(wd), np.arange(ht))
coords = np.stack(coords, axis=-1)
coords = coords.reshape(-1, 2).astype(np.float32)
flow = flow.reshape(-1, 2).astype(np.float32)
valid = valid.reshape(-1).astype(np.float32)
coords0 = coords[valid>=1]
flow0 = flow[valid>=1]
ht1 = int(round(ht * fy))
wd1 = int(round(wd * fx))
coords1 = coords0 * [fx, fy]
flow1 = flow0 * [fx, fy]
xx = np.round(coords1[:,0]).astype(np.int32)
yy = np.round(coords1[:,1]).astype(np.int32)
v = (xx > 0) & (xx < wd1) & (yy > 0) & (yy < ht1)
xx = xx[v]
yy = yy[v]
flow1 = flow1[v]
flow_img = np.zeros([ht1, wd1, 2], dtype=np.float32)
valid_img = np.zeros([ht1, wd1], dtype=np.int32)
flow_img[yy, xx] = flow1
valid_img[yy, xx] = 1
return flow_img, valid_img
def spatial_transform(self, img1, img2, flow, valid):
# randomly sample scale
ht, wd = img1.shape[:2]
min_scale = np.maximum(
(self.crop_size[0] + 1) / float(ht),
(self.crop_size[1] + 1) / float(wd))
scale = 2 ** np.random.uniform(self.min_scale, self.max_scale)
scale_x = np.clip(scale, min_scale, None)
scale_y = np.clip(scale, min_scale, None)
if np.random.rand() < self.spatial_aug_prob:
# rescale the images
img1 = cv2.resize(img1, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)
img2 = cv2.resize(img2, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)
flow, valid = self.resize_sparse_flow_map(flow, valid, fx=scale_x, fy=scale_y)
if self.do_flip:
if np.random.rand() < 0.5: # h-flip
img1 = img1[:, ::-1]
img2 = img2[:, ::-1]
flow = flow[:, ::-1] * [-1.0, 1.0]
valid = valid[:, ::-1]
margin_y = 20
margin_x = 50
y0 = np.random.randint(0, img1.shape[0] - self.crop_size[0] + margin_y)
x0 = np.random.randint(-margin_x, img1.shape[1] - self.crop_size[1] + margin_x)
y0 = np.clip(y0, 0, img1.shape[0] - self.crop_size[0])
x0 = np.clip(x0, 0, img1.shape[1] - self.crop_size[1])
img1 = img1[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
img2 = img2[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
flow = flow[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
valid = valid[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
return img1, img2, flow, valid
def __call__(self, img1, img2, flow, valid):
img1, img2 = self.color_transform(img1, img2)
img1, img2 = self.eraser_transform(img1, img2)
img1, img2, flow, valid = self.spatial_transform(img1, img2, flow, valid)
img1 = np.ascontiguousarray(img1)
img2 = np.ascontiguousarray(img2)
flow = np.ascontiguousarray(flow)
valid = np.ascontiguousarray(valid)
return img1, img2, flow, valid
| 36.874494 | 97 | 0.582565 | import numpy as np
import random
import math
from PIL import Image
import cv2
cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)
import torch
from torchvision.transforms import ColorJitter
import torch.nn.functional as F
class FlowAugmentor:
def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=True):
self.crop_size = crop_size
self.min_scale = min_scale
self.max_scale = max_scale
self.spatial_aug_prob = 0.8
self.stretch_prob = 0.8
self.max_stretch = 0.2
self.do_flip = do_flip
self.h_flip_prob = 0.5
self.v_flip_prob = 0.1
self.photo_aug = ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.5/3.14)
self.asymmetric_color_aug_prob = 0.2
self.eraser_aug_prob = 0.5
def color_transform(self, img1, img2):
if np.random.rand() < self.asymmetric_color_aug_prob:
img1 = np.array(self.photo_aug(Image.fromarray(img1)), dtype=np.uint8)
img2 = np.array(self.photo_aug(Image.fromarray(img2)), dtype=np.uint8)
else:
image_stack = np.concatenate([img1, img2], axis=0)
image_stack = np.array(self.photo_aug(Image.fromarray(image_stack)), dtype=np.uint8)
img1, img2 = np.split(image_stack, 2, axis=0)
return img1, img2
def eraser_transform(self, img1, img2, bounds=[50, 100]):
ht, wd = img1.shape[:2]
if np.random.rand() < self.eraser_aug_prob:
mean_color = np.mean(img2.reshape(-1, 3), axis=0)
for _ in range(np.random.randint(1, 3)):
x0 = np.random.randint(0, wd)
y0 = np.random.randint(0, ht)
dx = np.random.randint(bounds[0], bounds[1])
dy = np.random.randint(bounds[0], bounds[1])
img2[y0:y0+dy, x0:x0+dx, :] = mean_color
return img1, img2
def spatial_transform(self, img1, img2, flow):
ht, wd = img1.shape[:2]
min_scale = np.maximum(
(self.crop_size[0] + 8) / float(ht),
(self.crop_size[1] + 8) / float(wd))
scale = 2 ** np.random.uniform(self.min_scale, self.max_scale)
scale_x = scale
scale_y = scale
if np.random.rand() < self.stretch_prob:
scale_x *= 2 ** np.random.uniform(-self.max_stretch, self.max_stretch)
scale_y *= 2 ** np.random.uniform(-self.max_stretch, self.max_stretch)
scale_x = np.clip(scale_x, min_scale, None)
scale_y = np.clip(scale_y, min_scale, None)
if np.random.rand() < self.spatial_aug_prob:
img1 = cv2.resize(img1, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)
img2 = cv2.resize(img2, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)
flow = cv2.resize(flow, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)
flow = flow * [scale_x, scale_y]
if self.do_flip:
if np.random.rand() < self.h_flip_prob:
img1 = img1[:, ::-1]
img2 = img2[:, ::-1]
flow = flow[:, ::-1] * [-1.0, 1.0]
if np.random.rand() < self.v_flip_prob:
img1 = img1[::-1, :]
img2 = img2[::-1, :]
flow = flow[::-1, :] * [1.0, -1.0]
y0 = np.random.randint(0, img1.shape[0] - self.crop_size[0])
x0 = np.random.randint(0, img1.shape[1] - self.crop_size[1])
img1 = img1[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
img2 = img2[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
flow = flow[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
return img1, img2, flow
def __call__(self, img1, img2, flow):
img1, img2 = self.color_transform(img1, img2)
img1, img2 = self.eraser_transform(img1, img2)
img1, img2, flow = self.spatial_transform(img1, img2, flow)
img1 = np.ascontiguousarray(img1)
img2 = np.ascontiguousarray(img2)
flow = np.ascontiguousarray(flow)
return img1, img2, flow
class SparseFlowAugmentor:
def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=False):
self.crop_size = crop_size
self.min_scale = min_scale
self.max_scale = max_scale
self.spatial_aug_prob = 0.8
self.stretch_prob = 0.8
self.max_stretch = 0.2
self.do_flip = do_flip
self.h_flip_prob = 0.5
self.v_flip_prob = 0.1
self.photo_aug = ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.3/3.14)
self.asymmetric_color_aug_prob = 0.2
self.eraser_aug_prob = 0.5
def color_transform(self, img1, img2):
image_stack = np.concatenate([img1, img2], axis=0)
image_stack = np.array(self.photo_aug(Image.fromarray(image_stack)), dtype=np.uint8)
img1, img2 = np.split(image_stack, 2, axis=0)
return img1, img2
def eraser_transform(self, img1, img2):
ht, wd = img1.shape[:2]
if np.random.rand() < self.eraser_aug_prob:
mean_color = np.mean(img2.reshape(-1, 3), axis=0)
for _ in range(np.random.randint(1, 3)):
x0 = np.random.randint(0, wd)
y0 = np.random.randint(0, ht)
dx = np.random.randint(50, 100)
dy = np.random.randint(50, 100)
img2[y0:y0+dy, x0:x0+dx, :] = mean_color
return img1, img2
def resize_sparse_flow_map(self, flow, valid, fx=1.0, fy=1.0):
ht, wd = flow.shape[:2]
coords = np.meshgrid(np.arange(wd), np.arange(ht))
coords = np.stack(coords, axis=-1)
coords = coords.reshape(-1, 2).astype(np.float32)
flow = flow.reshape(-1, 2).astype(np.float32)
valid = valid.reshape(-1).astype(np.float32)
coords0 = coords[valid>=1]
flow0 = flow[valid>=1]
ht1 = int(round(ht * fy))
wd1 = int(round(wd * fx))
coords1 = coords0 * [fx, fy]
flow1 = flow0 * [fx, fy]
xx = np.round(coords1[:,0]).astype(np.int32)
yy = np.round(coords1[:,1]).astype(np.int32)
v = (xx > 0) & (xx < wd1) & (yy > 0) & (yy < ht1)
xx = xx[v]
yy = yy[v]
flow1 = flow1[v]
flow_img = np.zeros([ht1, wd1, 2], dtype=np.float32)
valid_img = np.zeros([ht1, wd1], dtype=np.int32)
flow_img[yy, xx] = flow1
valid_img[yy, xx] = 1
return flow_img, valid_img
def spatial_transform(self, img1, img2, flow, valid):
ht, wd = img1.shape[:2]
min_scale = np.maximum(
(self.crop_size[0] + 1) / float(ht),
(self.crop_size[1] + 1) / float(wd))
scale = 2 ** np.random.uniform(self.min_scale, self.max_scale)
scale_x = np.clip(scale, min_scale, None)
scale_y = np.clip(scale, min_scale, None)
if np.random.rand() < self.spatial_aug_prob:
img1 = cv2.resize(img1, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)
img2 = cv2.resize(img2, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)
flow, valid = self.resize_sparse_flow_map(flow, valid, fx=scale_x, fy=scale_y)
if self.do_flip:
if np.random.rand() < 0.5:
img1 = img1[:, ::-1]
img2 = img2[:, ::-1]
flow = flow[:, ::-1] * [-1.0, 1.0]
valid = valid[:, ::-1]
margin_y = 20
margin_x = 50
y0 = np.random.randint(0, img1.shape[0] - self.crop_size[0] + margin_y)
x0 = np.random.randint(-margin_x, img1.shape[1] - self.crop_size[1] + margin_x)
y0 = np.clip(y0, 0, img1.shape[0] - self.crop_size[0])
x0 = np.clip(x0, 0, img1.shape[1] - self.crop_size[1])
img1 = img1[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
img2 = img2[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
flow = flow[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
valid = valid[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
return img1, img2, flow, valid
def __call__(self, img1, img2, flow, valid):
img1, img2 = self.color_transform(img1, img2)
img1, img2 = self.eraser_transform(img1, img2)
img1, img2, flow, valid = self.spatial_transform(img1, img2, flow, valid)
img1 = np.ascontiguousarray(img1)
img2 = np.ascontiguousarray(img2)
flow = np.ascontiguousarray(flow)
valid = np.ascontiguousarray(valid)
return img1, img2, flow, valid
| true | true |
f73bac4341781f5243e4344c4f9199468247396d | 6,451 | py | Python | tomatopy/reviews.py | FinTrek/tomatopy | 355f41197ae48abc62496261efd39e24c5099e9b | [
"MIT"
] | 5 | 2019-09-08T19:32:09.000Z | 2021-03-05T02:15:41.000Z | tomatopy/reviews.py | FinTrek/tomatopy | 355f41197ae48abc62496261efd39e24c5099e9b | [
"MIT"
] | 2 | 2020-07-20T18:06:12.000Z | 2020-09-25T13:10:09.000Z | tomatopy/reviews.py | sjmiller8182/tomatopy | 355f41197ae48abc62496261efd39e24c5099e9b | [
"MIT"
] | 3 | 2019-12-10T22:04:46.000Z | 2020-10-17T23:48:17.000Z | """main_info.py
This file contains private functions for scraping the review pages
This file requires no packages.
This file contains the following functions:
* _get_critic_reviews_from_page - scrapes info per critic page
* _get_num_pages - finds number of pages to scrape
* get_critic_reviews - scrapes info over all critic pages
"""
#===================
# imports / m-global
#===================
# base
import re
import time
from typing import Dict, List
# this package
from .util import _make_soup
from .util import get_verbose_setting
from .util import _build_url
# regex patterns
# run once on import
page_pat = re.compile(r'Page 1 of \d+')
review_pat = re.compile(r'<div class=\"the_review\">[;a-zA-Z\s,-.\'\/\?\[\]\":\']*</div>')
rating_pat = re.compile(r'Original Score:\s([A-Z](\+|-)?|\d(.\d)?(\/\d)?)')
fresh_pat = re.compile(r'small\s(fresh|rotten)\"')
critic_pat = re.compile(r'\/\"\>([A-Z][a-zA-Z]+\s[A-Z][a-zA-Z\-]+)|([A-Z][a-zA-Z.]+\s[A-Z].?\s[A-Z][a-zA-Z]+)|([A-Z][a-zA-Z]+\s[A-Z]+\'[A-Z][a-zA-Z]+)')
publisher_pat = re.compile(r'\"subtle\">[a-zA-Z\s,.\(\)\'\-&;!\/\d+]+</em>')
date_pat = re.compile(r'[a-zA-Z]+\s\d+,\s\d+')
#=======================
# Critic Review Handling
#=======================
#==================
# interal functions
#==================
def _get_critic_reviews_from_page(soup) -> List:
"""Get the review, rating, critic, if critic is a
'top critic', publisher, date from a given page (bs4)
Parameters
----------
soup : bs4 object
bs4 html tree from html_parser
Returns
-------
list
list of lists containing the following:
reviews, rating, fresh, critic, top_critic,
publisher, date
"""
reviews = list()
rating = list()
fresh = list()
critic = list()
top_critic = list()
publisher = list()
date = list()
soup = str(soup)
review_soup = soup.split('="review_table')[1].split('row review_table_row')
review_soup.pop(0)
# extract info
for review in review_soup:
# extract review
match = re.findall(review_pat, str(review))
if len(match) > 0:
m = match[0]
for iden in ['<div class="the_review"> ','</div>']:
m = m.replace(iden,'')
reviews.append(m.strip('"'))
# extract rating
match = re.findall(rating_pat, str(review))
if len(match) > 0:
m = match[0][0]
if '/1' in m:
sp_m = m.split('/')
if sp_m[-1] == '1':
sp_m[-1] = '10'
m = '/'.join(sp_m)
rating.append(m)
else:
rating.append(None)
# extract fresh indicator
match = re.findall(fresh_pat, str(review))
if len(match) > 0:
fresh.append(match[0])
else:
fresh.append(None)
# extract ciritic
match = re.findall(critic_pat, str(review))
if len(match) > 0:
critic.append(''.join(match[0]))
else:
critic.append(None)
# check if top critic
if '> Top Critic<' in str(review):
top_critic.append(1)
else:
top_critic.append(0)
# extract publisher
match = re.findall(publisher_pat, str(review))
if len(match) > 0:
m = match[0]
m = m.replace('"subtle">', '')
m = m.replace('</em>','')
publisher.append(m)
else:
publisher.append(None)
# extract date
match = re.findall(date_pat, str(review))
if len(match) > 0:
date.append(match[0].strip('"'))
else:
date.append(None)
return [reviews, rating, fresh, critic, top_critic, publisher, date]
def _get_num_pages(soup) -> List:
"""Find the number of pages to scrape reviews from
Parameters
----------
soup : bs4 object
bs4 html tree from html_parser
Returns
-------
str
number of pages with reviews
"""
# from soup decend to page level
match = re.findall(page_pat,str(list(soup)))
if len(match) > 0:
match = match[0]
match = match.split(' of ')[-1]
return match
else:
return None
#===============
# user functions
#===============
def get_critic_reviews(page: str) -> Dict[str, List]:
"""Crawls the set of critic review pages for the given movie.
Returns a dict withkeys: reviews, rating, fresh,
critic, top_critic, publisher, date.
Parameters
----------
page : str
main page url for movie
Returns
-------
dict
dict containing scraped review info with the following keys:
'reviews', 'rating', 'fresh', 'critic', 'top_critic',
'publisher', 'date'
"""
# containers
info = [[],[],[],[],[],[],[]]
# make soup
soup = _make_soup(page + "reviews")
# how many soups?
pages = _get_num_pages(soup)
if pages is not None:
# verbose option
if get_verbose_setting():
print('scraping critic reviews')
print('scraping url: ' + page + "reviews " + str(pages) + " pages to scrape")
# eat soup
for page_num in range(1,int(pages)+1):
soup = _make_soup(page + "reviews?page=" + str(page_num) + "&sort=")
c_info = _get_critic_reviews_from_page(soup)
# accumulate review info
for i in range(len(c_info)):
info[i] = info[i] + c_info[i]
c_info = dict()
keys = ['reviews', 'rating', 'fresh', 'critic', 'top_critic', 'publisher', 'date']
for k in range(len(keys)):
c_info[keys[k]] = info[k]
# verbose option
if get_verbose_setting():
print('done scraping critic reviews')
else:
# if pages doesnt match return None; its easy to detect
c_info = None
return c_info
#=====================
# User Review Handling
#=====================
# TODO: Add scraping for user reviews
| 27.926407 | 152 | 0.505813 |
import re
import time
from typing import Dict, List
from .util import _make_soup
from .util import get_verbose_setting
from .util import _build_url
page_pat = re.compile(r'Page 1 of \d+')
review_pat = re.compile(r'<div class=\"the_review\">[;a-zA-Z\s,-.\'\/\?\[\]\":\']*</div>')
rating_pat = re.compile(r'Original Score:\s([A-Z](\+|-)?|\d(.\d)?(\/\d)?)')
fresh_pat = re.compile(r'small\s(fresh|rotten)\"')
critic_pat = re.compile(r'\/\"\>([A-Z][a-zA-Z]+\s[A-Z][a-zA-Z\-]+)|([A-Z][a-zA-Z.]+\s[A-Z].?\s[A-Z][a-zA-Z]+)|([A-Z][a-zA-Z]+\s[A-Z]+\'[A-Z][a-zA-Z]+)')
publisher_pat = re.compile(r'\"subtle\">[a-zA-Z\s,.\(\)\'\-&;!\/\d+]+</em>')
date_pat = re.compile(r'[a-zA-Z]+\s\d+,\s\d+')
#=======================
# Critic Review Handling
#=======================
#==================
# interal functions
#==================
def _get_critic_reviews_from_page(soup) -> List:
reviews = list()
rating = list()
fresh = list()
critic = list()
top_critic = list()
publisher = list()
date = list()
soup = str(soup)
review_soup = soup.split('="review_table')[1].split('row review_table_row')
review_soup.pop(0)
for review in review_soup:
match = re.findall(review_pat, str(review))
if len(match) > 0:
m = match[0]
for iden in ['<div class="the_review"> ','</div>']:
m = m.replace(iden,'')
reviews.append(m.strip('"'))
# extract rating
match = re.findall(rating_pat, str(review))
if len(match) > 0:
m = match[0][0]
if '/1' in m:
sp_m = m.split('/')
if sp_m[-1] == '1':
sp_m[-1] = '10'
m = '/'.join(sp_m)
rating.append(m)
else:
rating.append(None)
# extract fresh indicator
match = re.findall(fresh_pat, str(review))
if len(match) > 0:
fresh.append(match[0])
else:
fresh.append(None)
# extract ciritic
match = re.findall(critic_pat, str(review))
if len(match) > 0:
critic.append(''.join(match[0]))
else:
critic.append(None)
# check if top critic
if '> Top Critic<' in str(review):
top_critic.append(1)
else:
top_critic.append(0)
# extract publisher
match = re.findall(publisher_pat, str(review))
if len(match) > 0:
m = match[0]
m = m.replace('"subtle">', '')
m = m.replace('</em>','')
publisher.append(m)
else:
publisher.append(None)
# extract date
match = re.findall(date_pat, str(review))
if len(match) > 0:
date.append(match[0].strip('"'))
else:
date.append(None)
return [reviews, rating, fresh, critic, top_critic, publisher, date]
def _get_num_pages(soup) -> List:
match = re.findall(page_pat,str(list(soup)))
if len(match) > 0:
match = match[0]
match = match.split(' of ')[-1]
return match
else:
return None
def get_critic_reviews(page: str) -> Dict[str, List]:
info = [[],[],[],[],[],[],[]]
soup = _make_soup(page + "reviews")
pages = _get_num_pages(soup)
if pages is not None:
if get_verbose_setting():
print('scraping critic reviews')
print('scraping url: ' + page + "reviews " + str(pages) + " pages to scrape")
for page_num in range(1,int(pages)+1):
soup = _make_soup(page + "reviews?page=" + str(page_num) + "&sort=")
c_info = _get_critic_reviews_from_page(soup)
for i in range(len(c_info)):
info[i] = info[i] + c_info[i]
c_info = dict()
keys = ['reviews', 'rating', 'fresh', 'critic', 'top_critic', 'publisher', 'date']
for k in range(len(keys)):
c_info[keys[k]] = info[k]
if get_verbose_setting():
print('done scraping critic reviews')
else:
c_info = None
return c_info
| true | true |
f73bacaf6a208aeac998313db3bbd4a178bd8fc7 | 12,408 | py | Python | teuthology/worker.py | zhsj/teuthology | 7f11a09f2b7d7406d65f21a85fc2e3db395a95a0 | [
"MIT"
] | null | null | null | teuthology/worker.py | zhsj/teuthology | 7f11a09f2b7d7406d65f21a85fc2e3db395a95a0 | [
"MIT"
] | 1 | 2021-02-23T19:06:55.000Z | 2021-02-23T19:06:55.000Z | teuthology/worker.py | zhsj/teuthology | 7f11a09f2b7d7406d65f21a85fc2e3db395a95a0 | [
"MIT"
] | null | null | null | import logging
import os
import subprocess
import sys
import tempfile
import time
import yaml
from datetime import datetime
from teuthology import setup_log_file, install_except_hook
from . import beanstalk
from . import report
from . import safepath
from .config import config as teuth_config
from .config import set_config_attr
from .exceptions import BranchNotFoundError, SkipJob, MaxWhileTries
from .kill import kill_job
from .repo_utils import fetch_qa_suite, fetch_teuthology
log = logging.getLogger(__name__)
start_time = datetime.utcnow()
restart_file_path = '/tmp/teuthology-restart-workers'
stop_file_path = '/tmp/teuthology-stop-workers'
def sentinel(path):
if not os.path.exists(path):
return False
file_mtime = datetime.utcfromtimestamp(os.path.getmtime(path))
if file_mtime > start_time:
return True
else:
return False
def restart():
log.info('Restarting...')
args = sys.argv[:]
args.insert(0, sys.executable)
os.execv(sys.executable, args)
def stop():
log.info('Stopping...')
sys.exit(0)
def load_config(ctx=None):
teuth_config.load()
if ctx is not None:
if not os.path.isdir(ctx.archive_dir):
sys.exit("{prog}: archive directory must exist: {path}".format(
prog=os.path.basename(sys.argv[0]),
path=ctx.archive_dir,
))
else:
teuth_config.archive_base = ctx.archive_dir
def main(ctx):
loglevel = logging.INFO
if ctx.verbose:
loglevel = logging.DEBUG
log.setLevel(loglevel)
log_file_path = os.path.join(ctx.log_dir, 'worker.{tube}.{pid}'.format(
pid=os.getpid(), tube=ctx.tube,))
setup_log_file(log_file_path)
install_except_hook()
load_config(ctx=ctx)
set_config_attr(ctx)
connection = beanstalk.connect()
beanstalk.watch_tube(connection, ctx.tube)
result_proc = None
if teuth_config.teuthology_path is None:
fetch_teuthology('master')
fetch_qa_suite('master')
keep_running = True
while keep_running:
# Check to see if we have a teuthology-results process hanging around
# and if so, read its return code so that it can exit.
if result_proc is not None and result_proc.poll() is not None:
log.debug("teuthology-results exited with code: %s",
result_proc.returncode)
result_proc = None
if sentinel(restart_file_path):
restart()
elif sentinel(stop_file_path):
stop()
load_config()
job = connection.reserve(timeout=60)
if job is None:
continue
# bury the job so it won't be re-run if it fails
job.bury()
job_id = job.jid
log.info('Reserved job %d', job_id)
log.info('Config is: %s', job.body)
job_config = yaml.safe_load(job.body)
job_config['job_id'] = str(job_id)
if job_config.get('stop_worker'):
keep_running = False
try:
job_config, teuth_bin_path = prep_job(
job_config,
log_file_path,
ctx.archive_dir,
)
run_job(
job_config,
teuth_bin_path,
ctx.archive_dir,
ctx.verbose,
)
except SkipJob:
continue
# This try/except block is to keep the worker from dying when
# beanstalkc throws a SocketError
try:
job.delete()
except Exception:
log.exception("Saw exception while trying to delete job")
def prep_job(job_config, log_file_path, archive_dir):
job_id = job_config['job_id']
safe_archive = safepath.munge(job_config['name'])
job_config['worker_log'] = log_file_path
archive_path_full = os.path.join(
archive_dir, safe_archive, str(job_id))
job_config['archive_path'] = archive_path_full
# If the teuthology branch was not specified, default to master and
# store that value.
teuthology_branch = job_config.get('teuthology_branch', 'master')
job_config['teuthology_branch'] = teuthology_branch
try:
if teuth_config.teuthology_path is not None:
teuth_path = teuth_config.teuthology_path
else:
teuth_path = fetch_teuthology(branch=teuthology_branch)
# For the teuthology tasks, we look for suite_branch, and if we
# don't get that, we look for branch, and fall back to 'master'.
# last-in-suite jobs don't have suite_branch or branch set.
ceph_branch = job_config.get('branch', 'master')
suite_branch = job_config.get('suite_branch', ceph_branch)
suite_repo = job_config.get('suite_repo')
if suite_repo:
teuth_config.ceph_qa_suite_git_url = suite_repo
job_config['suite_path'] = os.path.normpath(os.path.join(
fetch_qa_suite(suite_branch),
job_config.get('suite_relpath', ''),
))
except BranchNotFoundError as exc:
log.exception("Branch not found; marking job as dead")
report.try_push_job_info(
job_config,
dict(status='dead', failure_reason=str(exc))
)
raise SkipJob()
except MaxWhileTries as exc:
log.exception("Failed to fetch or bootstrap; marking job as dead")
report.try_push_job_info(
job_config,
dict(status='dead', failure_reason=str(exc))
)
raise SkipJob()
teuth_bin_path = os.path.join(teuth_path, 'virtualenv', 'bin')
if not os.path.isdir(teuth_bin_path):
raise RuntimeError("teuthology branch %s at %s not bootstrapped!" %
(teuthology_branch, teuth_bin_path))
return job_config, teuth_bin_path
def run_job(job_config, teuth_bin_path, archive_dir, verbose):
safe_archive = safepath.munge(job_config['name'])
if job_config.get('last_in_suite'):
if teuth_config.results_server:
report.try_delete_jobs(job_config['name'], job_config['job_id'])
log.info('Generating results email for %s', job_config['name'])
args = [
os.path.join(teuth_bin_path, 'teuthology-results'),
'--timeout',
str(job_config.get('results_timeout',
teuth_config.results_timeout)),
'--email',
job_config['email'],
'--archive-dir',
os.path.join(archive_dir, safe_archive),
'--name',
job_config['name'],
]
# Execute teuthology-results, passing 'preexec_fn=os.setpgrp' to
# make sure that it will continue to run if this worker process
# dies (e.g. because of a restart)
result_proc = subprocess.Popen(args=args, preexec_fn=os.setpgrp)
log.info("teuthology-results PID: %s", result_proc.pid)
return
log.info('Creating archive dir %s', job_config['archive_path'])
safepath.makedirs('/', job_config['archive_path'])
log.info('Running job %s', job_config['job_id'])
suite_path = job_config['suite_path']
arg = [
os.path.join(teuth_bin_path, 'teuthology'),
]
# The following is for compatibility with older schedulers, from before we
# started merging the contents of job_config['config'] into job_config
# itself.
if 'config' in job_config:
inner_config = job_config.pop('config')
if not isinstance(inner_config, dict):
log.warn("run_job: job_config['config'] isn't a dict, it's a %s",
str(type(inner_config)))
else:
job_config.update(inner_config)
if verbose or job_config['verbose']:
arg.append('-v')
arg.extend([
'--lock',
'--block',
'--owner', job_config['owner'],
'--archive', job_config['archive_path'],
'--name', job_config['name'],
])
if job_config['description'] is not None:
arg.extend(['--description', job_config['description']])
arg.append('--')
with tempfile.NamedTemporaryFile(prefix='teuthology-worker.',
suffix='.tmp',) as tmp:
yaml.safe_dump(data=job_config, stream=tmp)
tmp.flush()
arg.append(tmp.name)
env = os.environ.copy()
python_path = env.get('PYTHONPATH', '')
python_path = ':'.join([suite_path, python_path]).strip(':')
env['PYTHONPATH'] = python_path
log.debug("Running: %s" % ' '.join(arg))
p = subprocess.Popen(args=arg, env=env)
log.info("Job archive: %s", job_config['archive_path'])
log.info("Job PID: %s", str(p.pid))
if teuth_config.results_server:
log.info("Running with watchdog")
try:
run_with_watchdog(p, job_config)
except Exception:
log.exception("run_with_watchdog had an unhandled exception")
raise
else:
log.info("Running without watchdog")
# This sleep() is to give the child time to start up and create the
# archive dir.
time.sleep(5)
symlink_worker_log(job_config['worker_log'],
job_config['archive_path'])
p.wait()
if p.returncode != 0:
log.error('Child exited with code %d', p.returncode)
else:
log.info('Success!')
def run_with_watchdog(process, job_config):
job_start_time = datetime.utcnow()
# Only push the information that's relevant to the watchdog, to save db
# load
job_info = dict(
name=job_config['name'],
job_id=job_config['job_id'],
)
# Sleep once outside of the loop to avoid double-posting jobs
time.sleep(teuth_config.watchdog_interval)
symlink_worker_log(job_config['worker_log'], job_config['archive_path'])
while process.poll() is None:
# Kill jobs that have been running longer than the global max
run_time = datetime.utcnow() - job_start_time
total_seconds = run_time.days * 60 * 60 * 24 + run_time.seconds
if total_seconds > teuth_config.max_job_time:
log.warning("Job ran longer than {max}s. Killing...".format(
max=teuth_config.max_job_time))
kill_job(job_info['name'], job_info['job_id'],
teuth_config.archive_base)
# calling this without a status just updates the jobs updated time
report.try_push_job_info(job_info)
time.sleep(teuth_config.watchdog_interval)
# The job finished. Let's make sure paddles knows.
branches_sans_reporting = ('argonaut', 'bobtail', 'cuttlefish', 'dumpling')
if job_config.get('teuthology_branch') in branches_sans_reporting:
# The job ran with a teuthology branch that may not have the reporting
# feature. Let's call teuthology-report (which will be from the master
# branch) to report the job manually.
cmd = "teuthology-report -v -D -r {run_name} -j {job_id}".format(
run_name=job_info['name'],
job_id=job_info['job_id'])
try:
log.info("Executing %s" % cmd)
report_proc = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
while report_proc.poll() is None:
for line in report_proc.stdout.readlines():
log.info(line.strip())
time.sleep(1)
log.info("Reported results via the teuthology-report command")
except Exception:
log.exception("teuthology-report failed")
else:
# Let's make sure that paddles knows the job is finished. We don't know
# the status, but if it was a pass or fail it will have already been
# reported to paddles. In that case paddles ignores the 'dead' status.
# If the job was killed, paddles will use the 'dead' status.
report.try_push_job_info(job_info, dict(status='dead'))
def symlink_worker_log(worker_log_path, archive_dir):
try:
log.debug("Worker log: %s", worker_log_path)
os.symlink(worker_log_path, os.path.join(archive_dir, 'worker.log'))
except Exception:
log.exception("Failed to symlink worker log")
| 35.757925 | 79 | 0.619278 | import logging
import os
import subprocess
import sys
import tempfile
import time
import yaml
from datetime import datetime
from teuthology import setup_log_file, install_except_hook
from . import beanstalk
from . import report
from . import safepath
from .config import config as teuth_config
from .config import set_config_attr
from .exceptions import BranchNotFoundError, SkipJob, MaxWhileTries
from .kill import kill_job
from .repo_utils import fetch_qa_suite, fetch_teuthology
log = logging.getLogger(__name__)
start_time = datetime.utcnow()
restart_file_path = '/tmp/teuthology-restart-workers'
stop_file_path = '/tmp/teuthology-stop-workers'
def sentinel(path):
if not os.path.exists(path):
return False
file_mtime = datetime.utcfromtimestamp(os.path.getmtime(path))
if file_mtime > start_time:
return True
else:
return False
def restart():
log.info('Restarting...')
args = sys.argv[:]
args.insert(0, sys.executable)
os.execv(sys.executable, args)
def stop():
log.info('Stopping...')
sys.exit(0)
def load_config(ctx=None):
teuth_config.load()
if ctx is not None:
if not os.path.isdir(ctx.archive_dir):
sys.exit("{prog}: archive directory must exist: {path}".format(
prog=os.path.basename(sys.argv[0]),
path=ctx.archive_dir,
))
else:
teuth_config.archive_base = ctx.archive_dir
def main(ctx):
loglevel = logging.INFO
if ctx.verbose:
loglevel = logging.DEBUG
log.setLevel(loglevel)
log_file_path = os.path.join(ctx.log_dir, 'worker.{tube}.{pid}'.format(
pid=os.getpid(), tube=ctx.tube,))
setup_log_file(log_file_path)
install_except_hook()
load_config(ctx=ctx)
set_config_attr(ctx)
connection = beanstalk.connect()
beanstalk.watch_tube(connection, ctx.tube)
result_proc = None
if teuth_config.teuthology_path is None:
fetch_teuthology('master')
fetch_qa_suite('master')
keep_running = True
while keep_running:
if result_proc is not None and result_proc.poll() is not None:
log.debug("teuthology-results exited with code: %s",
result_proc.returncode)
result_proc = None
if sentinel(restart_file_path):
restart()
elif sentinel(stop_file_path):
stop()
load_config()
job = connection.reserve(timeout=60)
if job is None:
continue
job.bury()
job_id = job.jid
log.info('Reserved job %d', job_id)
log.info('Config is: %s', job.body)
job_config = yaml.safe_load(job.body)
job_config['job_id'] = str(job_id)
if job_config.get('stop_worker'):
keep_running = False
try:
job_config, teuth_bin_path = prep_job(
job_config,
log_file_path,
ctx.archive_dir,
)
run_job(
job_config,
teuth_bin_path,
ctx.archive_dir,
ctx.verbose,
)
except SkipJob:
continue
# This try/except block is to keep the worker from dying when
# beanstalkc throws a SocketError
try:
job.delete()
except Exception:
log.exception("Saw exception while trying to delete job")
def prep_job(job_config, log_file_path, archive_dir):
job_id = job_config['job_id']
safe_archive = safepath.munge(job_config['name'])
job_config['worker_log'] = log_file_path
archive_path_full = os.path.join(
archive_dir, safe_archive, str(job_id))
job_config['archive_path'] = archive_path_full
# If the teuthology branch was not specified, default to master and
# store that value.
teuthology_branch = job_config.get('teuthology_branch', 'master')
job_config['teuthology_branch'] = teuthology_branch
try:
if teuth_config.teuthology_path is not None:
teuth_path = teuth_config.teuthology_path
else:
teuth_path = fetch_teuthology(branch=teuthology_branch)
# For the teuthology tasks, we look for suite_branch, and if we
# don't get that, we look for branch, and fall back to 'master'.
ceph_branch = job_config.get('branch', 'master')
suite_branch = job_config.get('suite_branch', ceph_branch)
suite_repo = job_config.get('suite_repo')
if suite_repo:
teuth_config.ceph_qa_suite_git_url = suite_repo
job_config['suite_path'] = os.path.normpath(os.path.join(
fetch_qa_suite(suite_branch),
job_config.get('suite_relpath', ''),
))
except BranchNotFoundError as exc:
log.exception("Branch not found; marking job as dead")
report.try_push_job_info(
job_config,
dict(status='dead', failure_reason=str(exc))
)
raise SkipJob()
except MaxWhileTries as exc:
log.exception("Failed to fetch or bootstrap; marking job as dead")
report.try_push_job_info(
job_config,
dict(status='dead', failure_reason=str(exc))
)
raise SkipJob()
teuth_bin_path = os.path.join(teuth_path, 'virtualenv', 'bin')
if not os.path.isdir(teuth_bin_path):
raise RuntimeError("teuthology branch %s at %s not bootstrapped!" %
(teuthology_branch, teuth_bin_path))
return job_config, teuth_bin_path
def run_job(job_config, teuth_bin_path, archive_dir, verbose):
safe_archive = safepath.munge(job_config['name'])
if job_config.get('last_in_suite'):
if teuth_config.results_server:
report.try_delete_jobs(job_config['name'], job_config['job_id'])
log.info('Generating results email for %s', job_config['name'])
args = [
os.path.join(teuth_bin_path, 'teuthology-results'),
'--timeout',
str(job_config.get('results_timeout',
teuth_config.results_timeout)),
'--email',
job_config['email'],
'--archive-dir',
os.path.join(archive_dir, safe_archive),
'--name',
job_config['name'],
]
# Execute teuthology-results, passing 'preexec_fn=os.setpgrp' to
# make sure that it will continue to run if this worker process
# dies (e.g. because of a restart)
result_proc = subprocess.Popen(args=args, preexec_fn=os.setpgrp)
log.info("teuthology-results PID: %s", result_proc.pid)
return
log.info('Creating archive dir %s', job_config['archive_path'])
safepath.makedirs('/', job_config['archive_path'])
log.info('Running job %s', job_config['job_id'])
suite_path = job_config['suite_path']
arg = [
os.path.join(teuth_bin_path, 'teuthology'),
]
# The following is for compatibility with older schedulers, from before we
# started merging the contents of job_config['config'] into job_config
# itself.
if 'config' in job_config:
inner_config = job_config.pop('config')
if not isinstance(inner_config, dict):
log.warn("run_job: job_config['config'] isn't a dict, it's a %s",
str(type(inner_config)))
else:
job_config.update(inner_config)
if verbose or job_config['verbose']:
arg.append('-v')
arg.extend([
'--lock',
'--block',
'--owner', job_config['owner'],
'--archive', job_config['archive_path'],
'--name', job_config['name'],
])
if job_config['description'] is not None:
arg.extend(['--description', job_config['description']])
arg.append('--')
with tempfile.NamedTemporaryFile(prefix='teuthology-worker.',
suffix='.tmp',) as tmp:
yaml.safe_dump(data=job_config, stream=tmp)
tmp.flush()
arg.append(tmp.name)
env = os.environ.copy()
python_path = env.get('PYTHONPATH', '')
python_path = ':'.join([suite_path, python_path]).strip(':')
env['PYTHONPATH'] = python_path
log.debug("Running: %s" % ' '.join(arg))
p = subprocess.Popen(args=arg, env=env)
log.info("Job archive: %s", job_config['archive_path'])
log.info("Job PID: %s", str(p.pid))
if teuth_config.results_server:
log.info("Running with watchdog")
try:
run_with_watchdog(p, job_config)
except Exception:
log.exception("run_with_watchdog had an unhandled exception")
raise
else:
log.info("Running without watchdog")
# This sleep() is to give the child time to start up and create the
# archive dir.
time.sleep(5)
symlink_worker_log(job_config['worker_log'],
job_config['archive_path'])
p.wait()
if p.returncode != 0:
log.error('Child exited with code %d', p.returncode)
else:
log.info('Success!')
def run_with_watchdog(process, job_config):
job_start_time = datetime.utcnow()
# Only push the information that's relevant to the watchdog, to save db
job_info = dict(
name=job_config['name'],
job_id=job_config['job_id'],
)
time.sleep(teuth_config.watchdog_interval)
symlink_worker_log(job_config['worker_log'], job_config['archive_path'])
while process.poll() is None:
run_time = datetime.utcnow() - job_start_time
total_seconds = run_time.days * 60 * 60 * 24 + run_time.seconds
if total_seconds > teuth_config.max_job_time:
log.warning("Job ran longer than {max}s. Killing...".format(
max=teuth_config.max_job_time))
kill_job(job_info['name'], job_info['job_id'],
teuth_config.archive_base)
report.try_push_job_info(job_info)
time.sleep(teuth_config.watchdog_interval)
branches_sans_reporting = ('argonaut', 'bobtail', 'cuttlefish', 'dumpling')
if job_config.get('teuthology_branch') in branches_sans_reporting:
# The job ran with a teuthology branch that may not have the reporting
# feature. Let's call teuthology-report (which will be from the master
cmd = "teuthology-report -v -D -r {run_name} -j {job_id}".format(
run_name=job_info['name'],
job_id=job_info['job_id'])
try:
log.info("Executing %s" % cmd)
report_proc = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
while report_proc.poll() is None:
for line in report_proc.stdout.readlines():
log.info(line.strip())
time.sleep(1)
log.info("Reported results via the teuthology-report command")
except Exception:
log.exception("teuthology-report failed")
else:
report.try_push_job_info(job_info, dict(status='dead'))
def symlink_worker_log(worker_log_path, archive_dir):
try:
log.debug("Worker log: %s", worker_log_path)
os.symlink(worker_log_path, os.path.join(archive_dir, 'worker.log'))
except Exception:
log.exception("Failed to symlink worker log")
| true | true |
f73bacbf2d3d133eecf2150b7cc24d0d49ff0512 | 6,149 | py | Python | driveshell.py | nygeek/drive_inspector | 447510be1c10c6a7bb6d1068a9b7912544617df7 | [
"Apache-2.0"
] | null | null | null | driveshell.py | nygeek/drive_inspector | 447510be1c10c6a7bb6d1068a9b7912544617df7 | [
"Apache-2.0"
] | null | null | null | driveshell.py | nygeek/drive_inspector | 447510be1c10c6a7bb6d1068a9b7912544617df7 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python3
""" Implementation of the interactive DriveInspector using the DriveFile
class implemented in drivefile.py
Started 2018-05-12 by Marc Donner
Copyright (C) 2018 Marc Donner
"""
import sys
from drivefilecached import DriveFileCached
from drivefilecached import canonicalize_path
from drivefileraw import TestStats
from drivefileraw import handle_ls
from drivefileraw import handle_stat
from drivefileraw import handle_status
from drivefileraw import handle_find
# This may not be needed in Python 3. Check carefully.
# reload(sys)
# sys.setdefaultencoding('utf8')
APPLICATION_NAME = 'Drive Shell'
def handle_cd(drive_file, node_id, show_all):
"""Handle the cd verb by calling set_cwd()."""
if drive_file.debug:
print("# handle_cd(node_id: " + str(node_id) + ",")
print("# show_all: " + str(show_all))
drive_file.set_cwd(node_id)
print("pwd: " + drive_file.get_cwd())
return True
def handle_debug(drive_file, node_id, show_all):
"""Handle the debug verb by toggling the debug flag."""
if drive_file.debug:
print("# handle_debug(node_id: " + str(node_id) + ",")
print("# show_all: " + str(show_all))
drive_file.set_debug(not drive_file.get_debug())
return True
def handle_help(drive_file, node_id, show_all):
"""Handle the help verb by displaying the help text."""
if drive_file.debug:
print("# handle_help(node_id: " + str(node_id) + ",")
print("# show_all: " + str(show_all))
print("driveshell")
print("\n")
print("Commands:")
print(" cd <path>")
print(" debug [Toggles the debug flag.]")
print(" find <path>")
print(" help [displays this help text.]")
print(" ls <path>")
print(" output <path> [set the output file path.]")
print(" pwd")
print(" quit")
print(" stat <path>")
print(" status [Report the DriveFileCached object status.]")
return True
def handle_output(drive_file, node_id, show_all):
"""Handle the output verb by setting an output file path and
opening a new output file."""
if drive_file.debug:
print("# handle_pwd(node_id: " + str(node_id) + ",")
print("# show_all: " + str(show_all))
drive_file.df_set_output(node_id)
print("# output path now: '" + drive_file.output_path + "'")
return True
def handle_pwd(drive_file, node_id, show_all):
"""Handle the pwd verb by displaying the current working directory."""
if drive_file.debug:
print("# handle_pwd(node_id: " + str(node_id) + ",")
print("# show_all: " + str(show_all))
print("pwd: " + drive_file.get_cwd())
return True
def handle_quit(drive_file, node_id, show_all):
"""Handle the quit verb by returning True."""
if drive_file.debug:
print("# handle_quit(node_id: " + str(node_id) + ",")
print("# show_all: " + str(show_all))
return False
def drive_shell(teststats):
"""The shell supporting interactive use of the DriveFileCached
machinery.
"""
# Each command will be structured as VERB NOUN
# The first set of verbs that we will support are:
# ls
# stat
# find
# cd
# pwd
#
# We will also support some state modification commands:
# debug
# cache (dump | clear | reload)
#
# and, of course:
# quit
# for this to work, all of the handlers need the same signature:
# (drive_file, node_id, show_all)
# If a function returns False, then we will exit the main loop
# As of now, only the quit command returns False
# 2018-06-24 Ick ... replacing noun with node_id makes life
# ugly for implementation of cache (dump | clear | reload)
# I *could* break the handlers into two groups - nodeid_handlers
# and noun_handlers and proceed that way. I could leave cd as a
# nodeid handler, since making that change actually improved a
# bunch of stuff in the DriveFileCached class.
startup_report = teststats.report_startup()
print(startup_report)
node_id_handlers = {
'cd': handle_cd,
'find': handle_find,
'ls': handle_ls,
'stat': handle_stat,
}
noun_handlers = {
'debug': handle_debug,
'help': handle_help,
'output': handle_output,
'pwd': handle_pwd,
'status': handle_status,
'quit': handle_quit,
}
drive_file = DriveFileCached(False)
drive_file.df_set_output('stdout')
# Later on add a command line argument to skip the cache
drive_file.load_cache()
running = True
tokens = []
while running:
try:
# Python 3 input() behaves as Python 2 raw_input()
# To get Python 2 input() behavior do eval(input())
# line = raw_input("> ")
line = input("> ")
tokens = line.split(None, 1)
verb = tokens[0].lower() if tokens else ""
noun = "." if len(tokens) <= 1 else tokens[1]
if verb in node_id_handlers.keys():
# Resolve the noun to a node_id
path = canonicalize_path(
drive_file.get_cwd(),
noun,
drive_file.debug
)
node_id = drive_file.resolve_path(path)
running = node_id_handlers[verb](drive_file, node_id, True)
elif verb in noun_handlers.keys():
running = noun_handlers[verb](drive_file, noun, True)
else:
print("Unrecognized command: " + str(verb))
except EOFError:
print("\n# EOF ...")
running = False
drive_file.dump_cache()
print("# call_count: ")
print("# get: " + str(drive_file.call_count['get']))
print("# list_children: " + \
str(drive_file.call_count['list_children']))
wrapup_report = teststats.report_wrapup()
print(wrapup_report)
def main():
"""Test code and basic CLI functionality engine."""
test_stats = TestStats()
drive_shell(test_stats)
if __name__ == '__main__':
main()
| 30.745 | 75 | 0.617661 |
import sys
from drivefilecached import DriveFileCached
from drivefilecached import canonicalize_path
from drivefileraw import TestStats
from drivefileraw import handle_ls
from drivefileraw import handle_stat
from drivefileraw import handle_status
from drivefileraw import handle_find
APPLICATION_NAME = 'Drive Shell'
def handle_cd(drive_file, node_id, show_all):
if drive_file.debug:
print("# handle_cd(node_id: " + str(node_id) + ",")
print("# show_all: " + str(show_all))
drive_file.set_cwd(node_id)
print("pwd: " + drive_file.get_cwd())
return True
def handle_debug(drive_file, node_id, show_all):
if drive_file.debug:
print("# handle_debug(node_id: " + str(node_id) + ",")
print("# show_all: " + str(show_all))
drive_file.set_debug(not drive_file.get_debug())
return True
def handle_help(drive_file, node_id, show_all):
if drive_file.debug:
print("# handle_help(node_id: " + str(node_id) + ",")
print("# show_all: " + str(show_all))
print("driveshell")
print("\n")
print("Commands:")
print(" cd <path>")
print(" debug [Toggles the debug flag.]")
print(" find <path>")
print(" help [displays this help text.]")
print(" ls <path>")
print(" output <path> [set the output file path.]")
print(" pwd")
print(" quit")
print(" stat <path>")
print(" status [Report the DriveFileCached object status.]")
return True
def handle_output(drive_file, node_id, show_all):
if drive_file.debug:
print("# handle_pwd(node_id: " + str(node_id) + ",")
print("# show_all: " + str(show_all))
drive_file.df_set_output(node_id)
print("# output path now: '" + drive_file.output_path + "'")
return True
def handle_pwd(drive_file, node_id, show_all):
if drive_file.debug:
print("# handle_pwd(node_id: " + str(node_id) + ",")
print("# show_all: " + str(show_all))
print("pwd: " + drive_file.get_cwd())
return True
def handle_quit(drive_file, node_id, show_all):
if drive_file.debug:
print("# handle_quit(node_id: " + str(node_id) + ",")
print("# show_all: " + str(show_all))
return False
def drive_shell(teststats):
startup_report = teststats.report_startup()
print(startup_report)
node_id_handlers = {
'cd': handle_cd,
'find': handle_find,
'ls': handle_ls,
'stat': handle_stat,
}
noun_handlers = {
'debug': handle_debug,
'help': handle_help,
'output': handle_output,
'pwd': handle_pwd,
'status': handle_status,
'quit': handle_quit,
}
drive_file = DriveFileCached(False)
drive_file.df_set_output('stdout')
drive_file.load_cache()
running = True
tokens = []
while running:
try:
line = input("> ")
tokens = line.split(None, 1)
verb = tokens[0].lower() if tokens else ""
noun = "." if len(tokens) <= 1 else tokens[1]
if verb in node_id_handlers.keys():
path = canonicalize_path(
drive_file.get_cwd(),
noun,
drive_file.debug
)
node_id = drive_file.resolve_path(path)
running = node_id_handlers[verb](drive_file, node_id, True)
elif verb in noun_handlers.keys():
running = noun_handlers[verb](drive_file, noun, True)
else:
print("Unrecognized command: " + str(verb))
except EOFError:
print("\n# EOF ...")
running = False
drive_file.dump_cache()
print("# call_count: ")
print("# get: " + str(drive_file.call_count['get']))
print("# list_children: " + \
str(drive_file.call_count['list_children']))
wrapup_report = teststats.report_wrapup()
print(wrapup_report)
def main():
test_stats = TestStats()
drive_shell(test_stats)
if __name__ == '__main__':
main()
| true | true |
f73bb057a27de4c93726e9102287fcb9057da455 | 18,729 | py | Python | ceasiompy/utils/WB/UncGeometry/WithFuseGeom/Wings/wingsgeom.py | jphkun/CEASIOMpy | 6425cfeb786019fccfc98aaa2fd676b2de466dac | [
"Apache-2.0"
] | 33 | 2018-11-20T16:34:40.000Z | 2022-03-29T07:26:18.000Z | ceasiompy/utils/WB/UncGeometry/WithFuseGeom/Wings/wingsgeom.py | jphkun/CEASIOMpy | 6425cfeb786019fccfc98aaa2fd676b2de466dac | [
"Apache-2.0"
] | 54 | 2019-09-17T15:57:47.000Z | 2022-03-30T08:12:52.000Z | ceasiompy/utils/WB/UncGeometry/WithFuseGeom/Wings/wingsgeom.py | jphkun/CEASIOMpy | 6425cfeb786019fccfc98aaa2fd676b2de466dac | [
"Apache-2.0"
] | 26 | 2018-11-30T14:33:44.000Z | 2022-03-22T07:30:18.000Z | """
CEASIOMpy: Conceptual Aircraft Design Software
Developed for CFS ENGINEERING, 1015 Lausanne, Switzerland
The script evaluate the wings geometry from cpacs file for an
unconventional aircraft with fuselage.
Python version: >=3.6
| Author : Stefano Piccini
| Date of creation: 2018-09-27
| Last modifiction: 2020-01-22 (AJ)
"""
#==============================================================================
# IMPORTS
#==============================================================================
import numpy as np
import math
import ceasiompy.utils.cpacsfunctions as cpsf
from ceasiompy.utils.ceasiomlogger import get_logger
log = get_logger(__file__.split('.')[0])
#==============================================================================
# CLASSES
#==============================================================================
"""All classes are defined inside the classes folder and in the
InputClasses/Unconventional folder."""
#==============================================================================
# FUNCTIONS
#==============================================================================
def check_segment_connection(wing_plt_area_xz, wing_plt_area_yz, awg, tigl):
""" The function checks for each segment the start and end section index
and to reorder them.
Args:
wing_plt_area_xz (float): Wing area on the xz plane [m^2].
wing_plt_area_yz (float): Wing area on the yz plane [m^2].
awg (class): AircraftGeometry class look at
aircraft_geometry_class.py in the
classes folder for explanation.
tigl (handel): Tigl handle.
Returns:
sec_nb (int): Number of sections for each wing.
start_index (int) : Start section index for each wing.
seg_sec_reordered (float-array): Reordered segments with respective
start and end section for each wing.
sec_index (float_array): List of section index reordered.
"""
log.info('-----------------------------------------------------------')
log.info('---------- Checking wings segments connection -------------')
log.info('-----------------------------------------------------------')
# Initialising arrays
nbmax = np.amax(awg.wing_seg_nb)
seg_sec = np.zeros((nbmax,awg.w_nb,3))
seg_sec_reordered = np.zeros(np.shape(seg_sec))
sec_index = np.zeros((nbmax,awg.w_nb))
start_index = []
sec_nb = []
# First for each segment the start and end section are found, then
# they are reordered considering that the end section of a segment
# is the start sectio of the next one.
# The first section is the one that has the lowest y,
# for horizontal wings, or z, for vertical wings position
# The code works if a section is defined and not used and if the segments
# are not define with a consequential order.
# WARNING The code does not work if a segment is defined
# and then not used.
# The aircraft should be designed along the x axis
# and on the x-y plane
for i in range(1,awg.w_nb+1):
wing_sec_index = []
for j in range(1,awg.wing_seg_nb[i-1]+1):
(s0,e) = tigl.wingGetInnerSectionAndElementIndex(i,j)
(s1,e) = tigl.wingGetOuterSectionAndElementIndex(i,j)
seg_sec[j-1,i-1,0] = s0
seg_sec[j-1,i-1,1] = s1
seg_sec[j-1,i-1,2] = j
(slpx,slpy,slpz) = tigl.wingGetChordPoint(i,1,0.0,0.0)
seg_sec_reordered[0,i-1,:] = seg_sec[0,i-1,:]
start_index.append(1)
for j in range(2,awg.wing_seg_nb[i-1]+1):
(x,y,z) = tigl.wingGetChordPoint(i,j,1.0,0.0)
if (awg.wing_plt_area[i-1] > wing_plt_area_xz[i-1]\
and awg.wing_plt_area[i-1] > wing_plt_area_yz[i-1]):
if y < slpy:
(slpx,slpy,slpz) = (x,y,z)
start_index.append(j)
seg_sec_reordered[0,i-1,:] = seg_sec[j-1,i-1,:]
else:
if z < slpz:
(slpx,slpy,slpz) = (x,y,z)
start_index.append(j)
seg_sec_reordered[0,i-1,:] = seg_sec[j-1,i-1,:]
for j in range(2,awg.wing_seg_nb[i-1]+1):
end_sec = seg_sec_reordered[j-2,i-1,1]
start_next = np.where(seg_sec[:,i-1,0] == end_sec)
seg_sec_reordered[j-1,i-1,:] = seg_sec[start_next[0],i-1,:]
wing_sec_index.append(seg_sec_reordered[0,0,0])
for j in range(2,awg.wing_seg_nb[i-1]+1):
if (seg_sec_reordered[j-1,i-1,0] in wing_sec_index) == False:
wing_sec_index.append(seg_sec_reordered[j-1,i-1,0])
if (seg_sec_reordered[j-1,i-1,1] in wing_sec_index) == False:
wing_sec_index.append(seg_sec_reordered[j-1,i-1,1])
nb = np.shape(wing_sec_index)
if nb[0] > nbmax:
nbmax = nb[0]
sec_index.resize(nbmax,awg.w_nb)
sec_index[0:nb[0],i-1] = wing_sec_index[0:nb[0]]
sec_nb.append(nb[0])
return(sec_nb, start_index, seg_sec_reordered, sec_index)
def get_wing_segment_length(awg, wing_center_section_point):
""" The function evaluates the length of each segment of each wing,
also considering the ones defined using symmetry.
Args:
awg (class): AircraftWingGeometry class look at
aircraft_geometry_class.py in the
classes folder for explanation.
wing_center_section_point (float_array): Central point of each
segment defined at 1/4
of the chord [m, m, m].
Returns:
awg (class): AircraftGeometry class updated.
"""
log.info('-----------------------------------------------------------')
log.info('---------- Evaluating wings segments length ---------------')
log.info('-----------------------------------------------------------')
max_seg_nb = np.amax(awg.wing_seg_nb)
awg.wing_seg_length = np.zeros((max_seg_nb,awg.wing_nb))
# To evaluate the length of each segment, the ditance of central point
# of the start and end section of each segment is computed
a = 0
for i in range(1,awg.w_nb+1):
for j in range(1,awg.wing_seg_nb[i-1]+1):
(x1,y1,z1) = wing_center_section_point[j-1,i-1,:]
(x2,y2,z2) = wing_center_section_point[j,i-1,:]
awg.wing_seg_length[j-1][i+a-1]\
= (math.sqrt((x1-x2)**2+(y1-y2)**2+(z1-z2)**2))
if awg.wing_sym[i-1] != 0:
awg.wing_seg_length[:,i+a] = awg.wing_seg_length[:,i+a-1]
a += 1
return(awg)
def wing_geom_eval(w_nb, TP, awg, cpacs_in):
""" Main function to evaluate the wings geometry
Args:
w_nb (int): Number of wings.
TP (boolean): True if the aircraft is a turboprop.
awg (class): AircraftWingGeometry class look at
aircraft_geometry_class.py in the
classes folder for explanation.
cpacs_in (str): Path to the CPACS file
Returns:
awg (class): AircraftGeometry class updated.
"""
log.info('-----------------------------------------------------------')
log.info('---------- Analysing wing geometry ------------------------')
log.info('-----------------------------------------------------------')
# Opening tixi and tigl
tixi = cpsf.open_tixi(cpacs_in)
tigl = cpsf.open_tigl(tixi)
# INITIALIZATION 1 ---------------------------------------------------------
awg.w_nb = w_nb
awg.wing_nb = w_nb
wing_plt_area_xz = []
wing_plt_area_yz = []
wingUID = []
# Counting sections and segments--------------------------------------------
b = 0
PLT = 0
for i in range(1,awg.w_nb + 1):
double = 1
awg.wing_sym.append(tigl.wingGetSymmetry(i))
if awg.wing_sym[i-1] != 0:
double = 2 # To consider the real amount of wing
# when they are defined using symmetry
awg.wing_nb += 1
awg.wing_sec_nb.append(tigl.wingGetSectionCount(i))
awg.wing_seg_nb.append(tigl.wingGetSegmentCount(i))
awg.wing_vol.append(round(tigl.wingGetVolume(i) * double,3))
# x-y plane
awg.wing_plt_area.append(tigl.wingGetReferenceArea(i,1)*double)
# x-z plane`
wing_plt_area_xz.append(tigl.wingGetReferenceArea(i,2)*double)
# y-z plane
wing_plt_area_yz.append(tigl.wingGetReferenceArea(i,3)*double)
awg.wing_tot_vol = awg.wing_tot_vol + awg.wing_vol[i-1]
wingUID.append(tigl.wingGetUID(i))
awg.wing_span.append(round(tigl.wingGetSpan(wingUID[i-1]),3))
a = np.amax(awg.wing_span)
# Evaluating the index that corresponds to the main wing
if awg.wing_plt_area[i-1] > wing_plt_area_xz[i-1] and\
awg.wing_plt_area[i-1] > wing_plt_area_yz[i-1]:
PLT += 1
if a > b:
awg.main_wing_index = i
b = a
# Checking segment and section connection and reordering them
(awg.wing_sec_nb, start_index, seg_sec, wing_sec_index)\
= check_segment_connection(wing_plt_area_xz, wing_plt_area_yz,\
awg, tigl)
# INITIALIZATION 2 ---------------------------------------------------------
max_wing_sec_nb = np.amax(awg.wing_sec_nb)
max_wing_seg_nb = np.amax(awg.wing_seg_nb)
wing_center_section_point = np.zeros((max_wing_sec_nb, awg.w_nb, 3))
awg.wing_center_seg_point = np.zeros((max_wing_seg_nb, awg.wing_nb, 3))
awg.wing_seg_vol = np.zeros((max_wing_seg_nb, awg.w_nb))
awg.wing_fuel_seg_vol = np.zeros((max_wing_seg_nb, awg.w_nb))
awg.wing_fuel_vol = 0
awg.wing_mac = np.zeros((4, awg.w_nb))
awg.wing_sec_thicknes = np.zeros((max_wing_sec_nb+1, awg.w_nb))
# WING ANALYSIS --------------------------------------------------------------
# Main wing plantform area
awg.wing_plt_area_main = round(awg.wing_plt_area[awg.main_wing_index-1],3)
# Wing: MAC,chords,thicknes,span,plantform area ------------------------------
for i in range(1,awg.w_nb+1):
mac = tigl.wingGetMAC(wingUID[i-1])
(wpx,wpy,wpz) = tigl.wingGetChordPoint(i,1,0.0,0.0)
(wpx2,wpy2,wpz2) = tigl.wingGetChordPoint(i,1,0.0,1.0)
awg.wing_max_chord.append(np.sqrt((wpx2-wpx)**2 + (wpy2-wpy)**2\
+ (wpz2-wpz)**2))
(wpx,wpy,wpz) = tigl.wingGetChordPoint(i,awg.wing_seg_nb[i-1],1.0,0.0)
(wpx2,wpy2,wpz2) = tigl.wingGetChordPoint(i,awg.wing_seg_nb[i-1],\
1.0,1.0)
awg.wing_min_chord.append(np.sqrt((wpx2-wpx)**2 + (wpy2-wpy)**2\
+ (wpz2-wpz)**2) )
for k in range(1,5):
awg.wing_mac[k-1][i-1] = mac[k-1]
for jj in range(1,awg.wing_seg_nb[i-1]+1):
j = int(seg_sec[jj-1,i-1,2])
cle = tigl.wingGetChordPoint(i,j,0.0,0.0)
awg.wing_seg_vol[j-1][i-1] = tigl.wingGetSegmentVolume(i,j)
lp = tigl.wingGetLowerPoint(i,j,0.0,0.0)
up = tigl.wingGetUpperPoint(i,j,0.0,0.0)
if np.all(cle == lp):
L = 0.25
else:
L = 0.75
if np.all(cle == up):
U = 0.25
else:
U = 0.75
(wplx, wply, wplz) = tigl.wingGetLowerPoint(i,j,0.0,L)
(wpux, wpuy, wpuz) = tigl.wingGetUpperPoint(i,j,0.0,U)
wing_center_section_point[j-1][i-1][0] = (wplx+wpux) / 2
wing_center_section_point[j-1][i-1][1] = (wply+wpuy) / 2
wing_center_section_point[j-1][i-1][2] = (wplz+wpuz) / 2
awg.wing_sec_thicknes[j-1][i-1] = np.sqrt((wpux-wplx)**2\
+ (wpuy-wply)**2 + (wpuz-wplz)**2)
j = int(seg_sec[awg.wing_seg_nb[i-1]-1,i-1,2])
(wplx, wply, wplz) = tigl.wingGetLowerPoint(\
i,awg.wing_seg_nb[i-1],1.0,L)
(wpux, wpuy, wpuz) = tigl.wingGetUpperPoint(\
i,awg.wing_seg_nb[i-1],1.0,U)
awg.wing_sec_thicknes[j][i-1] = np.sqrt((wpux-wplx)**2\
+ (wpuy-wply)**2 + (wpuz-wplz)**2)
wing_center_section_point[awg.wing_seg_nb[i-1]][i-1][0] = (wplx+wpux)/2
wing_center_section_point[awg.wing_seg_nb[i-1]][i-1][1] = (wply+wpuy)/2
wing_center_section_point[awg.wing_seg_nb[i-1]][i-1][2] = (wplz+wpuz)/2
awg.wing_sec_mean_thick.append(np.mean(\
awg.wing_sec_thicknes[0:awg.wing_seg_nb[i-1]+1,i-1]))
# Evaluating wing fuel tank volume and if the wing is horizontal or vertical
if awg.wing_plt_area[i-1] > wing_plt_area_xz[i-1] and\
awg.wing_plt_area[i-1] > wing_plt_area_yz[i-1]:
tp_ratio = awg.wing_min_chord[i-1]/awg.wing_max_chord[i-1]
if TP:
corr = -0.05
else:
corr = 0.0
if PLT == 1:
corr += 0.05
if tp_ratio * awg.wing_plt_area[i-1] > 80:
awg.wing_fuel_vol += round(awg.wing_vol[i-1] * (0.7+corr),2)
elif tp_ratio * awg.wing_plt_area[i-1] > 40:
awg.wing_fuel_vol += round(awg.wing_vol[i-1] * (0.65+corr),2)
elif tp_ratio * awg.wing_plt_area[i-1] > 10:
awg.wing_fuel_vol += round(awg.wing_vol[i-1] * (0.55+corr),2)
else:
awg.wing_fuel_vol += 0
for j in seg_sec[:,i-1,2]:
if j == 0.0:
break
awg.wing_fuel_seg_vol[int(j)-1][i-1]\
= round((awg.wing_seg_vol[int(j)-1][i-1]\
/(sum(awg.wing_vol))) * awg.wing_fuel_vol,2)
awg.is_horiz.append(True)
if awg.wing_sym[i-1] != 0:
awg.is_horiz.append(True)
else:
awg.is_horiz.append(False)
if awg.wing_sym[i-1] != 0:
awg.is_horiz.append(False)
# Wing segment length evaluatin function
awg = get_wing_segment_length(awg,wing_center_section_point)
awg.w_seg_sec = seg_sec
# Wings wetted area
awg.tail_wings_surface = []
for i in range(1, awg.w_nb+1):
a = str(wingUID[i-1])
s = tigl.wingGetSurfaceArea(i)
if awg.wing_sym[i-1] != 0:
s *= 2
if i == awg.main_wing_index:
awg.main_wing_surface = s
else:
awg.tail_wings_surface.append(s)
awg.total_wings_surface += s
# Evaluating the point at the center of each segment, the center
# is placed at 1/4 of the chord, symmetry is considered.
a = 0
c = False
for i in range(1,int(awg.wing_nb)+1):
if c:
c = False
continue
for jj in range(1,awg.wing_seg_nb[i-a-1]+1):
j = int(seg_sec[jj-1,i-a-1,2])
awg.wing_center_seg_point[j-1][i-1][0]\
= (wing_center_section_point[j-1][i-a-1][0]\
+ wing_center_section_point[j][i-a-1][0])/2
awg.wing_center_seg_point[j-1][i-1][1]\
= (wing_center_section_point[j-1][i-a-1][1]\
+ wing_center_section_point[j][i-a-1][1])/2
awg.wing_center_seg_point[j-1][i-1][2]\
= (wing_center_section_point[j-1][i-a-1][2]\
+ wing_center_section_point[j][i-a-1][2])/2
if awg.wing_sym[i-1-a] != 0:
if awg.wing_sym[i-1-a] == 1:
symy = 1
symx = 1
symz = -1
if awg.wing_sym[i-1-a] == 2:
symy = -1
symx = 1
symz = 1
if awg.wing_sym[i-1-a] == 3:
symy = 1
symx = -1
symz = 1
awg.wing_center_seg_point[:,i,0]\
= awg.wing_center_seg_point[:,i-1,0] * symx
awg.wing_center_seg_point[:,i,1]\
= awg.wing_center_seg_point[:,i-1,1] * symy
awg.wing_center_seg_point[:,i,2]\
= awg.wing_center_seg_point[:,i-1,2] * symz
c = True
a += 1
cpsf.close_tixi(tixi, cpacs_in)
# log info display ---------------------------------------------------------
log.info('-----------------------------------------------------------')
log.info('---------- Wing Geometry Evaluation -----------------------')
log.info('---------- USEFUL INFO ------------------------------------')
log.info('If wing number is greater than 1 the informations of each obj \
are listed in an array ordered progressively')
log.info('Number of Wings [-]: ' + str(awg.wing_nb))
log.info('Wing symmetry plane [-]: ' + str(awg.wing_sym))
log.info('Number of wing sections (not counting symmetry) [-]: ' + str(awg.wing_sec_nb))
log.info('Number of wing segments (not counting symmetry) [-]: ' + str(awg.wing_seg_nb))
log.info('Wing Span (counting symmetry)[m]: \n' + str(awg.wing_span))
log.info('Wing MAC length [m]: ' + str(awg.wing_mac[0,]))
log.info('Wing MAC x,y,z coordinate [m]: \n' + str(awg.wing_mac[1:4,]))
log.info('Wings sections thicknes [m]: \n' + str(awg.wing_sec_thicknes))
log.info('Wings sections mean thicknes [m]: \n' + str(awg.wing_sec_mean_thick))
log.info('Wing segments length [m]: \n' + str(awg.wing_seg_length))
log.info('Wing max chord length [m]: \n' + str(awg.wing_max_chord))
log.info('Wing min chord length [m]: \n' + str(awg.wing_min_chord))
log.info('Main wing plantform area [m^2]: ' + str(awg.wing_plt_area_main))
log.info('Main wing wetted surface [m^2]: ' + str(awg.main_wing_surface))
log.info('Tail wings wetted surface [m^2]: \n' + str(awg.tail_wings_surface))
log.info('Wings plantform area [m^2]: \n' + str(awg.wing_plt_area))
log.info('Volume of each wing [m^3]: ' + str(awg.wing_vol))
log.info('Total wing volume [m^3]: ' + str(awg.wing_tot_vol))
log.info('Fuel volume in the wing [m^3]:' + str(awg.wing_fuel_vol))
log.info('Total fuel Volume [m^3]:' + str(awg.fuel_vol_tot))
log.info('-----------------------------------------------------------')
return(awg)
#==============================================================================
# MAIN
#==============================================================================
if __name__ == '__main__':
log.warning('###########################################################')
log.warning('# ERROR NOT A STANDALONE PROGRAM, RUN balanceuncmain.py #')
log.warning('###########################################################')
| 42.565909 | 92 | 0.527738 |
import numpy as np
import math
import ceasiompy.utils.cpacsfunctions as cpsf
from ceasiompy.utils.ceasiomlogger import get_logger
log = get_logger(__file__.split('.')[0])
def check_segment_connection(wing_plt_area_xz, wing_plt_area_yz, awg, tigl):
log.info('-----------------------------------------------------------')
log.info('---------- Checking wings segments connection -------------')
log.info('-----------------------------------------------------------')
nbmax = np.amax(awg.wing_seg_nb)
seg_sec = np.zeros((nbmax,awg.w_nb,3))
seg_sec_reordered = np.zeros(np.shape(seg_sec))
sec_index = np.zeros((nbmax,awg.w_nb))
start_index = []
sec_nb = []
for i in range(1,awg.w_nb+1):
wing_sec_index = []
for j in range(1,awg.wing_seg_nb[i-1]+1):
(s0,e) = tigl.wingGetInnerSectionAndElementIndex(i,j)
(s1,e) = tigl.wingGetOuterSectionAndElementIndex(i,j)
seg_sec[j-1,i-1,0] = s0
seg_sec[j-1,i-1,1] = s1
seg_sec[j-1,i-1,2] = j
(slpx,slpy,slpz) = tigl.wingGetChordPoint(i,1,0.0,0.0)
seg_sec_reordered[0,i-1,:] = seg_sec[0,i-1,:]
start_index.append(1)
for j in range(2,awg.wing_seg_nb[i-1]+1):
(x,y,z) = tigl.wingGetChordPoint(i,j,1.0,0.0)
if (awg.wing_plt_area[i-1] > wing_plt_area_xz[i-1]\
and awg.wing_plt_area[i-1] > wing_plt_area_yz[i-1]):
if y < slpy:
(slpx,slpy,slpz) = (x,y,z)
start_index.append(j)
seg_sec_reordered[0,i-1,:] = seg_sec[j-1,i-1,:]
else:
if z < slpz:
(slpx,slpy,slpz) = (x,y,z)
start_index.append(j)
seg_sec_reordered[0,i-1,:] = seg_sec[j-1,i-1,:]
for j in range(2,awg.wing_seg_nb[i-1]+1):
end_sec = seg_sec_reordered[j-2,i-1,1]
start_next = np.where(seg_sec[:,i-1,0] == end_sec)
seg_sec_reordered[j-1,i-1,:] = seg_sec[start_next[0],i-1,:]
wing_sec_index.append(seg_sec_reordered[0,0,0])
for j in range(2,awg.wing_seg_nb[i-1]+1):
if (seg_sec_reordered[j-1,i-1,0] in wing_sec_index) == False:
wing_sec_index.append(seg_sec_reordered[j-1,i-1,0])
if (seg_sec_reordered[j-1,i-1,1] in wing_sec_index) == False:
wing_sec_index.append(seg_sec_reordered[j-1,i-1,1])
nb = np.shape(wing_sec_index)
if nb[0] > nbmax:
nbmax = nb[0]
sec_index.resize(nbmax,awg.w_nb)
sec_index[0:nb[0],i-1] = wing_sec_index[0:nb[0]]
sec_nb.append(nb[0])
return(sec_nb, start_index, seg_sec_reordered, sec_index)
def get_wing_segment_length(awg, wing_center_section_point):
log.info('-----------------------------------------------------------')
log.info('---------- Evaluating wings segments length ---------------')
log.info('-----------------------------------------------------------')
max_seg_nb = np.amax(awg.wing_seg_nb)
awg.wing_seg_length = np.zeros((max_seg_nb,awg.wing_nb))
a = 0
for i in range(1,awg.w_nb+1):
for j in range(1,awg.wing_seg_nb[i-1]+1):
(x1,y1,z1) = wing_center_section_point[j-1,i-1,:]
(x2,y2,z2) = wing_center_section_point[j,i-1,:]
awg.wing_seg_length[j-1][i+a-1]\
= (math.sqrt((x1-x2)**2+(y1-y2)**2+(z1-z2)**2))
if awg.wing_sym[i-1] != 0:
awg.wing_seg_length[:,i+a] = awg.wing_seg_length[:,i+a-1]
a += 1
return(awg)
def wing_geom_eval(w_nb, TP, awg, cpacs_in):
log.info('-----------------------------------------------------------')
log.info('---------- Analysing wing geometry ------------------------')
log.info('-----------------------------------------------------------')
tixi = cpsf.open_tixi(cpacs_in)
tigl = cpsf.open_tigl(tixi)
awg.w_nb = w_nb
awg.wing_nb = w_nb
wing_plt_area_xz = []
wing_plt_area_yz = []
wingUID = []
b = 0
PLT = 0
for i in range(1,awg.w_nb + 1):
double = 1
awg.wing_sym.append(tigl.wingGetSymmetry(i))
if awg.wing_sym[i-1] != 0:
double = 2
awg.wing_nb += 1
awg.wing_sec_nb.append(tigl.wingGetSectionCount(i))
awg.wing_seg_nb.append(tigl.wingGetSegmentCount(i))
awg.wing_vol.append(round(tigl.wingGetVolume(i) * double,3))
awg.wing_plt_area.append(tigl.wingGetReferenceArea(i,1)*double)
wing_plt_area_xz.append(tigl.wingGetReferenceArea(i,2)*double)
wing_plt_area_yz.append(tigl.wingGetReferenceArea(i,3)*double)
awg.wing_tot_vol = awg.wing_tot_vol + awg.wing_vol[i-1]
wingUID.append(tigl.wingGetUID(i))
awg.wing_span.append(round(tigl.wingGetSpan(wingUID[i-1]),3))
a = np.amax(awg.wing_span)
if awg.wing_plt_area[i-1] > wing_plt_area_xz[i-1] and\
awg.wing_plt_area[i-1] > wing_plt_area_yz[i-1]:
PLT += 1
if a > b:
awg.main_wing_index = i
b = a
(awg.wing_sec_nb, start_index, seg_sec, wing_sec_index)\
= check_segment_connection(wing_plt_area_xz, wing_plt_area_yz,\
awg, tigl)
max_wing_sec_nb = np.amax(awg.wing_sec_nb)
max_wing_seg_nb = np.amax(awg.wing_seg_nb)
wing_center_section_point = np.zeros((max_wing_sec_nb, awg.w_nb, 3))
awg.wing_center_seg_point = np.zeros((max_wing_seg_nb, awg.wing_nb, 3))
awg.wing_seg_vol = np.zeros((max_wing_seg_nb, awg.w_nb))
awg.wing_fuel_seg_vol = np.zeros((max_wing_seg_nb, awg.w_nb))
awg.wing_fuel_vol = 0
awg.wing_mac = np.zeros((4, awg.w_nb))
awg.wing_sec_thicknes = np.zeros((max_wing_sec_nb+1, awg.w_nb))
awg.wing_plt_area_main = round(awg.wing_plt_area[awg.main_wing_index-1],3)
for i in range(1,awg.w_nb+1):
mac = tigl.wingGetMAC(wingUID[i-1])
(wpx,wpy,wpz) = tigl.wingGetChordPoint(i,1,0.0,0.0)
(wpx2,wpy2,wpz2) = tigl.wingGetChordPoint(i,1,0.0,1.0)
awg.wing_max_chord.append(np.sqrt((wpx2-wpx)**2 + (wpy2-wpy)**2\
+ (wpz2-wpz)**2))
(wpx,wpy,wpz) = tigl.wingGetChordPoint(i,awg.wing_seg_nb[i-1],1.0,0.0)
(wpx2,wpy2,wpz2) = tigl.wingGetChordPoint(i,awg.wing_seg_nb[i-1],\
1.0,1.0)
awg.wing_min_chord.append(np.sqrt((wpx2-wpx)**2 + (wpy2-wpy)**2\
+ (wpz2-wpz)**2) )
for k in range(1,5):
awg.wing_mac[k-1][i-1] = mac[k-1]
for jj in range(1,awg.wing_seg_nb[i-1]+1):
j = int(seg_sec[jj-1,i-1,2])
cle = tigl.wingGetChordPoint(i,j,0.0,0.0)
awg.wing_seg_vol[j-1][i-1] = tigl.wingGetSegmentVolume(i,j)
lp = tigl.wingGetLowerPoint(i,j,0.0,0.0)
up = tigl.wingGetUpperPoint(i,j,0.0,0.0)
if np.all(cle == lp):
L = 0.25
else:
L = 0.75
if np.all(cle == up):
U = 0.25
else:
U = 0.75
(wplx, wply, wplz) = tigl.wingGetLowerPoint(i,j,0.0,L)
(wpux, wpuy, wpuz) = tigl.wingGetUpperPoint(i,j,0.0,U)
wing_center_section_point[j-1][i-1][0] = (wplx+wpux) / 2
wing_center_section_point[j-1][i-1][1] = (wply+wpuy) / 2
wing_center_section_point[j-1][i-1][2] = (wplz+wpuz) / 2
awg.wing_sec_thicknes[j-1][i-1] = np.sqrt((wpux-wplx)**2\
+ (wpuy-wply)**2 + (wpuz-wplz)**2)
j = int(seg_sec[awg.wing_seg_nb[i-1]-1,i-1,2])
(wplx, wply, wplz) = tigl.wingGetLowerPoint(\
i,awg.wing_seg_nb[i-1],1.0,L)
(wpux, wpuy, wpuz) = tigl.wingGetUpperPoint(\
i,awg.wing_seg_nb[i-1],1.0,U)
awg.wing_sec_thicknes[j][i-1] = np.sqrt((wpux-wplx)**2\
+ (wpuy-wply)**2 + (wpuz-wplz)**2)
wing_center_section_point[awg.wing_seg_nb[i-1]][i-1][0] = (wplx+wpux)/2
wing_center_section_point[awg.wing_seg_nb[i-1]][i-1][1] = (wply+wpuy)/2
wing_center_section_point[awg.wing_seg_nb[i-1]][i-1][2] = (wplz+wpuz)/2
awg.wing_sec_mean_thick.append(np.mean(\
awg.wing_sec_thicknes[0:awg.wing_seg_nb[i-1]+1,i-1]))
if awg.wing_plt_area[i-1] > wing_plt_area_xz[i-1] and\
awg.wing_plt_area[i-1] > wing_plt_area_yz[i-1]:
tp_ratio = awg.wing_min_chord[i-1]/awg.wing_max_chord[i-1]
if TP:
corr = -0.05
else:
corr = 0.0
if PLT == 1:
corr += 0.05
if tp_ratio * awg.wing_plt_area[i-1] > 80:
awg.wing_fuel_vol += round(awg.wing_vol[i-1] * (0.7+corr),2)
elif tp_ratio * awg.wing_plt_area[i-1] > 40:
awg.wing_fuel_vol += round(awg.wing_vol[i-1] * (0.65+corr),2)
elif tp_ratio * awg.wing_plt_area[i-1] > 10:
awg.wing_fuel_vol += round(awg.wing_vol[i-1] * (0.55+corr),2)
else:
awg.wing_fuel_vol += 0
for j in seg_sec[:,i-1,2]:
if j == 0.0:
break
awg.wing_fuel_seg_vol[int(j)-1][i-1]\
= round((awg.wing_seg_vol[int(j)-1][i-1]\
/(sum(awg.wing_vol))) * awg.wing_fuel_vol,2)
awg.is_horiz.append(True)
if awg.wing_sym[i-1] != 0:
awg.is_horiz.append(True)
else:
awg.is_horiz.append(False)
if awg.wing_sym[i-1] != 0:
awg.is_horiz.append(False)
awg = get_wing_segment_length(awg,wing_center_section_point)
awg.w_seg_sec = seg_sec
awg.tail_wings_surface = []
for i in range(1, awg.w_nb+1):
a = str(wingUID[i-1])
s = tigl.wingGetSurfaceArea(i)
if awg.wing_sym[i-1] != 0:
s *= 2
if i == awg.main_wing_index:
awg.main_wing_surface = s
else:
awg.tail_wings_surface.append(s)
awg.total_wings_surface += s
a = 0
c = False
for i in range(1,int(awg.wing_nb)+1):
if c:
c = False
continue
for jj in range(1,awg.wing_seg_nb[i-a-1]+1):
j = int(seg_sec[jj-1,i-a-1,2])
awg.wing_center_seg_point[j-1][i-1][0]\
= (wing_center_section_point[j-1][i-a-1][0]\
+ wing_center_section_point[j][i-a-1][0])/2
awg.wing_center_seg_point[j-1][i-1][1]\
= (wing_center_section_point[j-1][i-a-1][1]\
+ wing_center_section_point[j][i-a-1][1])/2
awg.wing_center_seg_point[j-1][i-1][2]\
= (wing_center_section_point[j-1][i-a-1][2]\
+ wing_center_section_point[j][i-a-1][2])/2
if awg.wing_sym[i-1-a] != 0:
if awg.wing_sym[i-1-a] == 1:
symy = 1
symx = 1
symz = -1
if awg.wing_sym[i-1-a] == 2:
symy = -1
symx = 1
symz = 1
if awg.wing_sym[i-1-a] == 3:
symy = 1
symx = -1
symz = 1
awg.wing_center_seg_point[:,i,0]\
= awg.wing_center_seg_point[:,i-1,0] * symx
awg.wing_center_seg_point[:,i,1]\
= awg.wing_center_seg_point[:,i-1,1] * symy
awg.wing_center_seg_point[:,i,2]\
= awg.wing_center_seg_point[:,i-1,2] * symz
c = True
a += 1
cpsf.close_tixi(tixi, cpacs_in)
log.info('-----------------------------------------------------------')
log.info('---------- Wing Geometry Evaluation -----------------------')
log.info('---------- USEFUL INFO ------------------------------------')
log.info('If wing number is greater than 1 the informations of each obj \
are listed in an array ordered progressively')
log.info('Number of Wings [-]: ' + str(awg.wing_nb))
log.info('Wing symmetry plane [-]: ' + str(awg.wing_sym))
log.info('Number of wing sections (not counting symmetry) [-]: ' + str(awg.wing_sec_nb))
log.info('Number of wing segments (not counting symmetry) [-]: ' + str(awg.wing_seg_nb))
log.info('Wing Span (counting symmetry)[m]: \n' + str(awg.wing_span))
log.info('Wing MAC length [m]: ' + str(awg.wing_mac[0,]))
log.info('Wing MAC x,y,z coordinate [m]: \n' + str(awg.wing_mac[1:4,]))
log.info('Wings sections thicknes [m]: \n' + str(awg.wing_sec_thicknes))
log.info('Wings sections mean thicknes [m]: \n' + str(awg.wing_sec_mean_thick))
log.info('Wing segments length [m]: \n' + str(awg.wing_seg_length))
log.info('Wing max chord length [m]: \n' + str(awg.wing_max_chord))
log.info('Wing min chord length [m]: \n' + str(awg.wing_min_chord))
log.info('Main wing plantform area [m^2]: ' + str(awg.wing_plt_area_main))
log.info('Main wing wetted surface [m^2]: ' + str(awg.main_wing_surface))
log.info('Tail wings wetted surface [m^2]: \n' + str(awg.tail_wings_surface))
log.info('Wings plantform area [m^2]: \n' + str(awg.wing_plt_area))
log.info('Volume of each wing [m^3]: ' + str(awg.wing_vol))
log.info('Total wing volume [m^3]: ' + str(awg.wing_tot_vol))
log.info('Fuel volume in the wing [m^3]:' + str(awg.wing_fuel_vol))
log.info('Total fuel Volume [m^3]:' + str(awg.fuel_vol_tot))
log.info('-----------------------------------------------------------')
return(awg)
if __name__ == '__main__':
log.warning('###########################################################')
log.warning('# ERROR NOT A STANDALONE PROGRAM, RUN balanceuncmain.py #')
log.warning('###########################################################')
| true | true |
f73bb09b509696101ab4faddbf949f66ebb72e15 | 3,046 | py | Python | homeassistant/components/ebusd/sensor.py | zalke/home-assistant | a31e49c857722c0723dc5297cd83cbce0f8716f6 | [
"Apache-2.0"
] | 4 | 2019-07-03T22:36:57.000Z | 2019-08-10T15:33:25.000Z | homeassistant/components/ebusd/sensor.py | zalke/home-assistant | a31e49c857722c0723dc5297cd83cbce0f8716f6 | [
"Apache-2.0"
] | 7 | 2019-08-23T05:26:02.000Z | 2022-03-11T23:57:18.000Z | homeassistant/components/ebusd/sensor.py | zalke/home-assistant | a31e49c857722c0723dc5297cd83cbce0f8716f6 | [
"Apache-2.0"
] | 3 | 2019-04-28T16:35:45.000Z | 2020-05-28T15:21:59.000Z | """Support for Ebusd sensors."""
import logging
import datetime
from homeassistant.helpers.entity import Entity
from .const import DOMAIN
TIME_FRAME1_BEGIN = 'time_frame1_begin'
TIME_FRAME1_END = 'time_frame1_end'
TIME_FRAME2_BEGIN = 'time_frame2_begin'
TIME_FRAME2_END = 'time_frame2_end'
TIME_FRAME3_BEGIN = 'time_frame3_begin'
TIME_FRAME3_END = 'time_frame3_end'
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Ebus sensor."""
ebusd_api = hass.data[DOMAIN]
monitored_conditions = discovery_info['monitored_conditions']
name = discovery_info['client_name']
dev = []
for condition in monitored_conditions:
dev.append(EbusdSensor(
ebusd_api, discovery_info['sensor_types'][condition], name))
add_entities(dev, True)
class EbusdSensor(Entity):
"""Ebusd component sensor methods definition."""
def __init__(self, data, sensor, name):
"""Initialize the sensor."""
self._state = None
self._client_name = name
self._name, self._unit_of_measurement, self._icon, self._type = sensor
self.data = data
@property
def name(self):
"""Return the name of the sensor."""
return '{} {}'.format(self._client_name, self._name)
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def device_state_attributes(self):
"""Return the device state attributes."""
if self._type == 1 and self._state is not None:
schedule = {
TIME_FRAME1_BEGIN: None,
TIME_FRAME1_END: None,
TIME_FRAME2_BEGIN: None,
TIME_FRAME2_END: None,
TIME_FRAME3_BEGIN: None,
TIME_FRAME3_END: None
}
time_frame = self._state.split(';')
for index, item in enumerate(sorted(schedule.items())):
if index < len(time_frame):
parsed = datetime.datetime.strptime(
time_frame[index], '%H:%M')
parsed = parsed.replace(
datetime.datetime.now().year,
datetime.datetime.now().month,
datetime.datetime.now().day)
schedule[item[0]] = parsed.isoformat()
return schedule
return None
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return self._unit_of_measurement
def update(self):
"""Fetch new state data for the sensor."""
try:
self.data.update(self._name, self._type)
if self._name not in self.data.value:
return
self._state = self.data.value[self._name]
except RuntimeError:
_LOGGER.debug("EbusdData.update exception")
| 31.081633 | 78 | 0.605384 | import logging
import datetime
from homeassistant.helpers.entity import Entity
from .const import DOMAIN
TIME_FRAME1_BEGIN = 'time_frame1_begin'
TIME_FRAME1_END = 'time_frame1_end'
TIME_FRAME2_BEGIN = 'time_frame2_begin'
TIME_FRAME2_END = 'time_frame2_end'
TIME_FRAME3_BEGIN = 'time_frame3_begin'
TIME_FRAME3_END = 'time_frame3_end'
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
ebusd_api = hass.data[DOMAIN]
monitored_conditions = discovery_info['monitored_conditions']
name = discovery_info['client_name']
dev = []
for condition in monitored_conditions:
dev.append(EbusdSensor(
ebusd_api, discovery_info['sensor_types'][condition], name))
add_entities(dev, True)
class EbusdSensor(Entity):
def __init__(self, data, sensor, name):
self._state = None
self._client_name = name
self._name, self._unit_of_measurement, self._icon, self._type = sensor
self.data = data
@property
def name(self):
return '{} {}'.format(self._client_name, self._name)
@property
def state(self):
return self._state
@property
def device_state_attributes(self):
if self._type == 1 and self._state is not None:
schedule = {
TIME_FRAME1_BEGIN: None,
TIME_FRAME1_END: None,
TIME_FRAME2_BEGIN: None,
TIME_FRAME2_END: None,
TIME_FRAME3_BEGIN: None,
TIME_FRAME3_END: None
}
time_frame = self._state.split(';')
for index, item in enumerate(sorted(schedule.items())):
if index < len(time_frame):
parsed = datetime.datetime.strptime(
time_frame[index], '%H:%M')
parsed = parsed.replace(
datetime.datetime.now().year,
datetime.datetime.now().month,
datetime.datetime.now().day)
schedule[item[0]] = parsed.isoformat()
return schedule
return None
@property
def icon(self):
return self._icon
@property
def unit_of_measurement(self):
return self._unit_of_measurement
def update(self):
try:
self.data.update(self._name, self._type)
if self._name not in self.data.value:
return
self._state = self.data.value[self._name]
except RuntimeError:
_LOGGER.debug("EbusdData.update exception")
| true | true |
f73bb0e7631b8679aea8df524130f4386f13cdca | 78,203 | py | Python | rx7/__init__.py | Ramin-RX7/RX7-Lib | 28d2c4bc316b031bb05700c72e5119a7ff2d0ae7 | [
"MIT"
] | 6 | 2020-03-18T13:30:12.000Z | 2020-09-23T21:27:42.000Z | rx7/__init__.py | Ramin-RX7/RX7-Lib | 28d2c4bc316b031bb05700c72e5119a7ff2d0ae7 | [
"MIT"
] | null | null | null | rx7/__init__.py | Ramin-RX7/RX7-Lib | 28d2c4bc316b031bb05700c72e5119a7ff2d0ae7 | [
"MIT"
] | null | null | null | '''
This Module is One to Make Your Code Shorter.
High API Will Make You Feel You're Ordering And Machine Is Doing!
Also There is Collection of most usefull function and methods from popular modules of python.
(Read Help of Functions)
Official Documention Will Be Added Soon.
'''
'''
Written By RX
Last Update: 1-15-2021
'''
__version__ = '3.0.0'
"""
< Release Changes >
- style.log_ now have all time prefix by default
- call=call_later
- system.mac_address
- io.selective_input choices can be dict
- Class Internet
- class date_time
"""
'''
TODO:
- average()
DATETIME:
X calendar_month_st replace day will be all noms
- Passed Time func
- System.(copy_to_clipboard & paste_from_clipboard)
- Other archive files in extract
- Call_later **kwargs
- Internet:
default_timeout
- files:
- files.join files.dirname
- Error in files.MEMBERS.all_all_*
- socket.socket()
- Screen recorder
- Make Sound
- mp3 tags (v 3.x)
- registery editor (v 3.x)
- re module (v 3.x)
- Developer:
reload_module
Check_Type
add_module_dir
- Create Local Server
- ( win32api.LoadLibrary() - ctypes.PyDLL() )
X Threading
- Ready-obj module
- !style defaults
- Check 3rd-party modules imports
- pip install update
- Open Video
- Open Audio
'''
#START
import os as _os
import re as _re
import sys as _sys
import abc as _abc
import time as _time
import socket as _socket
import typing as _typing
import urllib as _urllib
import shutil as _shutil
import random as _random
import datetime as _datetime
import calendar as _calendar
import requests as _requests
import subprocess as _subprocess
from bs4 import BeautifulSoup
from typing import (Any,Iterable,Optional,Callable,List,Union)
import psutil as _psutil
argv = _sys.argv
ABC = _abc.ABC
ABCMeta = _abc.ABCMeta
####### 8888888888 888 d8b #######
#### 888 888 Y8P ####
#### 888 888 ####
#### 8888888 888 888 88888b. .d8888b 888888 888 .d88b. 88888b. .d8888b ####
#### 888 888 888 888 "88b d88P" 888 888 d88""88b 888 "88b 88K ####
#### 888 888 888 888 888 888 888 888 888 888 888 888 "Y8888b. ####
#### 888 Y88b 888 888 888 Y88b. Y88b. 888 Y88..88P 888 888 X88 ####
####### 888 "Y88888 888 888 "Y8888P "Y888 888 "Y88P" 888 888 88888P' #######
def p(text='', end='\n'):
'''
p is print!
But because we use it a lot, we\'ve decided to make it one letter.
Example:
p('Hello World')
==>Hello World
'''
print(text, end=end)
def repeat(function, n: int, **kwargs):
'''
Repeat function for n times with given parameters
for more info see the example below.
Example:
re(rx.screenshot, 3, image_name='screenshot.png')
==> "function rx.screenshot will be executed 3 times."
'''
for _ in range(n):
function(**kwargs)
def wait(seconds):
'''
Use this if you want your program wait for a certain _time.
Parameters
----------
seconds : [int/float]
time to sleep program in seconds
'''
_time.sleep(seconds)
sleep = wait
def cls():
'''
You can use this function if you want to clear the environment.
'''
import platform
if platform.system() == "Windows":
_os.system('cls')
else:
_os.system('clear')
clear = cls
def progressbar(
total=100, dashes_nom=100, delay=1, dashes_shape=' ', complete_shape='█',
pre_text='Loading: ', left_port='|', right_port='|'):
'''
Use this function to make a custom in-app progress bar (Not Very Usefull).
(Use Progressbar() Generator instead to do your stuffs while updating progressbar)
Example:
progressbar(
Total=100,Dashes_Nom=10,Time=1,Dashes_Shape='-',
Complete_Shape='#', Pre_Text='Loading')
==> Loading|####------| 40/100
'''
def Progressbar(it, prefix="", size=60, file=_sys.stdout):
count = len(it)
def show(j):
x = int(size*j/count)
file.write(f"{prefix}{right_port}{complete_shape*x}{dashes_shape*(size-x)}{left_port} {j}/{count}\r")
file.flush()
show(0)
for i, item in enumerate(it):
yield item
show(i+1)
file.write("\n")
file.flush()
for _ in Progressbar(range(total), pre_text, dashes_nom):
wait(delay)
def wait_for(button:str):
"""
If You Want to Wait For the User to Press a Key (Keyboard/Mouse)
Use This Function.
Parameters
----------
button : str
Button to click
Raises
------
ValueError
It will be raised when invalid button is given
"""
button = button.lower()
if button.lower() in ('middle', 'left', 'right', 'back', 'forward'):
if button == 'back':
button = 'x'
if button == 'forward':
button = 'x2'
import mouse
mouse.wait(button)
else:
import keyboard
try:
keyboard.wait(button)
except:
raise ValueError('Incorrect Button Name.')
def call_later(function:Callable, *args, delay=0.001):
"""
Call Your Function Later Even Between Other Operations
(This function uses threading module so be careful about
how, when, and on what object you are going to operate on)
Parameters
----------
function : Callable
this should be your function name
delay : float,int
delay before calling function in seconds, by default 0.001
"""
import threading
thread = threading.Thread(target=lambda: (sleep(delay), function(*args)))
thread.start()
#keyboard.call_later(function, args, delay)
call = call_later
def convert_bytes(num:int) -> str:
"""
Convert num to idiomatic byte unit.
Parameters
----------
num : int
number you want to convert (in Byte)
Returns
-------
str
number + unit
Examples
--------
>>> convert_bytes(200)
'200.0 bytes'
>>> convert_bytes(6000)
'5.9 KB'
>>> convert_bytes(80000)
'78.1 KB'
"""
'''
'''
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0
def restart_app(python3:bool = False):
"""
This Function Close App and Recall it From Terminal
(It uses terminal.run to run command 'python[3] *argv')
Parameters
----------
python3 : bool, optional
use 'python' or 'python3', by default False
"""
_os.execv(_sys.executable, ['python3' if python3 else 'python'] + _sys.argv)
_sys.exit()
def active_window_title() -> str:
"""
Get active windows title
(Usually terminal is active window title
but if during executing your script you change window
this will return new window title)
Returns
-------
str
string of active window title
"""
import pyautogui
return pyautogui.getActiveWindowTitle()
def open_image(path:str) -> None:
"""
Open image file with default image viewer.
(Mac OS is not supported yet)
Parameters
----------
path : str
path to the image file
Raises
------
OSError
It will be raised when you run this function in not supported OS
"""
import platform
if platform.system() == 'Windows':
_os.system(path)
elif platform.system() == 'Linux':
_subprocess.getoutput(f'xdg-open {path}')
else:
raise OSError('Only Windows and Linux are supported for this function.')
_BASENAME=''
def download(url:str, filename:str=_BASENAME, save_memory:bool=True,
progressbar:bool =True, prefix:str='Downloading'):
'''
Use this function to download files.
if filename is not given, it will be last part of the url.
filename can be path for saving file.
save_memory parameter is used to save memory in large files
(save directly to storage)
'''
import requests, urllib
if not filename:
filename = url.split('/')[-1]
if save_memory:
'''
with _urllib.request.urlopen(url) as response, open(filename, 'wb') as f:
_shutil.copyfileobj(response, f)
'''
'''
r = _requests.get(url, stream = True)
with open(filename,"wb") as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
'''
if progressbar:
with open(filename, "wb") as f:
response = _requests.get(url, stream=True)
total_length = response.headers.get('content-length')
if total_length is None:
f.write(response.content)
else:
dl = 0
done = 0
total_length = int(total_length)
for data in response.iter_content(chunk_size=4096):
dl += len(data)
f.write(data)
done = int(33 * dl / total_length)
_sys.stdout.write(f"\r{prefix} {filename}: |{'█' * done}{' ' * (33-done)}| {100-((33-done)*3)}%")
_sys.stdout.flush()
if 100-((33-done)*3) == 96:
_sys.stdout.write(f"\r{prefix} {filename}: |{'█' * done}{' ' * (33-done)}| 100%")
_sys.stdout.flush()
else:
with open(filename, "wb") as f:
response = _requests.get(url, stream=True)
for data in response.iter_content(chunk_size=4096):
f.write(data)
else:
def report(blocknr, blocksize, size):
if progressbar:
current = blocknr*blocksize
_sys.stdout.write("\rDownloading {1}: {0:.2f}%".format(100.0*current/size,filename))
def downloadFile(url):
_urllib.request.urlretrieve(url, filename, report)
downloadFile(url)
pass
if progressbar: print()
def extract(filename:str, path:Optional[str]=None,files:Optional[Iterable[str]]=None,
password:Optional[str]=None) -> None:
"""
Extract Files from Zip files
By default it extracts all files
Parameters
----------
filename : str
path to .zip file
path : str, optional
path to extract files (by default: folder in current working directory)
files : Iterable[str], optional
Iterable of files you want to extract, by default None
password : str, optional
password if your .zip file is password protected, by default None
"""
import zipfile
zipfile.ZipFile(filename, 'r').extractall(path=path,members= files,pwd=password)
def screenshot(image_name:str='Screenshot.png'):
'''
This function will take a screenshot and save it as image_name
'''
import pyscreeze
return pyscreeze.screenshot(image_name)
def func_info(func:Callable):
"""
print some information about 'func'
Parameters
----------
func : Callable
function you want to get its information
"""
help(func) #func.__doc__
print('-'*30)
print('Module ', func.__module__)
print('-'*30)
try:
_code_ = str(func.__code__)
_code_ = _code_[_code_.index(',')+2:-1]
except AttributeError:
_code_ = f'No "file" and "line" information available '
_code_ += f' (I guess "{func}" is a built-in function)'
print(_code_)
def Progressbar(
total=60, dashes_nom=30, dashes_shape=' ', complete_shape='█',
pre_text='Loading: ', left_port='|', right_port='|'):
'''
Make your code more beautiful with progressbars!
this is generator function so use it like this:
>>> for _ in generator(100,10):
do_this()
do_that()
Loading: |████ | 40/100
'''
echo = _sys.stdout
def show(j):
x = int(dashes_nom*j/total)
echo.write(
f"{pre_text}{right_port}{complete_shape*x}{dashes_shape*(dashes_nom-x)}{left_port} {j}/{total}\r")
echo.flush()
show(0)
for i, item in enumerate(range(total)):
yield item
show(i+1)
echo.write("\n")
echo.flush()
_MOUSE_X = 0
_MOUSE_Y = 0
def pixel_color(x=_MOUSE_X, y=_MOUSE_Y) -> tuple:
"""
Function to return color of pixel of screen in tuple of RGB
Parameters
----------
x : int
pixel of column x, by default last x of mouse
y : int
pixel of row y, by default last y of mouse
Returns
-------
tuple
tuple with 3 integers: (RED,GREEN,BLUE)
"""
import pyautogui
if not x:
x = pyautogui.position()[0]
if not y:
y = pyautogui.position()[1]
PIXEL = pyautogui.screenshot(region=(x, y, 1, 1))
COLOR = PIXEL.getcolors()
return COLOR[0][1]
def import_module(path:str):
"""
Import modules from files even if they are not .py
Parameters
----------
path : str
path to file to import it
Returns
-------
ModuleType
return module
"""
import importlib.machinery
import importlib.util
loader = importlib.machinery.SourceFileLoader('MOD', path)
spec = importlib.util.spec_from_loader(loader.name, loader)
mod = importlib.util.module_from_spec(spec)
loader.exec_module(mod)
return mod
######################
# TUPLE FUNC #
######################
def force(tpl: Any, *var: Any) -> tuple:
'''
(TUPLE FUNCTION)
It returns tpl with adding var(s) to it.
'''
return tuple(list(tpl)+[v for v in var])
#force= lambda tpl,*var: tuple(list(tpl)+[v for v in var])
def erase(tpl: tuple, *var: Any) -> tuple:
'''
(TUPLE FUNCTION)
It returns tpl with removing var(s) from it.
'''
#lstv= [v for v in var if v in tpl]
lstt= list(tpl)
for th in [v for v in var if v in tpl]:
lstt.remove(th)
return tuple(lstt)
def replace(tpl: tuple, ind, var: Any) -> tuple:
'''
(TUPLE FUNCTION)
Replace tpl[ind] with var
'''
tpl=list(tpl)
if type(ind) == str:
ind= tpl.index(ind)
tpl[ind]=var
return tuple(tpl)
def insert(tpl: tuple, ind, var: Any) -> tuple:
'''
(TUPLE FUNCTION)
Exactly like tpl[ind]=var in lists but for tuples.
'''
tpl=list(tpl)
if type(ind) == str:
ind= tpl.index(ind)
tpl.insert(ind,var)
return tuple(tpl)
def pop(tuple,index=-1):
'''
(TUPLE FUNCTION)
pop method that is used in lists but for tuples
'''
return tuple(list(tuple).pop(index))
"""
def screen_recorder():
from screen_recorder_sdk import screen_recorder
#screen_recorder.enable_dev_log ()
screen_recorder.disable_log()
pid = 2456
screen_recorder.init_resources(pid)
screen_recorder.start_video_recording ('video1.mp4', 30, 8000000, True)
_time.sleep(10)
print('hello')
for i in range(100):
x= i**3
screen_recorder.stop_video_recording ()
screen_recorder.free_resources()
class Error(Exception):
'''
This module is for creating you own Error and Exception!
Useage:
>>> MyError = Error(name='MyError', msg='An Error occurred')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MyError: An Error occurred
Also You can raise it directly:
>>> raise Error(name='MyError', msg='An Error occurred')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MyError: An Error occurred
'''
def __new__(cls, msg, name=''):
Error.__name__ = name
return super(Error, cls).__new__(cls, msg)
def __init__(self, **kwargs):
pass
"""
####### .d8888b. 888 888 #######
#### d88P Y88b 888 888 ####
#### 888 888 888 888 ####
#### 888 888 888 8888b. .d8888b .d8888b .d88b. .d8888b ####
#### 888 888 888 "88b 88K 88K d8P Y8b 88K ####
#### 888 888 888 888 .d888888 "Y8888b. "Y8888b. 88888888 "Y8888b. ####
#### Y88b d88P 888 888 888 888 X88 X88 Y8b. X88 ####
####### "Y8888P" 888 888 "Y888888 88888P' 88888P' "Y8888 88888P' #######
class Random:
'''
random Variable Generator Class.
(ALL FUNCTIONS ARE STATIC METHODS)
'''
@staticmethod
def choose(iterator,k: int =1,duplicate=True):
'''
Return a random element from a non-empty sequence.
'''
if type(k) != int:
raise TypeError('k must be integer.')
if k == 1:
return _random.choice(iterator)
elif k > 1:
if duplicate:
return _random.choices(iterator,k=k)
else:
return _random.sample(iterator,k=k)
else:
raise ValueError('k Must Be Higher 0')
@staticmethod
def integer(first_number,last_number):
'''
Return random integer in range [a, b], including both end points.
'''
return _random.randint(first_number,last_number)
@staticmethod
def O1(decimal_number=17):
'''
return x in the interval [0, 1)
'''
return round(_random.random(),decimal_number)
@staticmethod
def number(first_number,last_number):
'''
return x in the interval [F, L]
'''
return _random.uniform(first_number,last_number)
@staticmethod
def shuffle(iterable):
'''
Return shuffled version of iterable
'''
real_type = type(iterable)
new_iterable = list(iterable)
_random.shuffle(new_iterable)
if real_type in (set,tuple):
return real_type(new_iterable)
elif real_type == str:
return ''.join(new_iterable)
elif real_type == dict:
return {item:iterable[item] for item in new_iterable}
else:
return new_iterable
random = Random
class Files:
'''
(STATIC METHODS)\n
Actions and information about files.\n
(READ FUNCTIONS DOCSTRING)
GET INFORMATION:
- exists()
- size()
- abspath()
- mdftime()
- acstime()
- content (read function)()
- is file()
- is dir()
- is readonly()
- is hidden()
ACTIONS:
- remove()
- rename()
- move()
- copy()
- hide()
- read only()
- write()
'''
@staticmethod
def size(path):
'''
return size of the file in byte(s).
Also work on directories.
'''
return _os.path.getsize(path)
#rooye pooshe emtehan she
@staticmethod
def remove(path,force=False):
'''
Use this to delete a file or a directory.
If force is True it will delete non-empty directories.
'''
if _os.path.isfile(path):
_os.remove(path)
else:
if force:
_shutil.rmtree(path)
else:
try:
_os.rmdir(path)
except OSError:
raise OSError(f"[WinError 145] The directory is not empty: '{path}'" + '\n' + ' '*23 +
'(Use force=True as an argument of remove function to remove non-empty directories.)') from None
delete = remove
@staticmethod
def rename(old_name,new_name):
'''Rename files with this function.'''
_os.rename(old_name,new_name)
@staticmethod
def abspath(path):
'''
return absolute path of given path.
'''
return _os.path.abspath(path)
@staticmethod
def exists(path):
'''
Search for the file And Returns a boolean.
if file exists: True
else: False
'''
return _os.path.exists(path)
@staticmethod
def mdftime(path):
'''
Get last modify time of the path.
'''
return _os.path.getmtime(path)
@staticmethod
def acstime(path):
'''
Get last access time of the path.
'''
return _os.path.getatime(path)
# change to date bayad biad
@staticmethod
def move(src,dst):
'''
Move (cut) file/directory from crs to dst.
'''
_shutil.move(src,dst)
#live_path= dst
#Baraye folder hast ya na?
@staticmethod
def copy(src,dest,preserve_metadata= True):
'''
Copy the file from src to destination.
preserve_metadata is for preserving metadata of file when copying.
(You can use it instead of rename too.
e.g:
copy('D:\\Test.py','E:\\Ali.py')
(It copies Test.py to E drive and renames it to Ali.py)
)
'''
if files.isdir(src):
_shutil.copytree(src,dest)
else:
if preserve_metadata: _shutil.copy2(src,dest)
else: _shutil.copy(src,dest)
@staticmethod
def hide(path,mode=True):
'''
Hide file or folder.
If mode==False: makes 'not hide'
(ONLY WINDOWS)
'''
try:
import win32api, win32con
except:
raise ImportError('Please install pywin32 via pip')
if mode:
win32api.SetFileAttributes(path,win32con.FILE_ATTRIBUTE_HIDDEN)
else:
win32api.SetFileAttributes(path,win32con.FILE_ATTRIBUTE_NORMAL)
@staticmethod
def read_only(path,mode=True):
'''
Make file attribute read_only.
If mode==False: makes 'not read_only'
'''
if type(mode)==bool:
from stat import S_IREAD,S_IWUSR
if mode==True:
_os.chmod(path, S_IREAD)
elif mode==False:
_os.chmod(path, S_IWUSR)
else:
raise Exception('Second argumant (mode) should be boolean.')
@staticmethod
def read(path):
'''
This can help you to read your file faster.
Example:
read('C:\\users\\Jack\\test.txt')
==> "Content of 'test.txt' will be shown."
'''
with open(path) as f:
FileR= f.read()
return FileR
@staticmethod
def write(file_path,text=None,mode='replace',start=''):
'''
With this method you can change content of the file.
file: File you want to change its content.
content: Content you want to add to file.
mode: Type of writing method.
'a' or 'continue' for add content to end of the file.
'w' or 'replace' for overwriting to file content.
start: I use this when I use mode='continue'
'''
if mode=='replace':
op= open(file_path,mode='w')
if text==None:
text= input('Type what you want.\n\n')
op.write(text)
op.close()
elif mode=='continue':
'''opr= open(file,mode='r')
FileR= opr.read()
op= open(file,mode='w')'''
op=open(file_path,'a')
if text==None:
text= input('Type what you want to add in the end of the file.\n\n')
op.write(start+text)
op.close()
else:
raise ValueError('mode can only be: replace(default) or continue Not "{0}"'.format(mode))
@staticmethod
def isdir(path):
return _os.path.isdir(path)
@staticmethod
def isfile(path):
return _os.path.isfile(path)
@staticmethod
def is_readonly(path):
'''
Return True if path is readonly else False.
(May Not Work in Linux)
'''
return _subprocess.getoutput(f'dir /ar {path} >nul 2>nul && echo True || echo False')
@staticmethod
def is_hidden(path):
"""
Check whether a file is presumed hidden, either because
the pathname starts with dot or because the platform
indicates such.
Return True if File or Directory is hidden.
(Work on both Linux and Windows)
"""
import platform
full_path = _os.path.abspath(path)
name = _os.path.basename(full_path)
def no(path): return False
platform_hidden = globals().get('is_hidden_' + platform.system(), no)
return name.startswith('.') or platform_hidden(full_path)
@staticmethod
def is_hidden_Windows(path):
import ctypes
res = ctypes.windll.kernel32.GetFileAttributesW(path)
assert res != -1
return bool(res & 2)
@staticmethod
def search_file(pattern, path='.\\',return_mode: Union['list','Generator']= 'list'):
'''
Search for files in path.
Return list or generator.
pattern:
- 'x.py' : search for 'x.py' in path.
- '*.py' : search for all files with .py extension in path.
- '*.*' : search for all files in path
- '**/*' : search for any file in path and also all sub-directories.
- '**/*.py: search for all python files in path and also sub-directories.
- 'mydir/**/*.py' : search for all python files in path/mydir/ and all of its sub-directories.
'''
import glob
if str(return_mode).lower() in ('list','generator'):
#print(_os.path.join(path,pattern))
if return_mode=='list': return glob.glob(_os.path.join(path,pattern), recursive=True)
else: return glob.iglob(_os.path.join(path,pattern), recursive=True)
else:
if type(return_mode)==str:
raise ValueError(f"return_mode van be 'list' or 'generator' not {return_mode}")
else:
raise TypeError(f"return_mode type should be 'str' and it should be in ['list', 'generator']")
@staticmethod
def search_content(path,word):
ALL= [val for sublist in [[_os.path.join(i[0], j) for j in i[2]] for i in _os.walk(path)] for val in sublist]
'''lst=[]
for file in ALL:
if word in rx.read(file):
lst.append(file)
return lst'''
return [file for file in ALL if word in open(file).read()]
@staticmethod
def mkdir(path):
path = _os.path.normpath(path)
NEW= ''
for FILE in path.split('\\'):
NEW+= FILE+'\\'
try: _os.mkdir(NEW)
except (FileExistsError,FileNotFoundError): pass
@staticmethod
def generate_tree(dir_path, level: int=-1, limit_to_directories: bool=False,
length_limit: int=1000, print_info: bool=True):
"""Given a directory Path object return a visual tree structure"""
from pathlib import Path
from itertools import islice
space= ' '; branch = '│ '; tee= '├── '; last= '└── '
dir_path = Path(dir_path) # accept string coerceable to Path
files = 0
directories = 0
def inner(dir_path: Path, prefix: str='', level=-1):
nonlocal files, directories
if not level: return # 0, stop iterating
if limit_to_directories: contents = [d for d in dir_path.iterdir() if d.is_dir()]
else: contents = list(dir_path.iterdir())
pointers = [tee] * (len(contents) - 1) + [last]
for pointer, path in zip(pointers, contents):
if path.is_dir():
yield prefix + pointer + path.name
directories += 1
extension = branch if pointer == tee else space
yield from inner(path, prefix=prefix+extension, level=level-1)
elif not limit_to_directories:
yield prefix + pointer + path.name
files += 1
RETURN=''
RETURN+=dir_path.name+'\n'
iterator = inner(dir_path, level=level)
for line in islice(iterator, length_limit): RETURN+=line+'\n'
if next(iterator, None): RETURN+=f'... length_limit, {length_limit}, reached, counted:'
if print_info: RETURN+=f'\n{directories} directories' + (f', {files} files' if files else '')
return RETURN
class MEMBERS:
@staticmethod
def all_exactdir(dir):
return _os.listdir(dir)
@staticmethod
def all_all_sep(dir):
return [i for i in _os.walk(dir)]
@staticmethod
def files_exactdir(dir,abspath=True):
if abspath:
return [dir+'/'+file_ for file_ in [i for i in _os.walk(dir)][0][2]]
return [i for i in _os.walk(dir)][0][2]
@staticmethod
def files_all(dir):
return [val for sublist in [[_os.path.join(i[0], j) for j in i[2]] for i in _os.walk(dir)] for val in sublist]
@staticmethod
def files_all_sep(dir):
return [[_os.path.join(i[0], j) for j in i[2]] for i in _os.walk(dir)]
@staticmethod
def dirs_exactdir(dir, abspath=True):
if dir.endswith('/'): dir=dir[:-1]
elif dir.endswith('\\'): dir=dir[:-1]
if abspath:
return [dir+'/'+folder for folder in [i for i in _os.walk(dir)][0][1]]
return [i for i in _os.walk(dir)][0][1]
@staticmethod
def dirs_all(dir):
return [TPL[0] for TPL in [i for i in _os.walk(dir)]]
files = Files
write = files.write
read = files.read
class System:
'''
Some system actions and information.
- Information about ram, ip, terminal, etc.
- Some System Actions like Shutdown and Restart
(ALL FUNCTIONS ARE STATIC METHODS)
'''
@staticmethod
def accname():
'''
return account username you have logged in.
'''
return _os.getlogin()
@staticmethod
def pid():
'''
Get pid number of terminal and return it.
'''
return _os.getpid()
'''@staticmethod
def disk_usage(path):
####
return _shutil.disk_usage(path)'''
@staticmethod
def chdir(path):
'''
Change directory of terminal.
'''
_os.chdir(path)
@staticmethod
def SHUT_DOWN():
'''
Shut down the PC. (WINDOWS)
'''
_os.system("shutdown /s /t 1")
@staticmethod
def RESTART():
'''
Restart the PC. (WINDOWS)
'''
_os.system("shutdown /r /t 1")
@staticmethod
def terminal_size() -> tuple:
'''
Return terminal size in tuple (columns,rows)
'''
size= _os.get_terminal_size()
return (size.columns,size.lines)
@staticmethod
def cwd():
'''
Return a unicode string representing the current working directory.
'''
return _os.getcwd()
@staticmethod
def ip_global():
"""
Return ip with by http://ipinfo.io/ip api.
returns global ip as string
"""
try:
import requests
new_session = _requests.session()
response = new_session.get("http://ipinfo.io/ip")
import re
ip_list = _re.findall(r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}", response.text)
new_session.close()
return ip_list[0]
except:
raise ConnectionError('No Internet Connection') from None
"""ip_global= internet.ip_global"""
@staticmethod
def ip_local():
"""
Return local ip of computer in windows by _socket. module
and in unix with hostname command in shell.
"""
#return [l for l in ([ip for ip in _socket.gethostbyname_ex(_socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [_socket._socket.(_socket.AF_INET, _socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
'''
s = _socket._socket.(_socket.AF_INET, _socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
'''
import platform
class NetworkError(Exception):
def __init__(self, message): super().__init__(message)
try:
ip = _socket.gethostbyname(_socket.gethostname())
if ip and ip != "127.0.1.1":
return ip
elif platform.system() != "Windows":
import subprocess
command = _subprocess.Popen(["hostname", "-I"],stdout=_subprocess.PIPE,stderr=_subprocess.PIPE,stdin=_subprocess.PIPE,shell=False)
response = list(command.communicate())
if len(response[0]) > 0:
return str(response[0])[2:-4]
raise NetworkError('No Network Connection')
raise NetworkError('No Network Connection')
except:
raise
"""ip_local= internet.ip_local"""
@staticmethod
def ram_total(convert=True):
"""
Return total ram of board as string
parameter convert: flag for convert mode (using of convert_byte function)
"""
response = list(_psutil.virtual_memory())
if convert:
return convert_bytes(int(response[0]))
return str(response[0])
@staticmethod
def ram_used(convert=True):
"""
Return how much ram is using.
parameter convert: flag for convert mode (convert with convert_byte function)
"""
response = list(_psutil.virtual_memory())
if convert:
return convert_bytes(int(response[3]))
return str(response[3])
@staticmethod
def ram_free(convert=True):
"""
Return how much ram is available.
parameter convert: flag for convert mode (convert with convert_byte function)
"""
response = list(_psutil.virtual_memory())
if convert:
return convert_bytes(int(response[1]))
return str(response[1])
@staticmethod
def ram_percent(ONLY_NOM=False):
"""
Return available ram percentage as an integer if ONLY_NOM, as string with % if not ONLY_NOM
Parameter ONLY_NOM: flag for return type and value.
"""
response = list(_psutil.virtual_memory())
if ONLY_NOM:
return response[2]
return str(response[2]) + " %"
@staticmethod
def boot_time():
'''
Return the system boot time expressed in seconds since the epoch.
'''
return _psutil.boot_time()
@staticmethod
def device_name():
return _socket.gethostname()
@staticmethod
def ip_website(url):
'''get IP address of Web Site'''
return _socket.gethostbyname(url)
"""ip_webs= internet.ip_website"""
@staticmethod
def win10_notification(title,message,icon=None, duration=5) -> None:
'''
(THIS ONLY WORKS FOR "WINDOWS 10")\n
Display Notification with title, message and icon for speciefic _time.
'''
try:
from win10toast import ToastNotifier
ToastNotifier().show_toast(title,message,duration=duration)
except:
raise ImportError('Use "pip install win10toast" to install required module')
@staticmethod
def cpu_count(logical=True):
'''
Return the number of logical CPUs in the system
(same as _os.cpu_count() in Python 3.4).
If *logical* is False return the number of physical cores only
(e.g. hyper thread CPUs are excluded).
Return None if undetermined.
'''
return _psutil.cpu_count(logical)
@staticmethod
def pyshell_execute_bit():
'''to determine whether a Python shell is executing in 32bit or 64bit'''
#return platform.architecture()[0][:2] # SLOW
#return ctypes.sizeof(ctypes.c_voidp)*8
import struct
return struct.calcsize("P") * 8
@staticmethod
def pids() -> list:
'''Return a list of current running PIDs'''
return _psutil.pids()
@staticmethod
def cpu_percent() -> float:
'''
Return a float representing the current system-wide CPU utilization as a percentage.'''
return _psutil.cpu_percent()
@staticmethod
def pid_exists(pid) -> bool:
return _psutil.pid_exists(pid)
@staticmethod
def mac_address(formatted=False):
import uuid
mac = uuid.getnode()
if formatted:
return ':'.join(['{:02x}'.format((mac >> ele) & 0xff) for ele in range(0,8*6,8)][::-1])
return hex(mac)
system = System
from colored import fg as _fg
from colored import bg as _bg
from colored import attr as _attr
class Style:
'''
This class is for Changing text Color,BG & Style.
(Using colored module but easier)
- style.print to customize your print.
- style.switch to change terminal colors.
- style.switch_default for making everything default.
Also You Can Create style object.
This will allow you to:
- Because it returns string You can Add it to other strings
- Slicing and indexing (Without Color)
'''
def __init__(self, text, color='default', BG='black'):
try:
self.color = color.lower()
self.BG = BG.lower()
#style = style.lower()
except:
pass
if color == 'default':
self.color = 7 #188
self.text = text
self.content = f"{_fg(color)}{_bg(BG)}{text}{_attr(0)}"
def __str__(self):
return self.content
def __repr__(self):
return self.content
def __add__(self, other):
#print(type(other))
if type(other)!=style:
return self.content+other
else:
return self.content+other.content
@staticmethod
def print(text='', color='default', BG='default', style=None, end='\n'):
'''
text(text='Hello World',color='red',BG='white')
output ==> 'Hello World' (With red color and white BG)
Styles: bold - underline - reverse - hidden
*bold and underline may not work. (Depends on terminal and OS)
'''
try:
color = color.lower()
BG = BG.lower()
style = style.lower() if style and type(style)==str else 0
except:
raise
if style == 'none':
style = 0
if color=='default' and BG!='default': # _bg & !clr
print(f'{_attr(style)}{_bg(BG)}{text}{_attr(0)}', end=end)
elif color!='default' and BG=='default': # !_bg & clr
print(f'{_attr(style)}{_fg(color)}{text}{_attr(0)}', end=end)
elif color=='default' and BG=='default': # !_bg & !clr
print(f'{_attr(style)}{text}{_attr(0)}', end=end)
elif color!='default' and BG!='default': # _bg & clr
print(f'{_attr(style)}{_bg(BG)}{_fg(color)}{text}{_attr(0)}', end=end)
@staticmethod
def switch(color='default', BG='black', style='None'):
'''
Change color,BG and style untill you call it again and change them.
'''
try:
color = color.lower()
BG = BG.lower()
style = style.lower()
except:
pass
if style == 'none':
style = 0
if color == 'default':
color = 7
print(f'{_attr(style)}{_bg(BG)}{_fg(color)}', end='')
@staticmethod
def switch_default():
'''Switch Terminal Attributes to its defaults'''
print(f'{_attr(0)}', end='')
reset = switch_default
@staticmethod
def log_success(text, color='green', BG='default', style=None, add_time=True):
#globals()['style'].print(text, color, BG, style=style)
NOW = _time.strftime('%H:%M:%S',_time.localtime()) if add_time else ''
globals()['style'].print(NOW, color, BG,end=' ')
globals()['style'].print(text, color, BG, style=style)
@staticmethod
def log_info(text, color='grey_93', BG='default', style=None, add_time=True):
NOW = _time.strftime('%H:%M:%S',_time.localtime()) if add_time else ''
globals()['style'].print(NOW, color, BG,end=' ')
globals()['style'].print(text, color, BG, style=style)
@staticmethod
def log_warning(text, color='gold_3a', BG='default', style=None, add_time=True):
NOW = _time.strftime('%H:%M:%S',_time.localtime()) if add_time else ''
globals()['style'].print(NOW, color, BG,end=' ')
globals()['style'].print(text, color, BG, style=style)
@staticmethod
def log_error(text, color='red', BG='default', style=None, add_time=True):
NOW = _time.strftime('%H:%M:%S',_time.localtime()) if add_time else ''
globals()['style'].print(NOW, color, BG,end=' ')
globals()['style'].print(text, color, BG, style=style)
@staticmethod
def log_critical(text, color='red_1', BG='default', style='bold', add_time=True):
NOW = _time.strftime('%H:%M:%S',_time.localtime()) if add_time else ''
globals()['style'].print(NOW, color, BG,end=' ')
globals()['style'].print(text, color, BG, style=style)
style = Style
class Record:
'''
Use this method to record an action time in second.
Usage:
Start= record()
#Some codes here...
Finnish= Start.lap()
print(Finnish) ==> 0.25486741
#Some more codes here...
Finnish= Start.lap() ==> 0.4502586
Start.laps --> [0.25486741, 0.4502586]
Use Start.stop() to finnish recording and save memory.
(after self.stop() using self.lap will cause error.)
'''
def __init__(self):
self.__start = _time.time()
self.laps = []
def __call__(self):
return f'Laps: {self.laps}'
def __repr__(self):
return f'Laps: {self.laps}'
def lap(self, save=True, Round=15):
'''
Return time passed from creating time of self.
(Read 'record' Doc String)
If save is True, time will be added to self.laps
'''
lp = _time.time() - self.__start
lp = round(lp,Round)
if save:
self.laps.append(lp)
return lp
def reset(self, reset_start=False):
'''
This will erase self.laps
If reset_start is True, start time will reset too.
'''
self.laps = []
if reset_start:
self.__start = _time.time()
def last_lap(self, save=True):
'''
Return time passed from last lap
(If self.laps is False then from start_time)
'''
ret = (self.lap(False)-self.laps[-1]) if self.laps else self.lap(False)
if save:
self.laps.append(self.lap())
return ret
@staticmethod
def timit(code,setup,times,globals_):
'''
Run the 'code' for 'times' times and return time it needs (all, not once)
(If you need any initialization for your 'code', put it in setup arg)
'''
import timeit
return timeit.timeit(stmt=code,setup=setup,number=times,globals=globals_)
record = Record
class Terminal:
"""
Run Terminal Commands with Terminal functions
(ALL FUNCTIONS ARE STATIC METHODS)
"""
@staticmethod
def run(command:str) -> None:
'''
Execute the command in a subshell
(NO RETURN, LIVE EXECUTION, OUTPUT WILL BE PRINTED)
'''
_os.system(command)
@staticmethod
def getoutput(command:str) -> str:
'''
Return output of executing command in a shell
(RETURN STR, RETURN AFTER EXECUTING CODE)
'''
return _subprocess.getoutput(command)
terminal = Terminal
class Decorator:
class Check_Type:
"""
Function decorator for developers\n
Use this decorator to check if user gives right argument type\n
You need to annotate argument type when defining it.\n
Supported Types:
* str
* list
* set
* dict
* tuple
* User-Defined Objects
Typing Module Supported Types:
* Iterable
* Callable
* Generatr
* Container
* Any
(MORE TYPES SOON ...)
'''
sig = signature(foo)
print(str(sig))
print(str(sig.parameters['b']))
print(sig.parameters['b'].annotation)
####
sig = signature(foo)
for param in sig.parameters.values():
if (param.kind == param.KEYWORD_ONLY and
param.default is param.empty):
print('Parameter:', param.annotation)
'''
"""
auto_correct = False
def __init__(self, function):
self.function = function
def __call__(self, *args, **kwargs):
special_types = ('callable', 'iterable', 'generator','container', 'any')
i=-1
__local__= list(locals()['args'])
annots= list(self.function.__annotations__.keys())
def extra_remover(correct):
# Typing module annots check
if correct.startswith('typing.'):
correct = correct[7:].lower()
# built-in types check
elif correct.startswith('<class '):
correct = correct[8:-2]
return correct
def check_specials(TYPE, LOCAL_I):
import inspect
wrong = ''
if TYPE == 'generator':
if inspect.isgeneratorfunction(LOCAL_I) or inspect.isgenerator(LOCAL_I):
return
else:
correct = 'generator'
elif TYPE == 'callable':
if callable(LOCAL_I):
return
else:
correct = 'callable'
elif TYPE == 'iterable':
if type(LOCAL_I) in (list, tuple, set, str):
print(type(LOCAL_I))
return
else:
correct = 'iterable'
elif TYPE == 'container':
if type(LOCAL_I) in (list,set,dict,tuple):
return
else:
correct = 'container'
elif TYPE == 'any':
return
wrong = extra_remover(str(type(LOCAL_I))) if not wrong else wrong
func_name = self.function.__name__
Error= TypeError(f"'{func_name}()' argument '{ARG}' must be '{correct}' (not '{wrong}')")
raise Error
for ARG in annots:
i += 1
try:
LOCAL_I = __local__[i]
correct = str(self.function.__annotations__[ARG])
'''if correct.startswith('typing.Union'):
correct = eval(correct[12:])
if type(correct) != list:
correct = [correct]'''
correct = extra_remover(correct)
if correct in special_types:
print(type(LOCAL_I))
check_specials(correct,LOCAL_I)
# Builtins and other Libraries objects
elif not eval(correct) == type(LOCAL_I):
if Check_Type.auto_correct:
try:
__local__[i] = eval(correct)(LOCAL_I)
continue
except ValueError:
pass
wrong = extra_remover(str(type(LOCAL_I)))
#correct = str(self.function.__annotations__[ARG])#[8:-2]
correct = extra_remover(correct)
func_name = self.function.__name__
Error= TypeError(f"'{func_name}()' argument '{ARG}' must be '{correct}' (not '{wrong}')")
raise Error
except (ValueError,IndexError):
pass#raise
except NameError:
raise
return self.function(*__local__, **kwargs)
decorator_all:Callable = None
@staticmethod
def attach_to_all(cls):
import inspect
for name, method in inspect.getmembers(cls):
if (not inspect.ismethod(method) and
not inspect.isfunction(method) ) or (
inspect.isbuiltin(method)):
continue
#print("Decorating function %s" % name)
setattr(cls, name, Decorator.decorator_all(method))
return cls
abstractmethod = _abc.abstractmethod
_registered_functions = {} #:Dict[str, Any]
class _MultiMethod(object):
def __init__(self, name):
self.name = name
self.typemap = {}
def __call__(self, *args):
types = tuple(arg.__class__ for arg in args)
function = self.typemap.get(types)
if function is None:
raise TypeError("no match: ",types)
return function(*args)
def register(self, types, function):
self.typemap[types] = function
def overload(*types):
def register(function):
name = function.__name__
mm = decorator._registered_functions.get(name)
if mm is None:
mm = decorator._registered_functions[name] = Decorator._MultiMethod(name)
mm.register(types, function)
return mm
return register
decorator = Decorator
Check_Type = Decorator.Check_Type
overload = Decorator.overload
class IO:
@staticmethod
def wait_for_input(prompt,SS:list=[]):
answer= ''
try:
while not answer:
answer = input(prompt).strip()
except (EOFError,KeyboardInterrupt):
style.print('EXITING...','red')
exit()
return answer
@staticmethod
def selective_input(prompt,choices,default=None,ignore_case=False,error=True,invalid='Invalid input'):
if type(choices) == dict:
Choices = list(choices.keys())+list(choices.values())
pass
if ignore_case:
Choices = [item.lower() for item in Choices]
while True:
inp = input(prompt)
inp = inp.lower() if ignore_case else inp
if not inp or inp not in Choices:
if error:
style.print(invalid, 'red')
else:
if default:
inp = default
break
else:
break
if type(choices) == dict:
try:
inp = choices[inp]
except KeyError:
pass
return inp
@staticmethod
def yesno_input(prompt,default=None):
error= not bool(default)
return io.selective_input(prompt,['y','yes','n','no'],default,error)
@staticmethod
def Input(prompt:str ='', default_value:str =''):
'''
Make Default Value For Your Input!
(THIS ONLY WORK ON WINDOWS (SORRY))
prompt is what you want and it's input(prompt) .
default_value is what there should be after prompt.
E.g:
>>> Input('Is rx7 Library Easy to Learn? ', 'Yes')
Is rx7 Library Easy to Learn? Yes
'''
import win32console
_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
keys = []
for c in str(default_value):
evt = win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)
evt.Char = c
evt.RepeatCount = 1
evt.KeyDown = True
keys.append(evt)
_stdin.WriteConsoleInput(keys)
return input(str(prompt))
@staticmethod
def getpass(prompt):
'''
Prompt for a password, with echo turned off.
'''
import getpass as Getpass
return Getpass.getpass(prompt=prompt)
io = IO
Input = default_input = io.Input
getpass = password_input = io.getpass
class Tuple:
'''
(Note That This is tuple of RX7 Module So it Has More Features!)\n
(This is Not Built-in immutable sequence.)\n
If no argument is given, the constructor returns an empty tuple.\n
There is *var argumant that you can add object as much as you need.\n
Any Built-in object is accepted. (Not tested on third-party objects.)\n
Beside built-in features of tuple, this supports:
+ You Can Add objects to your tuple now.
+ Also You Can Delete Them.
+ Replace Them.
+ Like lists, Tuple supports item assigning. ( tpl[2]='hello' )
(Tuple Unpacking is Supported.)
'''
#############################
def __init__(self,*var: Any, one_item=False):
if not one_item:
self.__content= tuple(var)
else:
self.__content=[]
for item in var:
for member in item:
self.__content.append(member)
self.__content= tuple(self.__content)
def __str__(self):
return str(self.__content)
def __repr__(self):
return str(self.__content)
#############################
#############################
def add(self,*var: Any):
'''
This will add var(s) to self.
'''
self.__content= tuple(list(self.__content)+[v for v in var])
#force= lambda tpl,*var: tuple(list(tpl)+[v for v in var])
force= add
def remove(self,*var: Any):
'''
It will remove var(s) from self.
'''
#lstv= [v for v in var if v in tpl]
lstt= list(self.__content)
for th in [v for v in var if v in self.__content]:
lstt.remove(th)
self.__content= tuple(lstt)
erase= remove
def pop(self,index):
return pop(self.__content)
#############################
#############################
def replace(self, ind: Union[int,Any], var: Any):
'''
Replace self[ind] with var.
'''
tpl=list(self.__content)
if type(ind) == str:
ind= tpl.index(ind)
tpl[ind]=var
self.__content= tuple(tpl)
def __setitem__(self,index,value,replace=False):
if not replace:
tpl=list(self.__content)
if type(index) == str:
ind= tpl.index(index)
tpl.insert(index,value)
self.__content= tuple(tpl)
else:
self.replace(index,value)
def __getitem__(self,index):
return self.__content[index]
#############################
def __add__(self,other):
return self.__content + other
def __contains__(self,var):
return var in self.__content
#############################
#############################
def __bool__(self):
return bool(len(self.__content))
def __hash__(self):
return hash(self.__content)
def __len__(self):
return len(self.__content)
#############################
#############################
_ReqConErr = _requests.exceptions.ConnectionError
class Internet:
@staticmethod
def is_connected(website='http://x.com/'):
'''
Check for internet connection with trying to connect to web-site
( Maybe you want to know why i used http://x.com/ as default web-site
The reason is there's no extra code to load
(compare x.com and google.com html source code)
And this make it a lot faster for checking.
)
'''
try:
_urllib.request.urlopen(website)
return True
except:
return False
def connection_checker(func):
"""Decaorator Which Checks Internet Connection before calling a function
Parameters
----------
func : Function
function which you are going to check if
there is internet connection before call it
"""
def inside(*args,**kwargs):
if not internet.is_connected():
raise ConnectionError('No internet connection') from None
return func(*args,**kwargs)
return inside
@staticmethod
def ip_global() -> str:
"""
Return your global ip by http://ipinfo.io/ip api.
"""
new_session = _requests.session()
response = new_session.get("http://ipinfo.io/ip")
ip_list = _re.findall(r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}", response.text)
new_session.close()
return ip_list[0]
@staticmethod
def ip_local() -> str:
"""
Return local ip of computer in windows by _socket. module
and in linux with hostname command in shell.
"""
#return [l for l in ([ip for ip in _socket.gethostbyname_ex(_socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [_socket._socket.(_socket.AF_INET, _socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
'''
s = _socket._socket.(_socket.AF_INET, _socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
'''
import platform
class NetworkError(Exception):
def __init__(self, message): super().__init__(message)
try:
ip = _socket.gethostbyname(_socket.gethostname())
if ip and ip not in ("127.0.1.1","127.0.0.1"):
return ip
elif platform.system() != "Windows":
command = _subprocess.Popen(["hostname", "-I"],stdout=_subprocess.PIPE,stderr=_subprocess.PIPE,stdin=_subprocess.PIPE,shell=False)
response = list(command.communicate())
if len(response[0]) > 0:
return str(response[0])[2:-4]
raise NetworkError('No Network Connection')
raise NetworkError('No Network Connection')
except:
raise
@staticmethod
def url_exists(URL) -> bool:
'''
check if url exists (with 'requests' module)
(NEED HTTP[S])
'''
try:
request = _requests.get(URL)
except _ReqConErr:
raise ConnectionError('No internet connection') from None
#print(response.status_code < 400)
if request.status_code == 200:
return True
else:
return False
@staticmethod
def ip_website(URL) -> str:
'''
get IP address of Web Site\n
(Without http[s])
'''
try:
return _socket.gethostbyname(URL)
except _socket.gaierror:
if internet.is_connected():
class NotExistsError(Exception):
def __init__(self):
super().__init__('URL Does Not Exists')
raise NotExistsError from None
else:
raise ConnectionError from None
@staticmethod
def url_links(URL) -> list:
'''
Get all links that are used in a specifiec url
(All "a" tags from html source)
(Needs 'http[s]')
''' #html.parser
try:
soup= BeautifulSoup(_requests.get(URL).text,features="lxml")
LINKS= []
for link in soup.find_all('a'):
LINKS.append(link.get('href'))
return LINKS
except _ReqConErr:
raise ConnectionError('No internet connection') from None
@staticmethod
def find_urls(string) -> list:
'''
find all urls in a string and returns list of them
(urls should start with http[s])
'''
url = _re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', string)
return url
@staticmethod
def is_url(URL) -> bool:
'''
check if a string is url (WITH HTTP[S])
'''
search= _re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', URL)
'(http[s]?://)?([Ww]{3}\.)?(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
if search and len(search.group())==len(URL):
return True
else:
return False
@staticmethod
def open_browser(url,new_tab=True):
import webbrowser
if new_tab:
webbrowser.open_new_tab(url)
else:
webbrowser.open(url)
"""
@staticmethod
def whois(URL):
'''
return whois lookup of a website
(WITHOUT HTTPS)
'''
try:
import whois
WHO = whois.query(URL)
WHOIS = WHO.dict
return {i:WHOIS[i] for i in WHOIS}
except _socket.gaierror:
raise ConnectionError('No internet connection') from None
"""
internet = Internet
class DateTime:
_NOW= 0
_NOW_YEAR= 0
_NOW_MONTH= 0
_NOW_DAY= 0
_NOW_HOUR= -1
_NOW_MINUTE= -1
_NOW_SECOND= -1
def NOW():
_NOW= _time.localtime()
_NOW_YEAR= _NOW.tm_year
_NOW_MONTH= _NOW.tm_mon
_NOW_DAY= _NOW.tm_mday
_NOW_HOUR= _NOW.tm_hour
_NOW_MINUTE= _NOW.tm_min
_NOW_SECOND= _NOW.tm_sec
return _datetime.datetime(_NOW_YEAR,_NOW_MONTH,_NOW_DAY,_NOW_HOUR,_NOW_MINUTE,_NOW_SECOND)
now = NOW
def normalize(date=[],time=[]):
now = date_time.NOW()
try:
if not date[0]: date[0]= now.year
if type(date[1]) == str:
try:
date[1]= date_time.month_dic[date[1].lower()]
except KeyError:
raise ValueError("Wrong Month Name") from None
if not date[1]: date[1]= now.month
if not date[2]: date[2]= now.day
except IndexError:
pass
try:
if time[0]<0: now.hour
if time[1]<0: now.minute
if time[2]<0: now.second
except IndexError:
pass
return [date,time]
Weekday_Names= ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
month_lst= ['january','february','march','april','may','june',
'july','august','september','october','november','december']
month_dic= {month:month_nom for month in month_lst for month_nom in range(1,13)}
def __init__(self,year=_NOW_YEAR,month=_NOW_MONTH,day=_NOW_DAY,hour=_NOW_HOUR,minute=_NOW_MINUTE,second=_NOW_SECOND,first_week_day=0):
'''
.: Working With Date and Time :.
- Include Both Static Methods and Class Methods
- Get NOW Time
- Show in Calendar
- Next and Previous Months in Calendar
- Determine Time Passed From Specific Date
- Calendar Supports Setting First Day of the Week
'''
"""
Now = date_time.NOW()
if not year : year=Now.year
if not month: month=Now.month
if not day : day=Now.day
if hour<0 : hour=Now.hour
if minute<0 : minute=Now.minute
if second<0 : second=Now.second
"""
_norm = date_time.normalize([year,month,day],[hour,minute,second])
year,month,day = _norm[0]
hour,minute,second = _norm[1]
if type(month)==str:
try:
month= date_time.month_dic[month.lower()]
except KeyError:
raise ValueError("Wrong Month Name") from None
self.date= _datetime.date(year,month,day)
self.year=year; self.month=month; self.day=day
self.time= (hour,minute,second)
self.hour=hour; self.minute=minute; self.second=second
self.weekday= date_time.get_weekday(self.year,self.month,self.day)
self.weekday_name= date_time.get_weekday(self.year,self.month,self.day,True)
self.week_nom= date_time.get_weeknom(self.year,self.month,self.day)
#self.first_week_day= first_week_day
_calendar.setfirstweekday(first_week_day)
self.calendar= str(_calendar.month(year, month)).replace(str(day),style(str(day),'green').content)
self.calendar_month= str(_calendar.month(year, month))
self.calendar_year_all=str(_calendar.calendar(year))
self.calendar_year= [_calendar.month(year,i) for i in range(1,13)]
self.calendar_next_all= [_calendar.month(year,i) for i in range(self.month+1,13)]
self.calendar_prev_all= [_calendar.month(year,i) for i in range(1,self.month)]
self.calendar_position_next_year= str(_calendar.month(year+1, month)).replace(str(day),style(str(day),'green').content)
self.calendar_position_prev_year= str(_calendar.month(year-1, month)).replace(str(day),style(str(day),'green').content)
def setfirstweekday(self,day):
if type(day)==int and day<7:
date_time.Weekday_Names= date_time.Weekday_Names[day:]+date_time.Weekday_Names[:day]
elif type(day)==str:
day= date_time.Weekday_Names.index(day)
date_time.Weekday_Names= date_time.Weekday_Names[day:]+date_time.Weekday_Names[:day]
else:
if type(day)==int:
raise ValueError('Invalid Nomber. Day number should be in range(7)')
else:
raise TypeError(f"Inappropriate Type For 'day'. day can be 'str' or 'int' not {type(day)}")
_calendar.setfirstweekday(day)
self.calendar= str(_calendar.month(self.year, self.month)).replace(str(day),style(str(day),'green').content)
self.calendar_month= str(_calendar.month(self.year, self.month))
self.calendar_year_all=str(_calendar.calendar(self.year))
self.calendar_year= [_calendar.month(self.year,i) for i in range(1,13)]
self.calendar_next_all= [_calendar.month(self.year,i) for i in range(self.month+1,13)]
self.calendar_prev_all= [_calendar.month(self.year,i) for i in range(1,self.month)]
self.calendar_position_next_year= str(_calendar.month(self.year+1, self.month)).replace(str(day),style(str(day),'green').content)
self.calendar_position_prev_year= str(_calendar.month(self.year-1, self.month)).replace(str(day),style(str(day),'green').content)
self.weekday= date_time.get_weekday(self.year,self.month,self.day)
self.weekday_name= date_time.get_weekday(self.year,self.month,self.day,True)
self.week_nom= date_time.get_weeknom(self.year,self.month,self.day)
@staticmethod
def today():
dt = date_time.NOW()
return (dt.year,dt.month,dt.day)
@staticmethod
def calender_year(year=_NOW_YEAR):
if not year: year=date_time.NOW().year
return [_calendar.month(year,i) for i in range(1,13)]
@staticmethod
def calendar_month_st(month=_NOW_MONTH,year=_NOW_YEAR,day=0):
year,month = date_time.normalize([year,month])[0]
if not day:
return str(_calendar.month(year, month))
else:
return str(_calendar.month(year, month)).replace(str(day),style(str(day),'green').content)
@staticmethod
def passed_date(f_date,l_date=_NOW,return_time='day'):
if not l_date: l_date=date_time.NOW()
f_date = _datetime.datetime(*f_date)
return_time= return_time.lower()
if return_time in ('day','month','year','hour','minute','second'):
DELTA= l_date - f_date
if return_time == 'year':
try:
_return = _re.search(r'(?P<X>(-)?\w+) day',str(DELTA/365)).group('X')
except:
_return = None
#_return = str(DELTA/365)
elif return_time == 'month':
_return = _re.search(r'\w+',str(DELTA/30)).group()
elif return_time == 'day':
_return = str(DELTA)[:-14]
elif return_time =='hour':
_return = str(DELTA*24)[:-14]
elif return_time == 'minute':
_return = str(DELTA*1440)[:-14]
elif return_time == 'second':
_return = str(DELTA*3600)[:-14]
if _return: return _return
else: return 0
else:
raise ValueError("return_time should be in ('year', 'month', 'day', 'hour', 'minute', 'second')")
passed_time = passed_date
'''@staticmethod
def passed_time(year=1970,month=1,day=1,hour=0,minute=0,second=0,return_time='second'):
pass'''
@staticmethod
def convert_epoch_to_local(second=_time.time()):
return _time.ctime(second)
@staticmethod
def get_weekday(year=_NOW_YEAR,month=_NOW_MONTH,day=_NOW_DAY,return_name=False):
"""
First day is Monday and the numbers starts from 0
"""
year,month,day = date_time.normalize([year,month,day])[0]
if return_name:
return date_time.Weekday_Names[_datetime.date(year,month,day).weekday()]
else:
return _datetime.date(year,month,day).weekday()
@staticmethod
def get_weeknom(year=_NOW_YEAR,month=_NOW_MONTH,day=_NOW_DAY):
"""
Returns 53 if First week is from last year
"""
year,month,day = date_time.normalize([year,month,day])[0]
return _datetime.date(year,month,day).isocalendar()[1]
@staticmethod
def calendar_show_week(week_nom,year=_NOW_YEAR):
year = date_time.normalize([year])[0][0]
week= week_nom
for i in list(range(1,8))[::-1]:
if date_time.get_weeknom(year,1,i)==1:
FIRST_WEEK_DAYS= len(list(range(i)))
break
day= (week-1)*7 - (6-FIRST_WEEK_DAYS)
mnth= 1
true=False
while not true:
try:
if _calendar.monthrange(year,mnth)[1]<day:
mnth+=1
day-= _calendar.monthrange(year,mnth)[1]
else:
true= True
except _calendar.IllegalMonthError:
class BadWeekNumber(Exception):
def __init__(self, message='Week Number is Higher Than Year Weeks.'): super().__init__(message)
raise BadWeekNumber from None
new= date_time(year,mnth,day)
cal= new.calendar_month.splitlines()
for item in cal:
if str(new.day) in item and item != cal[0]:
INDEX= cal.index(item);COLORED_WEEK= style(item,'green');break
WEEK_WITH_COLOR= '\n'.join(cal[:INDEX]+[str(COLORED_WEEK)]+cal[INDEX+1:])
return WEEK_WITH_COLOR
@staticmethod
def get_year():
return _time.localtime().tm_year
@staticmethod
def get_month():
return _time.localtime().tm_mon
@staticmethod
def get_day_of_month():
return _time.localtime().tm_mday
@staticmethod
def get_day_of_week():
return _time.localtime().tm_wday
@staticmethod
def get_day_of_year():
return _time.localtime().tm_yday
@staticmethod
def get_hour():
return _time.localtime().tm_hour
@staticmethod
def get_minute():
return _time.localtime().tm_min
@staticmethod
def get_second():
return _time.localtime().tm_sec
date_time = DateTime
_Auto = 0
class _Lang:
class Constant:
def __new__(cls,*args,array=True):
cls._init = False
return super(_Lang.Constant, cls).__new__(cls)
def __init__(self,*args,array=True):
'''
if array:
self.__members = args
else:
if len(args) > 1:
raise ValueError
self.__members = args[0]
'''
self.__members = args
self._init = True
def __str__(self):
#if len(self.__members) > 1:
return '<'+str(self.__members)[1:-1]+'>' #‹›
#return self.__members
def __repr__(self):
return '<'+str(self.__members)[1:-1]+'>'
def __setattr__(self,_attr,value):
if self._init:
raise AttributeError(f"'Constant' object does not support item assignment")
else:
super(_Lang.Constant,self).__setattr__(_attr,value)
def __getitem__(self,index):
return self.__members[index]
def __contains__(self,obj):
return obj in self.__members
def __bool__(self):
return bool(len(self.__members))
#'''
def __hash__(self):
return hash(tuple(['Constant',len(self)]+list(self.__members)))
#'''
def __len__(self):
#if type(self.__members) == tuple:
return len(self.__members)
def _dict_getter(self):
raise AttributeError("Conatant object has no attribute '__dict__'")
#return {}
__dict__ = property(_dict_getter)
def __dir__(self):
ret = list(super().__dir__())#[:-2]
ret.remove('_init')
ret.remove('_dict_getter')
return ret
const = Const = constant = Constant
class Array:
# Sized Array
__Type_Error = "Array of type '{}' does not accept object with type '{}'"
def __init__(self,*args,type_=_Auto,size=_Auto):
self.__members = []
if type_:
self.__TYPE = type_
else:
self.__TYPE = type(args[0])
self.__TYPE_NAME = self.__TYPE.__name__
if size:
self.__SIZE = size
else:
self.__SIZE = len(args)
for obj in args:
if type(obj) == self.__TYPE:
self.__members.append(obj)
else:
raise ValueError(_Lang.Array.__Type_Error.format(self.__TYPE_NAME,type(obj).__name__))
def __str__(self):
return '{'+str(self.__members)[1:-1]+'}' #‹›
def __repr__(self):
return '{'+str(self.__members)[1:-1]+'}'
def __getitem__(self,index):
return self.__members[index]
def __contains__(self,obj):
return obj in self.__members
def __bool__(self):
return bool(len(self.__members))
def __len__(self):
return len(self.__members)
def __setitem__(self,index,obj):
if type(obj) == self.__TYPE:
self.__members.insert(index,obj)
return
raise ValueError(_Lang.Array.__Type_Error.format(self.__TYPE_NAME,type(obj).__name__))
def insert(self,index,obj):
if type(obj) == self.__TYPE:
self.__members.insert(index,obj)
return
raise ValueError(_Lang.Array.__Type_Error.format(self.__TYPE_NAME,type(obj).__name__))
def append(self,obj):
if type(obj) == self.__TYPE:
self.__members.append(obj)
return
raise ValueError(_Lang.Array.__Type_Error.format(self.__TYPE_NAME,type(obj).__name__))
add = append
def remove(self,obj):
self.__members.remove(obj)
def pop(self,index=-1):
self.__members.pop(index)
array = Array
class Types:
Str = str
Int = int
Float = float
Set = set
Tuple = tuple
Dict = dict
List = list
Bool = bool
Bytes = bytes
Class = type
Type = type
Object = object
Lambda = type(lambda: None)
Function = Lambda #type(lambda: None)
#Constant = type(_Lang.Constant(1))
#Array = type(_Lang.Array(1,1))
Any = type#_typing.Any
Callable = _typing.Callable
Container = _typing.Container
Generator = Lambda #type(_f) #Not Built-in(s) #_types.GeneratorType || _typing.Generator
Iterable = _typing.Iterable
Iterator = _typing.Iterator
NoReturn = _typing.NoReturn
Optional = _typing.Optional
BuiltinFunction = type(len)
BuiltinMethod = type([].append)
Module = type(_typing)
Method = type(globals()['Tuple']().force)
#Mapping = _typing.Mapping
#OrderedDict = _typing.OrderedDict
#Text = str
#Union = _typing.Union
#_types.AsyncGeneratorType
types = Types
#setattr(_Lang,'Const',type(_Lang.Constant(1)))
#setattr(_Lang,'Array',type(_Lang.Array(1,1)))
#END
| 33.292039 | 276 | 0.552293 | __version__ = '3.0.0'
import os as _os
import re as _re
import sys as _sys
import abc as _abc
import time as _time
import socket as _socket
import typing as _typing
import urllib as _urllib
import shutil as _shutil
import random as _random
import datetime as _datetime
import calendar as _calendar
import requests as _requests
import subprocess as _subprocess
from bs4 import BeautifulSoup
from typing import (Any,Iterable,Optional,Callable,List,Union)
import psutil as _psutil
argv = _sys.argv
ABC = _abc.ABC
ABCMeta = _abc.ABCMeta
ve_memory:
if progressbar:
with open(filename, "wb") as f:
response = _requests.get(url, stream=True)
total_length = response.headers.get('content-length')
if total_length is None:
f.write(response.content)
else:
dl = 0
done = 0
total_length = int(total_length)
for data in response.iter_content(chunk_size=4096):
dl += len(data)
f.write(data)
done = int(33 * dl / total_length)
_sys.stdout.write(f"\r{prefix} {filename}: |{'█' * done}{' ' * (33-done)}| {100-((33-done)*3)}%")
_sys.stdout.flush()
if 100-((33-done)*3) == 96:
_sys.stdout.write(f"\r{prefix} {filename}: |{'█' * done}{' ' * (33-done)}| 100%")
_sys.stdout.flush()
else:
with open(filename, "wb") as f:
response = _requests.get(url, stream=True)
for data in response.iter_content(chunk_size=4096):
f.write(data)
else:
def report(blocknr, blocksize, size):
if progressbar:
current = blocknr*blocksize
_sys.stdout.write("\rDownloading {1}: {0:.2f}%".format(100.0*current/size,filename))
def downloadFile(url):
_urllib.request.urlretrieve(url, filename, report)
downloadFile(url)
pass
if progressbar: print()
def extract(filename:str, path:Optional[str]=None,files:Optional[Iterable[str]]=None,
password:Optional[str]=None) -> None:
import zipfile
zipfile.ZipFile(filename, 'r').extractall(path=path,members= files,pwd=password)
def screenshot(image_name:str='Screenshot.png'):
import pyscreeze
return pyscreeze.screenshot(image_name)
def func_info(func:Callable):
help(func) #func.__doc__
print('-'*30)
print('Module ', func.__module__)
print('-'*30)
try:
_code_ = str(func.__code__)
_code_ = _code_[_code_.index(',')+2:-1]
except AttributeError:
_code_ = f'No "file" and "line" information available '
_code_ += f' (I guess "{func}" is a built-in function)'
print(_code_)
def Progressbar(
total=60, dashes_nom=30, dashes_shape=' ', complete_shape='█',
pre_text='Loading: ', left_port='|', right_port='|'):
echo = _sys.stdout
def show(j):
x = int(dashes_nom*j/total)
echo.write(
f"{pre_text}{right_port}{complete_shape*x}{dashes_shape*(dashes_nom-x)}{left_port} {j}/{total}\r")
echo.flush()
show(0)
for i, item in enumerate(range(total)):
yield item
show(i+1)
echo.write("\n")
echo.flush()
_MOUSE_X = 0
_MOUSE_Y = 0
def pixel_color(x=_MOUSE_X, y=_MOUSE_Y) -> tuple:
import pyautogui
if not x:
x = pyautogui.position()[0]
if not y:
y = pyautogui.position()[1]
PIXEL = pyautogui.screenshot(region=(x, y, 1, 1))
COLOR = PIXEL.getcolors()
return COLOR[0][1]
def import_module(path:str):
import importlib.machinery
import importlib.util
loader = importlib.machinery.SourceFileLoader('MOD', path)
spec = importlib.util.spec_from_loader(loader.name, loader)
mod = importlib.util.module_from_spec(spec)
loader.exec_module(mod)
return mod
######################
# TUPLE FUNC #
######################
def force(tpl: Any, *var: Any) -> tuple:
return tuple(list(tpl)+[v for v in var])
#force= lambda tpl,*var: tuple(list(tpl)+[v for v in var])
def erase(tpl: tuple, *var: Any) -> tuple:
#lstv= [v for v in var if v in tpl]
lstt= list(tpl)
for th in [v for v in var if v in tpl]:
lstt.remove(th)
return tuple(lstt)
def replace(tpl: tuple, ind, var: Any) -> tuple:
tpl=list(tpl)
if type(ind) == str:
ind= tpl.index(ind)
tpl[ind]=var
return tuple(tpl)
def insert(tpl: tuple, ind, var: Any) -> tuple:
tpl=list(tpl)
if type(ind) == str:
ind= tpl.index(ind)
tpl.insert(ind,var)
return tuple(tpl)
def pop(tuple,index=-1):
return tuple(list(tuple).pop(index))
####### .d8888b. 888 888 #######
#### d88P Y88b 888 888 ####
#### 888 888 888 888 ####
#### 888 888 888 8888b. .d8888b .d8888b .d88b. .d8888b ####
#### 888 888 888 "88b 88K 88K d8P Y8b 88K ####
#### 888 888 888 888 .d888888 "Y8888b. "Y8888b. 88888888 "Y8888b. ####
#### Y88b d88P 888 888 888 888 X88 X88 Y8b. X88 ####
####### "Y8888P" 888 888 "Y888888 88888P' 88888P' "Y8888 88888P' #######
class Random:
@staticmethod
def choose(iterator,k: int =1,duplicate=True):
if type(k) != int:
raise TypeError('k must be integer.')
if k == 1:
return _random.choice(iterator)
elif k > 1:
if duplicate:
return _random.choices(iterator,k=k)
else:
return _random.sample(iterator,k=k)
else:
raise ValueError('k Must Be Higher 0')
@staticmethod
def integer(first_number,last_number):
return _random.randint(first_number,last_number)
@staticmethod
def O1(decimal_number=17):
return round(_random.random(),decimal_number)
@staticmethod
def number(first_number,last_number):
return _random.uniform(first_number,last_number)
@staticmethod
def shuffle(iterable):
real_type = type(iterable)
new_iterable = list(iterable)
_random.shuffle(new_iterable)
if real_type in (set,tuple):
return real_type(new_iterable)
elif real_type == str:
return ''.join(new_iterable)
elif real_type == dict:
return {item:iterable[item] for item in new_iterable}
else:
return new_iterable
random = Random
class Files:
@staticmethod
def size(path):
return _os.path.getsize(path)
#rooye pooshe emtehan she
@staticmethod
def remove(path,force=False):
if _os.path.isfile(path):
_os.remove(path)
else:
if force:
_shutil.rmtree(path)
else:
try:
_os.rmdir(path)
except OSError:
raise OSError(f"[WinError 145] The directory is not empty: '{path}'" + '\n' + ' '*23 +
'(Use force=True as an argument of remove function to remove non-empty directories.)') from None
delete = remove
@staticmethod
def rename(old_name,new_name):
_os.rename(old_name,new_name)
@staticmethod
def abspath(path):
return _os.path.abspath(path)
@staticmethod
def exists(path):
return _os.path.exists(path)
@staticmethod
def mdftime(path):
return _os.path.getmtime(path)
@staticmethod
def acstime(path):
return _os.path.getatime(path)
# change to date bayad biad
@staticmethod
def move(src,dst):
_shutil.move(src,dst)
#live_path= dst
#Baraye folder hast ya na?
@staticmethod
def copy(src,dest,preserve_metadata= True):
if files.isdir(src):
_shutil.copytree(src,dest)
else:
if preserve_metadata: _shutil.copy2(src,dest)
else: _shutil.copy(src,dest)
@staticmethod
def hide(path,mode=True):
try:
import win32api, win32con
except:
raise ImportError('Please install pywin32 via pip')
if mode:
win32api.SetFileAttributes(path,win32con.FILE_ATTRIBUTE_HIDDEN)
else:
win32api.SetFileAttributes(path,win32con.FILE_ATTRIBUTE_NORMAL)
@staticmethod
def read_only(path,mode=True):
if type(mode)==bool:
from stat import S_IREAD,S_IWUSR
if mode==True:
_os.chmod(path, S_IREAD)
elif mode==False:
_os.chmod(path, S_IWUSR)
else:
raise Exception('Second argumant (mode) should be boolean.')
@staticmethod
def read(path):
with open(path) as f:
FileR= f.read()
return FileR
@staticmethod
def write(file_path,text=None,mode='replace',start=''):
if mode=='replace':
op= open(file_path,mode='w')
if text==None:
text= input('Type what you want.\n\n')
op.write(text)
op.close()
elif mode=='continue':
'''opr= open(file,mode='r')
FileR= opr.read()
op= open(file,mode='w')'''
op=open(file_path,'a')
if text==None:
text= input('Type what you want to add in the end of the file.\n\n')
op.write(start+text)
op.close()
else:
raise ValueError('mode can only be: replace(default) or continue Not "{0}"'.format(mode))
@staticmethod
def isdir(path):
return _os.path.isdir(path)
@staticmethod
def isfile(path):
return _os.path.isfile(path)
@staticmethod
def is_readonly(path):
return _subprocess.getoutput(f'dir /ar {path} >nul 2>nul && echo True || echo False')
@staticmethod
def is_hidden(path):
import platform
full_path = _os.path.abspath(path)
name = _os.path.basename(full_path)
def no(path): return False
platform_hidden = globals().get('is_hidden_' + platform.system(), no)
return name.startswith('.') or platform_hidden(full_path)
@staticmethod
def is_hidden_Windows(path):
import ctypes
res = ctypes.windll.kernel32.GetFileAttributesW(path)
assert res != -1
return bool(res & 2)
@staticmethod
def search_file(pattern, path='.\\',return_mode: Union['list','Generator']= 'list'):
import glob
if str(return_mode).lower() in ('list','generator'):
#print(_os.path.join(path,pattern))
if return_mode=='list': return glob.glob(_os.path.join(path,pattern), recursive=True)
else: return glob.iglob(_os.path.join(path,pattern), recursive=True)
else:
if type(return_mode)==str:
raise ValueError(f"return_mode van be 'list' or 'generator' not {return_mode}")
else:
raise TypeError(f"return_mode type should be 'str' and it should be in ['list', 'generator']")
@staticmethod
def search_content(path,word):
ALL= [val for sublist in [[_os.path.join(i[0], j) for j in i[2]] for i in _os.walk(path)] for val in sublist]
return [file for file in ALL if word in open(file).read()]
@staticmethod
def mkdir(path):
path = _os.path.normpath(path)
NEW= ''
for FILE in path.split('\\'):
NEW+= FILE+'\\'
try: _os.mkdir(NEW)
except (FileExistsError,FileNotFoundError): pass
@staticmethod
def generate_tree(dir_path, level: int=-1, limit_to_directories: bool=False,
length_limit: int=1000, print_info: bool=True):
from pathlib import Path
from itertools import islice
space= ' '; branch = '│ '; tee= '├── '; last= '└── '
dir_path = Path(dir_path) # accept string coerceable to Path
files = 0
directories = 0
def inner(dir_path: Path, prefix: str='', level=-1):
nonlocal files, directories
if not level: return # 0, stop iterating
if limit_to_directories: contents = [d for d in dir_path.iterdir() if d.is_dir()]
else: contents = list(dir_path.iterdir())
pointers = [tee] * (len(contents) - 1) + [last]
for pointer, path in zip(pointers, contents):
if path.is_dir():
yield prefix + pointer + path.name
directories += 1
extension = branch if pointer == tee else space
yield from inner(path, prefix=prefix+extension, level=level-1)
elif not limit_to_directories:
yield prefix + pointer + path.name
files += 1
RETURN=''
RETURN+=dir_path.name+'\n'
iterator = inner(dir_path, level=level)
for line in islice(iterator, length_limit): RETURN+=line+'\n'
if next(iterator, None): RETURN+=f'... length_limit, {length_limit}, reached, counted:'
if print_info: RETURN+=f'\n{directories} directories' + (f', {files} files' if files else '')
return RETURN
class MEMBERS:
@staticmethod
def all_exactdir(dir):
return _os.listdir(dir)
@staticmethod
def all_all_sep(dir):
return [i for i in _os.walk(dir)]
@staticmethod
def files_exactdir(dir,abspath=True):
if abspath:
return [dir+'/'+file_ for file_ in [i for i in _os.walk(dir)][0][2]]
return [i for i in _os.walk(dir)][0][2]
@staticmethod
def files_all(dir):
return [val for sublist in [[_os.path.join(i[0], j) for j in i[2]] for i in _os.walk(dir)] for val in sublist]
@staticmethod
def files_all_sep(dir):
return [[_os.path.join(i[0], j) for j in i[2]] for i in _os.walk(dir)]
@staticmethod
def dirs_exactdir(dir, abspath=True):
if dir.endswith('/'): dir=dir[:-1]
elif dir.endswith('\\'): dir=dir[:-1]
if abspath:
return [dir+'/'+folder for folder in [i for i in _os.walk(dir)][0][1]]
return [i for i in _os.walk(dir)][0][1]
@staticmethod
def dirs_all(dir):
return [TPL[0] for TPL in [i for i in _os.walk(dir)]]
files = Files
write = files.write
read = files.read
class System:
@staticmethod
def accname():
return _os.getlogin()
@staticmethod
def pid():
return _os.getpid()
@staticmethod
def chdir(path):
_os.chdir(path)
@staticmethod
def SHUT_DOWN():
_os.system("shutdown /s /t 1")
@staticmethod
def RESTART():
_os.system("shutdown /r /t 1")
@staticmethod
def terminal_size() -> tuple:
size= _os.get_terminal_size()
return (size.columns,size.lines)
@staticmethod
def cwd():
return _os.getcwd()
@staticmethod
def ip_global():
try:
import requests
new_session = _requests.session()
response = new_session.get("http://ipinfo.io/ip")
import re
ip_list = _re.findall(r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}", response.text)
new_session.close()
return ip_list[0]
except:
raise ConnectionError('No Internet Connection') from None
@staticmethod
def ip_local():
#return [l for l in ([ip for ip in _socket.gethostbyname_ex(_socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [_socket._socket.(_socket.AF_INET, _socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
import platform
class NetworkError(Exception):
def __init__(self, message): super().__init__(message)
try:
ip = _socket.gethostbyname(_socket.gethostname())
if ip and ip != "127.0.1.1":
return ip
elif platform.system() != "Windows":
import subprocess
command = _subprocess.Popen(["hostname", "-I"],stdout=_subprocess.PIPE,stderr=_subprocess.PIPE,stdin=_subprocess.PIPE,shell=False)
response = list(command.communicate())
if len(response[0]) > 0:
return str(response[0])[2:-4]
raise NetworkError('No Network Connection')
raise NetworkError('No Network Connection')
except:
raise
@staticmethod
def ram_total(convert=True):
response = list(_psutil.virtual_memory())
if convert:
return convert_bytes(int(response[0]))
return str(response[0])
@staticmethod
def ram_used(convert=True):
response = list(_psutil.virtual_memory())
if convert:
return convert_bytes(int(response[3]))
return str(response[3])
@staticmethod
def ram_free(convert=True):
response = list(_psutil.virtual_memory())
if convert:
return convert_bytes(int(response[1]))
return str(response[1])
@staticmethod
def ram_percent(ONLY_NOM=False):
response = list(_psutil.virtual_memory())
if ONLY_NOM:
return response[2]
return str(response[2]) + " %"
@staticmethod
def boot_time():
return _psutil.boot_time()
@staticmethod
def device_name():
return _socket.gethostname()
@staticmethod
def ip_website(url):
return _socket.gethostbyname(url)
@staticmethod
def win10_notification(title,message,icon=None, duration=5) -> None:
try:
from win10toast import ToastNotifier
ToastNotifier().show_toast(title,message,duration=duration)
except:
raise ImportError('Use "pip install win10toast" to install required module')
@staticmethod
def cpu_count(logical=True):
return _psutil.cpu_count(logical)
@staticmethod
def pyshell_execute_bit():
#return platform.architecture()[0][:2] # SLOW
#return ctypes.sizeof(ctypes.c_voidp)*8
import struct
return struct.calcsize("P") * 8
@staticmethod
def pids() -> list:
return _psutil.pids()
@staticmethod
def cpu_percent() -> float:
return _psutil.cpu_percent()
@staticmethod
def pid_exists(pid) -> bool:
return _psutil.pid_exists(pid)
@staticmethod
def mac_address(formatted=False):
import uuid
mac = uuid.getnode()
if formatted:
return ':'.join(['{:02x}'.format((mac >> ele) & 0xff) for ele in range(0,8*6,8)][::-1])
return hex(mac)
system = System
from colored import fg as _fg
from colored import bg as _bg
from colored import attr as _attr
class Style:
def __init__(self, text, color='default', BG='black'):
try:
self.color = color.lower()
self.BG = BG.lower()
#style = style.lower()
except:
pass
if color == 'default':
self.color = 7 #188
self.text = text
self.content = f"{_fg(color)}{_bg(BG)}{text}{_attr(0)}"
def __str__(self):
return self.content
def __repr__(self):
return self.content
def __add__(self, other):
#print(type(other))
if type(other)!=style:
return self.content+other
else:
return self.content+other.content
@staticmethod
def print(text='', color='default', BG='default', style=None, end='\n'):
try:
color = color.lower()
BG = BG.lower()
style = style.lower() if style and type(style)==str else 0
except:
raise
if style == 'none':
style = 0
if color=='default' and BG!='default': # _bg & !clr
print(f'{_attr(style)}{_bg(BG)}{text}{_attr(0)}', end=end)
elif color!='default' and BG=='default': # !_bg & clr
print(f'{_attr(style)}{_fg(color)}{text}{_attr(0)}', end=end)
elif color=='default' and BG=='default': # !_bg & !clr
print(f'{_attr(style)}{text}{_attr(0)}', end=end)
elif color!='default' and BG!='default': # _bg & clr
print(f'{_attr(style)}{_bg(BG)}{_fg(color)}{text}{_attr(0)}', end=end)
@staticmethod
def switch(color='default', BG='black', style='None'):
try:
color = color.lower()
BG = BG.lower()
style = style.lower()
except:
pass
if style == 'none':
style = 0
if color == 'default':
color = 7
print(f'{_attr(style)}{_bg(BG)}{_fg(color)}', end='')
@staticmethod
def switch_default():
print(f'{_attr(0)}', end='')
reset = switch_default
@staticmethod
def log_success(text, color='green', BG='default', style=None, add_time=True):
#globals()['style'].print(text, color, BG, style=style)
NOW = _time.strftime('%H:%M:%S',_time.localtime()) if add_time else ''
globals()['style'].print(NOW, color, BG,end=' ')
globals()['style'].print(text, color, BG, style=style)
@staticmethod
def log_info(text, color='grey_93', BG='default', style=None, add_time=True):
NOW = _time.strftime('%H:%M:%S',_time.localtime()) if add_time else ''
globals()['style'].print(NOW, color, BG,end=' ')
globals()['style'].print(text, color, BG, style=style)
@staticmethod
def log_warning(text, color='gold_3a', BG='default', style=None, add_time=True):
NOW = _time.strftime('%H:%M:%S',_time.localtime()) if add_time else ''
globals()['style'].print(NOW, color, BG,end=' ')
globals()['style'].print(text, color, BG, style=style)
@staticmethod
def log_error(text, color='red', BG='default', style=None, add_time=True):
NOW = _time.strftime('%H:%M:%S',_time.localtime()) if add_time else ''
globals()['style'].print(NOW, color, BG,end=' ')
globals()['style'].print(text, color, BG, style=style)
@staticmethod
def log_critical(text, color='red_1', BG='default', style='bold', add_time=True):
NOW = _time.strftime('%H:%M:%S',_time.localtime()) if add_time else ''
globals()['style'].print(NOW, color, BG,end=' ')
globals()['style'].print(text, color, BG, style=style)
style = Style
class Record:
def __init__(self):
self.__start = _time.time()
self.laps = []
def __call__(self):
return f'Laps: {self.laps}'
def __repr__(self):
return f'Laps: {self.laps}'
def lap(self, save=True, Round=15):
lp = _time.time() - self.__start
lp = round(lp,Round)
if save:
self.laps.append(lp)
return lp
def reset(self, reset_start=False):
self.laps = []
if reset_start:
self.__start = _time.time()
def last_lap(self, save=True):
ret = (self.lap(False)-self.laps[-1]) if self.laps else self.lap(False)
if save:
self.laps.append(self.lap())
return ret
@staticmethod
def timit(code,setup,times,globals_):
import timeit
return timeit.timeit(stmt=code,setup=setup,number=times,globals=globals_)
record = Record
class Terminal:
@staticmethod
def run(command:str) -> None:
_os.system(command)
@staticmethod
def getoutput(command:str) -> str:
return _subprocess.getoutput(command)
terminal = Terminal
class Decorator:
class Check_Type:
auto_correct = False
def __init__(self, function):
self.function = function
def __call__(self, *args, **kwargs):
special_types = ('callable', 'iterable', 'generator','container', 'any')
i=-1
__local__= list(locals()['args'])
annots= list(self.function.__annotations__.keys())
def extra_remover(correct):
# Typing module annots check
if correct.startswith('typing.'):
correct = correct[7:].lower()
# built-in types check
elif correct.startswith('<class '):
correct = correct[8:-2]
return correct
def check_specials(TYPE, LOCAL_I):
import inspect
wrong = ''
if TYPE == 'generator':
if inspect.isgeneratorfunction(LOCAL_I) or inspect.isgenerator(LOCAL_I):
return
else:
correct = 'generator'
elif TYPE == 'callable':
if callable(LOCAL_I):
return
else:
correct = 'callable'
elif TYPE == 'iterable':
if type(LOCAL_I) in (list, tuple, set, str):
print(type(LOCAL_I))
return
else:
correct = 'iterable'
elif TYPE == 'container':
if type(LOCAL_I) in (list,set,dict,tuple):
return
else:
correct = 'container'
elif TYPE == 'any':
return
wrong = extra_remover(str(type(LOCAL_I))) if not wrong else wrong
func_name = self.function.__name__
Error= TypeError(f"'{func_name}()' argument '{ARG}' must be '{correct}' (not '{wrong}')")
raise Error
for ARG in annots:
i += 1
try:
LOCAL_I = __local__[i]
correct = str(self.function.__annotations__[ARG])
correct = extra_remover(correct)
if correct in special_types:
print(type(LOCAL_I))
check_specials(correct,LOCAL_I)
# Builtins and other Libraries objects
elif not eval(correct) == type(LOCAL_I):
if Check_Type.auto_correct:
try:
__local__[i] = eval(correct)(LOCAL_I)
continue
except ValueError:
pass
wrong = extra_remover(str(type(LOCAL_I)))
#correct = str(self.function.__annotations__[ARG])#[8:-2]
correct = extra_remover(correct)
func_name = self.function.__name__
Error= TypeError(f"'{func_name}()' argument '{ARG}' must be '{correct}' (not '{wrong}')")
raise Error
except (ValueError,IndexError):
pass#raise
except NameError:
raise
return self.function(*__local__, **kwargs)
decorator_all:Callable = None
@staticmethod
def attach_to_all(cls):
import inspect
for name, method in inspect.getmembers(cls):
if (not inspect.ismethod(method) and
not inspect.isfunction(method) ) or (
inspect.isbuiltin(method)):
continue
#print("Decorating function %s" % name)
setattr(cls, name, Decorator.decorator_all(method))
return cls
abstractmethod = _abc.abstractmethod
_registered_functions = {} #:Dict[str, Any]
class _MultiMethod(object):
def __init__(self, name):
self.name = name
self.typemap = {}
def __call__(self, *args):
types = tuple(arg.__class__ for arg in args)
function = self.typemap.get(types)
if function is None:
raise TypeError("no match: ",types)
return function(*args)
def register(self, types, function):
self.typemap[types] = function
def overload(*types):
def register(function):
name = function.__name__
mm = decorator._registered_functions.get(name)
if mm is None:
mm = decorator._registered_functions[name] = Decorator._MultiMethod(name)
mm.register(types, function)
return mm
return register
decorator = Decorator
Check_Type = Decorator.Check_Type
overload = Decorator.overload
class IO:
@staticmethod
def wait_for_input(prompt,SS:list=[]):
answer= ''
try:
while not answer:
answer = input(prompt).strip()
except (EOFError,KeyboardInterrupt):
style.print('EXITING...','red')
exit()
return answer
@staticmethod
def selective_input(prompt,choices,default=None,ignore_case=False,error=True,invalid='Invalid input'):
if type(choices) == dict:
Choices = list(choices.keys())+list(choices.values())
pass
if ignore_case:
Choices = [item.lower() for item in Choices]
while True:
inp = input(prompt)
inp = inp.lower() if ignore_case else inp
if not inp or inp not in Choices:
if error:
style.print(invalid, 'red')
else:
if default:
inp = default
break
else:
break
if type(choices) == dict:
try:
inp = choices[inp]
except KeyError:
pass
return inp
@staticmethod
def yesno_input(prompt,default=None):
error= not bool(default)
return io.selective_input(prompt,['y','yes','n','no'],default,error)
@staticmethod
def Input(prompt:str ='', default_value:str =''):
import win32console
_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
keys = []
for c in str(default_value):
evt = win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)
evt.Char = c
evt.RepeatCount = 1
evt.KeyDown = True
keys.append(evt)
_stdin.WriteConsoleInput(keys)
return input(str(prompt))
@staticmethod
def getpass(prompt):
import getpass as Getpass
return Getpass.getpass(prompt=prompt)
io = IO
Input = default_input = io.Input
getpass = password_input = io.getpass
class Tuple:
#############################
def __init__(self,*var: Any, one_item=False):
if not one_item:
self.__content= tuple(var)
else:
self.__content=[]
for item in var:
for member in item:
self.__content.append(member)
self.__content= tuple(self.__content)
def __str__(self):
return str(self.__content)
def __repr__(self):
return str(self.__content)
#############################
#############################
def add(self,*var: Any):
self.__content= tuple(list(self.__content)+[v for v in var])
#force= lambda tpl,*var: tuple(list(tpl)+[v for v in var])
force= add
def remove(self,*var: Any):
#lstv= [v for v in var if v in tpl]
lstt= list(self.__content)
for th in [v for v in var if v in self.__content]:
lstt.remove(th)
self.__content= tuple(lstt)
erase= remove
def pop(self,index):
return pop(self.__content)
#############################
#############################
def replace(self, ind: Union[int,Any], var: Any):
tpl=list(self.__content)
if type(ind) == str:
ind= tpl.index(ind)
tpl[ind]=var
self.__content= tuple(tpl)
def __setitem__(self,index,value,replace=False):
if not replace:
tpl=list(self.__content)
if type(index) == str:
ind= tpl.index(index)
tpl.insert(index,value)
self.__content= tuple(tpl)
else:
self.replace(index,value)
def __getitem__(self,index):
return self.__content[index]
#############################
def __add__(self,other):
return self.__content + other
def __contains__(self,var):
return var in self.__content
#############################
#############################
def __bool__(self):
return bool(len(self.__content))
def __hash__(self):
return hash(self.__content)
def __len__(self):
return len(self.__content)
#############################
#############################
_ReqConErr = _requests.exceptions.ConnectionError
class Internet:
@staticmethod
def is_connected(website='http://x.com/'):
try:
_urllib.request.urlopen(website)
return True
except:
return False
def connection_checker(func):
def inside(*args,**kwargs):
if not internet.is_connected():
raise ConnectionError('No internet connection') from None
return func(*args,**kwargs)
return inside
@staticmethod
def ip_global() -> str:
new_session = _requests.session()
response = new_session.get("http://ipinfo.io/ip")
ip_list = _re.findall(r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}", response.text)
new_session.close()
return ip_list[0]
@staticmethod
def ip_local() -> str:
#return [l for l in ([ip for ip in _socket.gethostbyname_ex(_socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [_socket._socket.(_socket.AF_INET, _socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
import platform
class NetworkError(Exception):
def __init__(self, message): super().__init__(message)
try:
ip = _socket.gethostbyname(_socket.gethostname())
if ip and ip not in ("127.0.1.1","127.0.0.1"):
return ip
elif platform.system() != "Windows":
command = _subprocess.Popen(["hostname", "-I"],stdout=_subprocess.PIPE,stderr=_subprocess.PIPE,stdin=_subprocess.PIPE,shell=False)
response = list(command.communicate())
if len(response[0]) > 0:
return str(response[0])[2:-4]
raise NetworkError('No Network Connection')
raise NetworkError('No Network Connection')
except:
raise
@staticmethod
def url_exists(URL) -> bool:
try:
request = _requests.get(URL)
except _ReqConErr:
raise ConnectionError('No internet connection') from None
#print(response.status_code < 400)
if request.status_code == 200:
return True
else:
return False
@staticmethod
def ip_website(URL) -> str:
try:
return _socket.gethostbyname(URL)
except _socket.gaierror:
if internet.is_connected():
class NotExistsError(Exception):
def __init__(self):
super().__init__('URL Does Not Exists')
raise NotExistsError from None
else:
raise ConnectionError from None
@staticmethod
def url_links(URL) -> list:
try:
soup= BeautifulSoup(_requests.get(URL).text,features="lxml")
LINKS= []
for link in soup.find_all('a'):
LINKS.append(link.get('href'))
return LINKS
except _ReqConErr:
raise ConnectionError('No internet connection') from None
@staticmethod
def find_urls(string) -> list:
url = _re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', string)
return url
@staticmethod
def is_url(URL) -> bool:
search= _re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', URL)
if search and len(search.group())==len(URL):
return True
else:
return False
@staticmethod
def open_browser(url,new_tab=True):
import webbrowser
if new_tab:
webbrowser.open_new_tab(url)
else:
webbrowser.open(url)
internet = Internet
class DateTime:
_NOW= 0
_NOW_YEAR= 0
_NOW_MONTH= 0
_NOW_DAY= 0
_NOW_HOUR= -1
_NOW_MINUTE= -1
_NOW_SECOND= -1
def NOW():
_NOW= _time.localtime()
_NOW_YEAR= _NOW.tm_year
_NOW_MONTH= _NOW.tm_mon
_NOW_DAY= _NOW.tm_mday
_NOW_HOUR= _NOW.tm_hour
_NOW_MINUTE= _NOW.tm_min
_NOW_SECOND= _NOW.tm_sec
return _datetime.datetime(_NOW_YEAR,_NOW_MONTH,_NOW_DAY,_NOW_HOUR,_NOW_MINUTE,_NOW_SECOND)
now = NOW
def normalize(date=[],time=[]):
now = date_time.NOW()
try:
if not date[0]: date[0]= now.year
if type(date[1]) == str:
try:
date[1]= date_time.month_dic[date[1].lower()]
except KeyError:
raise ValueError("Wrong Month Name") from None
if not date[1]: date[1]= now.month
if not date[2]: date[2]= now.day
except IndexError:
pass
try:
if time[0]<0: now.hour
if time[1]<0: now.minute
if time[2]<0: now.second
except IndexError:
pass
return [date,time]
Weekday_Names= ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
month_lst= ['january','february','march','april','may','june',
'july','august','september','october','november','december']
month_dic= {month:month_nom for month in month_lst for month_nom in range(1,13)}
def __init__(self,year=_NOW_YEAR,month=_NOW_MONTH,day=_NOW_DAY,hour=_NOW_HOUR,minute=_NOW_MINUTE,second=_NOW_SECOND,first_week_day=0):
_norm = date_time.normalize([year,month,day],[hour,minute,second])
year,month,day = _norm[0]
hour,minute,second = _norm[1]
if type(month)==str:
try:
month= date_time.month_dic[month.lower()]
except KeyError:
raise ValueError("Wrong Month Name") from None
self.date= _datetime.date(year,month,day)
self.year=year; self.month=month; self.day=day
self.time= (hour,minute,second)
self.hour=hour; self.minute=minute; self.second=second
self.weekday= date_time.get_weekday(self.year,self.month,self.day)
self.weekday_name= date_time.get_weekday(self.year,self.month,self.day,True)
self.week_nom= date_time.get_weeknom(self.year,self.month,self.day)
#self.first_week_day= first_week_day
_calendar.setfirstweekday(first_week_day)
self.calendar= str(_calendar.month(year, month)).replace(str(day),style(str(day),'green').content)
self.calendar_month= str(_calendar.month(year, month))
self.calendar_year_all=str(_calendar.calendar(year))
self.calendar_year= [_calendar.month(year,i) for i in range(1,13)]
self.calendar_next_all= [_calendar.month(year,i) for i in range(self.month+1,13)]
self.calendar_prev_all= [_calendar.month(year,i) for i in range(1,self.month)]
self.calendar_position_next_year= str(_calendar.month(year+1, month)).replace(str(day),style(str(day),'green').content)
self.calendar_position_prev_year= str(_calendar.month(year-1, month)).replace(str(day),style(str(day),'green').content)
def setfirstweekday(self,day):
if type(day)==int and day<7:
date_time.Weekday_Names= date_time.Weekday_Names[day:]+date_time.Weekday_Names[:day]
elif type(day)==str:
day= date_time.Weekday_Names.index(day)
date_time.Weekday_Names= date_time.Weekday_Names[day:]+date_time.Weekday_Names[:day]
else:
if type(day)==int:
raise ValueError('Invalid Nomber. Day number should be in range(7)')
else:
raise TypeError(f"Inappropriate Type For 'day'. day can be 'str' or 'int' not {type(day)}")
_calendar.setfirstweekday(day)
self.calendar= str(_calendar.month(self.year, self.month)).replace(str(day),style(str(day),'green').content)
self.calendar_month= str(_calendar.month(self.year, self.month))
self.calendar_year_all=str(_calendar.calendar(self.year))
self.calendar_year= [_calendar.month(self.year,i) for i in range(1,13)]
self.calendar_next_all= [_calendar.month(self.year,i) for i in range(self.month+1,13)]
self.calendar_prev_all= [_calendar.month(self.year,i) for i in range(1,self.month)]
self.calendar_position_next_year= str(_calendar.month(self.year+1, self.month)).replace(str(day),style(str(day),'green').content)
self.calendar_position_prev_year= str(_calendar.month(self.year-1, self.month)).replace(str(day),style(str(day),'green').content)
self.weekday= date_time.get_weekday(self.year,self.month,self.day)
self.weekday_name= date_time.get_weekday(self.year,self.month,self.day,True)
self.week_nom= date_time.get_weeknom(self.year,self.month,self.day)
@staticmethod
def today():
dt = date_time.NOW()
return (dt.year,dt.month,dt.day)
@staticmethod
def calender_year(year=_NOW_YEAR):
if not year: year=date_time.NOW().year
return [_calendar.month(year,i) for i in range(1,13)]
@staticmethod
def calendar_month_st(month=_NOW_MONTH,year=_NOW_YEAR,day=0):
year,month = date_time.normalize([year,month])[0]
if not day:
return str(_calendar.month(year, month))
else:
return str(_calendar.month(year, month)).replace(str(day),style(str(day),'green').content)
@staticmethod
def passed_date(f_date,l_date=_NOW,return_time='day'):
if not l_date: l_date=date_time.NOW()
f_date = _datetime.datetime(*f_date)
return_time= return_time.lower()
if return_time in ('day','month','year','hour','minute','second'):
DELTA= l_date - f_date
if return_time == 'year':
try:
_return = _re.search(r'(?P<X>(-)?\w+) day',str(DELTA/365)).group('X')
except:
_return = None
#_return = str(DELTA/365)
elif return_time == 'month':
_return = _re.search(r'\w+',str(DELTA/30)).group()
elif return_time == 'day':
_return = str(DELTA)[:-14]
elif return_time =='hour':
_return = str(DELTA*24)[:-14]
elif return_time == 'minute':
_return = str(DELTA*1440)[:-14]
elif return_time == 'second':
_return = str(DELTA*3600)[:-14]
if _return: return _return
else: return 0
else:
raise ValueError("return_time should be in ('year', 'month', 'day', 'hour', 'minute', 'second')")
passed_time = passed_date
@staticmethod
def convert_epoch_to_local(second=_time.time()):
return _time.ctime(second)
@staticmethod
def get_weekday(year=_NOW_YEAR,month=_NOW_MONTH,day=_NOW_DAY,return_name=False):
year,month,day = date_time.normalize([year,month,day])[0]
if return_name:
return date_time.Weekday_Names[_datetime.date(year,month,day).weekday()]
else:
return _datetime.date(year,month,day).weekday()
@staticmethod
def get_weeknom(year=_NOW_YEAR,month=_NOW_MONTH,day=_NOW_DAY):
year,month,day = date_time.normalize([year,month,day])[0]
return _datetime.date(year,month,day).isocalendar()[1]
@staticmethod
def calendar_show_week(week_nom,year=_NOW_YEAR):
year = date_time.normalize([year])[0][0]
week= week_nom
for i in list(range(1,8))[::-1]:
if date_time.get_weeknom(year,1,i)==1:
FIRST_WEEK_DAYS= len(list(range(i)))
break
day= (week-1)*7 - (6-FIRST_WEEK_DAYS)
mnth= 1
true=False
while not true:
try:
if _calendar.monthrange(year,mnth)[1]<day:
mnth+=1
day-= _calendar.monthrange(year,mnth)[1]
else:
true= True
except _calendar.IllegalMonthError:
class BadWeekNumber(Exception):
def __init__(self, message='Week Number is Higher Than Year Weeks.'): super().__init__(message)
raise BadWeekNumber from None
new= date_time(year,mnth,day)
cal= new.calendar_month.splitlines()
for item in cal:
if str(new.day) in item and item != cal[0]:
INDEX= cal.index(item);COLORED_WEEK= style(item,'green');break
WEEK_WITH_COLOR= '\n'.join(cal[:INDEX]+[str(COLORED_WEEK)]+cal[INDEX+1:])
return WEEK_WITH_COLOR
@staticmethod
def get_year():
return _time.localtime().tm_year
@staticmethod
def get_month():
return _time.localtime().tm_mon
@staticmethod
def get_day_of_month():
return _time.localtime().tm_mday
@staticmethod
def get_day_of_week():
return _time.localtime().tm_wday
@staticmethod
def get_day_of_year():
return _time.localtime().tm_yday
@staticmethod
def get_hour():
return _time.localtime().tm_hour
@staticmethod
def get_minute():
return _time.localtime().tm_min
@staticmethod
def get_second():
return _time.localtime().tm_sec
date_time = DateTime
_Auto = 0
class _Lang:
class Constant:
def __new__(cls,*args,array=True):
cls._init = False
return super(_Lang.Constant, cls).__new__(cls)
def __init__(self,*args,array=True):
self.__members = args
self._init = True
def __str__(self):
#if len(self.__members) > 1:
return '<'+str(self.__members)[1:-1]+'>' #‹›
#return self.__members
def __repr__(self):
return '<'+str(self.__members)[1:-1]+'>'
def __setattr__(self,_attr,value):
if self._init:
raise AttributeError(f"'Constant' object does not support item assignment")
else:
super(_Lang.Constant,self).__setattr__(_attr,value)
def __getitem__(self,index):
return self.__members[index]
def __contains__(self,obj):
return obj in self.__members
def __bool__(self):
return bool(len(self.__members))
#'''
def __hash__(self):
return hash(tuple(['Constant',len(self)]+list(self.__members)))
#'''
def __len__(self):
#if type(self.__members) == tuple:
return len(self.__members)
def _dict_getter(self):
raise AttributeError("Conatant object has no attribute '__dict__'")
#return {}
__dict__ = property(_dict_getter)
def __dir__(self):
ret = list(super().__dir__())#[:-2]
ret.remove('_init')
ret.remove('_dict_getter')
return ret
const = Const = constant = Constant
class Array:
# Sized Array
__Type_Error = "Array of type '{}' does not accept object with type '{}'"
def __init__(self,*args,type_=_Auto,size=_Auto):
self.__members = []
if type_:
self.__TYPE = type_
else:
self.__TYPE = type(args[0])
self.__TYPE_NAME = self.__TYPE.__name__
if size:
self.__SIZE = size
else:
self.__SIZE = len(args)
for obj in args:
if type(obj) == self.__TYPE:
self.__members.append(obj)
else:
raise ValueError(_Lang.Array.__Type_Error.format(self.__TYPE_NAME,type(obj).__name__))
def __str__(self):
return '{'+str(self.__members)[1:-1]+'}' #‹›
def __repr__(self):
return '{'+str(self.__members)[1:-1]+'}'
def __getitem__(self,index):
return self.__members[index]
def __contains__(self,obj):
return obj in self.__members
def __bool__(self):
return bool(len(self.__members))
def __len__(self):
return len(self.__members)
def __setitem__(self,index,obj):
if type(obj) == self.__TYPE:
self.__members.insert(index,obj)
return
raise ValueError(_Lang.Array.__Type_Error.format(self.__TYPE_NAME,type(obj).__name__))
def insert(self,index,obj):
if type(obj) == self.__TYPE:
self.__members.insert(index,obj)
return
raise ValueError(_Lang.Array.__Type_Error.format(self.__TYPE_NAME,type(obj).__name__))
def append(self,obj):
if type(obj) == self.__TYPE:
self.__members.append(obj)
return
raise ValueError(_Lang.Array.__Type_Error.format(self.__TYPE_NAME,type(obj).__name__))
add = append
def remove(self,obj):
self.__members.remove(obj)
def pop(self,index=-1):
self.__members.pop(index)
array = Array
class Types:
Str = str
Int = int
Float = float
Set = set
Tuple = tuple
Dict = dict
List = list
Bool = bool
Bytes = bytes
Class = type
Type = type
Object = object
Lambda = type(lambda: None)
Function = Lambda #type(lambda: None)
#Constant = type(_Lang.Constant(1))
#Array = type(_Lang.Array(1,1))
Any = type#_typing.Any
Callable = _typing.Callable
Container = _typing.Container
Generator = Lambda #type(_f) #Not Built-in(s) #_types.GeneratorType || _typing.Generator
Iterable = _typing.Iterable
Iterator = _typing.Iterator
NoReturn = _typing.NoReturn
Optional = _typing.Optional
BuiltinFunction = type(len)
BuiltinMethod = type([].append)
Module = type(_typing)
Method = type(globals()['Tuple']().force)
#Mapping = _typing.Mapping
#OrderedDict = _typing.OrderedDict
#Text = str
#Union = _typing.Union
#_types.AsyncGeneratorType
types = Types
#setattr(_Lang,'Const',type(_Lang.Constant(1)))
#setattr(_Lang,'Array',type(_Lang.Array(1,1)))
#END
| true | true |
f73bb19619c019dc12e0183f60850cb0c0904636 | 3,504 | py | Python | asyncmc/host.py | ContextLogic/asyncmc | 1091d06f70e8d6b22914a33f9fad3f0480dde6ef | [
"MIT"
] | null | null | null | asyncmc/host.py | ContextLogic/asyncmc | 1091d06f70e8d6b22914a33f9fad3f0480dde6ef | [
"MIT"
] | null | null | null | asyncmc/host.py | ContextLogic/asyncmc | 1091d06f70e8d6b22914a33f9fad3f0480dde6ef | [
"MIT"
] | null | null | null | import socket
import time
# import logging
import tornado.ioloop
import tornado.iostream
from tornado import gen
from . import constants
from . import exceptions
class Host(object):
def __init__(self, host, conn, debug=0):
self.debug = debug
self.host = host
self.port = 11211
self.flush_on_reconnect = 1
self.stream = None
self.flush_on_next_connect = 0
self.dead_retry = constants.DEAD_RETRY
self.deaduntil = 0
if ":" in self.host:
parts = self.host.rsplit(":", 1)
self.host = parts[0]
self.port = int(parts[1])
if self.host.startswith('[') and self.host.endswith(']'):
self.host = self.host[1:-1]
self.sock = None
def _ensure_connection(self):
if self.sock:
return self
remaining = constants.SOCKET_TIMEOUT
last_error = None
for family, socktype, proto, _, addr in socket.getaddrinfo(
self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM
):
if not remaining:
self.mark_dead('connect: no time left')
return None
try:
s = socket.socket(family, socktype, proto)
s.settimeout(remaining)
start = time.time()
s.connect(addr)
break
except socket.timeout as msg:
self.mark_dead('connect: {}'.format(msg))
return None
except socket.error as msg:
if isinstance(msg, tuple):
msg = msg[1]
last_error = msg
s.close()
duration = time.time() - start
remaining = max(remaining - duration, 0)
else:
# if we never broke out of the getaddr loop
self.mark_dead('connect: {}'.format(last_error))
return None
self.sock = s
self.stream = tornado.iostream.IOStream(s)
self.stream.debug = True
return self
def _check_dead(self):
if self.deaduntil and self.deaduntil > time.time():
return 1
self.deaduntil = 0
return 0
def mark_dead(self, reason):
self.disconect_reason = str(reason)
self.deaduntil = time.time() + self.dead_retry
if self.flush_on_reconnect:
self.flush_on_next_connect = 1
self.close_socket()
def close_socket(self):
if self.sock:
self.stream.close()
self.sock.close()
self.sock = None
def raise_if_disconnect(self):
if hasattr(self, 'disconect_reason'):
raise exceptions.ConnectionDeadError(
'socket host "{}" port "{}" disconected because "{}"'.format(
self.host,
self.port,
self.disconect_reason
)
)
@gen.coroutine
def send_cmd(self, cmd, noreply=False, stream=False):
if self._ensure_connection() is None:
self.raise_if_disconnect()
cmd = cmd + "\r\n".encode()
if stream:
yield self.stream.write(cmd)
raise gen.Return(self.stream)
elif self.stream:
yield self.stream.write(cmd)
if not noreply and self.stream:
response = yield self.stream.read_until(b'\r\n')
raise gen.Return(response[:-2])
self.raise_if_disconnect()
| 30.736842 | 77 | 0.544521 | import socket
import time
import tornado.ioloop
import tornado.iostream
from tornado import gen
from . import constants
from . import exceptions
class Host(object):
def __init__(self, host, conn, debug=0):
self.debug = debug
self.host = host
self.port = 11211
self.flush_on_reconnect = 1
self.stream = None
self.flush_on_next_connect = 0
self.dead_retry = constants.DEAD_RETRY
self.deaduntil = 0
if ":" in self.host:
parts = self.host.rsplit(":", 1)
self.host = parts[0]
self.port = int(parts[1])
if self.host.startswith('[') and self.host.endswith(']'):
self.host = self.host[1:-1]
self.sock = None
def _ensure_connection(self):
if self.sock:
return self
remaining = constants.SOCKET_TIMEOUT
last_error = None
for family, socktype, proto, _, addr in socket.getaddrinfo(
self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM
):
if not remaining:
self.mark_dead('connect: no time left')
return None
try:
s = socket.socket(family, socktype, proto)
s.settimeout(remaining)
start = time.time()
s.connect(addr)
break
except socket.timeout as msg:
self.mark_dead('connect: {}'.format(msg))
return None
except socket.error as msg:
if isinstance(msg, tuple):
msg = msg[1]
last_error = msg
s.close()
duration = time.time() - start
remaining = max(remaining - duration, 0)
else:
self.mark_dead('connect: {}'.format(last_error))
return None
self.sock = s
self.stream = tornado.iostream.IOStream(s)
self.stream.debug = True
return self
def _check_dead(self):
if self.deaduntil and self.deaduntil > time.time():
return 1
self.deaduntil = 0
return 0
def mark_dead(self, reason):
self.disconect_reason = str(reason)
self.deaduntil = time.time() + self.dead_retry
if self.flush_on_reconnect:
self.flush_on_next_connect = 1
self.close_socket()
def close_socket(self):
if self.sock:
self.stream.close()
self.sock.close()
self.sock = None
def raise_if_disconnect(self):
if hasattr(self, 'disconect_reason'):
raise exceptions.ConnectionDeadError(
'socket host "{}" port "{}" disconected because "{}"'.format(
self.host,
self.port,
self.disconect_reason
)
)
@gen.coroutine
def send_cmd(self, cmd, noreply=False, stream=False):
if self._ensure_connection() is None:
self.raise_if_disconnect()
cmd = cmd + "\r\n".encode()
if stream:
yield self.stream.write(cmd)
raise gen.Return(self.stream)
elif self.stream:
yield self.stream.write(cmd)
if not noreply and self.stream:
response = yield self.stream.read_until(b'\r\n')
raise gen.Return(response[:-2])
self.raise_if_disconnect()
| true | true |
f73bb217822f915c58dae277c970281d9f9cbeb8 | 4,808 | py | Python | configs/recognition/tsm/train_kinetics10_tsm_DEAR.py | Cogito2012/DEAR | 97d0e8f191da0f20dcc9721280af48171dabef5e | [
"Apache-2.0"
] | 47 | 2021-09-02T10:42:29.000Z | 2022-03-31T01:37:49.000Z | configs/recognition/tsm/train_kinetics10_tsm_DEAR.py | Cogito2012/DEAR | 97d0e8f191da0f20dcc9721280af48171dabef5e | [
"Apache-2.0"
] | 2 | 2021-12-05T02:28:42.000Z | 2022-01-05T06:46:10.000Z | configs/recognition/tsm/train_kinetics10_tsm_DEAR.py | Cogito2012/DEAR | 97d0e8f191da0f20dcc9721280af48171dabef5e | [
"Apache-2.0"
] | 6 | 2021-09-19T16:31:32.000Z | 2022-03-03T06:57:34.000Z | # model settings
evidence_loss = dict(type='EvidenceLoss',
num_classes=101,
evidence='exp',
loss_type='log',
with_kldiv=False,
with_avuloss=True,
annealing_method='exp')
model = dict(
type='Recognizer2D',
backbone=dict(
type='ResNetTSM',
pretrained='torchvision://resnet50',
depth=50,
norm_eval=False,
shift_div=8),
cls_head=dict(
type='TSMHead',
loss_cls=evidence_loss,
num_classes=101,
in_channels=2048,
spatial_type='avg',
consensus=dict(type='AvgConsensus', dim=1),
dropout_ratio=0.5,
init_std=0.001,
is_shift=True),
debias_head=dict(
type='DebiasHead',
loss_cls=evidence_loss, # actually not used!
loss_factor=0.1,
num_classes=101,
in_channels=2048,
dropout_ratio=0.5,
init_std=0.01))
# model training and testing settings
train_cfg = None
test_cfg = dict(average_clips='evidence', evidence_type='exp')
# dataset settings
dataset_type = 'VideoDataset'
data_root = 'data/kinetics10/videos_train'
data_root_val = 'data/kinetics10/videos_val'
ann_file_train = 'data/kinetics10/kinetics10_train_list_videos.txt'
ann_file_val = 'data/kinetics10/kinetics10_val_list_videos.txt'
ann_file_test = 'data/kinetics10/kinetics10_val_list_videos.txt'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False)
train_pipeline = [
dict(type='OpenCVInit', num_threads=1),
dict(type='DenseSampleFrames', clip_len=1, frame_interval=1, num_clips=8),
dict(type='OpenCVDecode'),
dict(type='Resize', scale=(-1, 256)),
dict(
type='MultiScaleCrop',
input_size=224,
scales=(1, 0.875, 0.75, 0.66),
random_crop=False,
max_wh_scale_gap=1,
num_fixed_crops=13),
dict(type='Resize', scale=(224, 224), keep_ratio=False),
dict(type='Flip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs', 'label'])
]
val_pipeline = [
dict(type='OpenCVInit', num_threads=1),
dict(
type='DenseSampleFrames',
clip_len=1,
frame_interval=1,
num_clips=8,
test_mode=True),
dict(type='OpenCVDecode'),
dict(type='Resize', scale=(-1, 256)),
dict(type='CenterCrop', crop_size=224),
dict(type='Flip', flip_ratio=0),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs'])
]
test_pipeline = [
dict(type='OpenCVInit', num_threads=1),
dict(
type='DenseSampleFrames',
clip_len=1,
frame_interval=1,
num_clips=8,
test_mode=True),
dict(type='OpenCVDecode'),
dict(type='Resize', scale=(-1, 256)),
dict(type='CenterCrop', crop_size=224),
dict(type='Flip', flip_ratio=0),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs'])
]
data = dict(
videos_per_gpu=4,
workers_per_gpu=4,
val_dataloader=dict(videos_per_gpu=4),
train=dict(
type=dataset_type,
ann_file=ann_file_train,
data_prefix=data_root,
start_index=0,
pipeline=train_pipeline),
val=dict(
type=dataset_type,
ann_file=ann_file_val,
data_prefix=data_root_val,
start_index=0,
pipeline=val_pipeline),
test=dict(
type=dataset_type,
ann_file=ann_file_test,
data_prefix=data_root_val,
start_index=0,
pipeline=test_pipeline))
# optimizer
optimizer = dict(
type='SGD',
constructor='TSMOptimizerConstructor',
paramwise_cfg=dict(fc_lr5=True),
lr=0.001, # this lr is used for 8 gpus
momentum=0.9,
weight_decay=0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=20, norm_type=2))
# learning policy
lr_config = dict(policy='step', step=[20, 40])
total_epochs = 50
checkpoint_config = dict(interval=10)
evaluation = dict(
interval=2, metrics=['top_k_accuracy', 'mean_class_accuracy'])
log_config = dict(
interval=20,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook'),
])
annealing_runner = True
# runtime settings
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = './work_dirs/tsm/train_kinetics10_tsm_DEAR'
load_from = None
resume_from = None
workflow = [('train', 1)]
| 31.84106 | 78 | 0.634567 |
evidence_loss = dict(type='EvidenceLoss',
num_classes=101,
evidence='exp',
loss_type='log',
with_kldiv=False,
with_avuloss=True,
annealing_method='exp')
model = dict(
type='Recognizer2D',
backbone=dict(
type='ResNetTSM',
pretrained='torchvision://resnet50',
depth=50,
norm_eval=False,
shift_div=8),
cls_head=dict(
type='TSMHead',
loss_cls=evidence_loss,
num_classes=101,
in_channels=2048,
spatial_type='avg',
consensus=dict(type='AvgConsensus', dim=1),
dropout_ratio=0.5,
init_std=0.001,
is_shift=True),
debias_head=dict(
type='DebiasHead',
loss_cls=evidence_loss,
loss_factor=0.1,
num_classes=101,
in_channels=2048,
dropout_ratio=0.5,
init_std=0.01))
train_cfg = None
test_cfg = dict(average_clips='evidence', evidence_type='exp')
dataset_type = 'VideoDataset'
data_root = 'data/kinetics10/videos_train'
data_root_val = 'data/kinetics10/videos_val'
ann_file_train = 'data/kinetics10/kinetics10_train_list_videos.txt'
ann_file_val = 'data/kinetics10/kinetics10_val_list_videos.txt'
ann_file_test = 'data/kinetics10/kinetics10_val_list_videos.txt'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False)
train_pipeline = [
dict(type='OpenCVInit', num_threads=1),
dict(type='DenseSampleFrames', clip_len=1, frame_interval=1, num_clips=8),
dict(type='OpenCVDecode'),
dict(type='Resize', scale=(-1, 256)),
dict(
type='MultiScaleCrop',
input_size=224,
scales=(1, 0.875, 0.75, 0.66),
random_crop=False,
max_wh_scale_gap=1,
num_fixed_crops=13),
dict(type='Resize', scale=(224, 224), keep_ratio=False),
dict(type='Flip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs', 'label'])
]
val_pipeline = [
dict(type='OpenCVInit', num_threads=1),
dict(
type='DenseSampleFrames',
clip_len=1,
frame_interval=1,
num_clips=8,
test_mode=True),
dict(type='OpenCVDecode'),
dict(type='Resize', scale=(-1, 256)),
dict(type='CenterCrop', crop_size=224),
dict(type='Flip', flip_ratio=0),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs'])
]
test_pipeline = [
dict(type='OpenCVInit', num_threads=1),
dict(
type='DenseSampleFrames',
clip_len=1,
frame_interval=1,
num_clips=8,
test_mode=True),
dict(type='OpenCVDecode'),
dict(type='Resize', scale=(-1, 256)),
dict(type='CenterCrop', crop_size=224),
dict(type='Flip', flip_ratio=0),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs'])
]
data = dict(
videos_per_gpu=4,
workers_per_gpu=4,
val_dataloader=dict(videos_per_gpu=4),
train=dict(
type=dataset_type,
ann_file=ann_file_train,
data_prefix=data_root,
start_index=0,
pipeline=train_pipeline),
val=dict(
type=dataset_type,
ann_file=ann_file_val,
data_prefix=data_root_val,
start_index=0,
pipeline=val_pipeline),
test=dict(
type=dataset_type,
ann_file=ann_file_test,
data_prefix=data_root_val,
start_index=0,
pipeline=test_pipeline))
optimizer = dict(
type='SGD',
constructor='TSMOptimizerConstructor',
paramwise_cfg=dict(fc_lr5=True),
lr=0.001,
momentum=0.9,
weight_decay=0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=20, norm_type=2))
lr_config = dict(policy='step', step=[20, 40])
total_epochs = 50
checkpoint_config = dict(interval=10)
evaluation = dict(
interval=2, metrics=['top_k_accuracy', 'mean_class_accuracy'])
log_config = dict(
interval=20,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook'),
])
annealing_runner = True
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = './work_dirs/tsm/train_kinetics10_tsm_DEAR'
load_from = None
resume_from = None
workflow = [('train', 1)]
| true | true |
f73bb2dd8f3459edfcfe045d0234308a2d65b723 | 3,874 | py | Python | tests/service/test_scrape.py | avwx-rest/avwx-engine | af0ec16630d1d79bca19f2610b5d2b84a782333f | [
"MIT"
] | 25 | 2019-11-27T05:33:04.000Z | 2022-02-05T04:04:44.000Z | tests/service/test_scrape.py | avwx-rest/avwx-engine | af0ec16630d1d79bca19f2610b5d2b84a782333f | [
"MIT"
] | 13 | 2019-11-18T17:03:54.000Z | 2021-09-04T03:53:55.000Z | tests/service/test_scrape.py | avwx-rest/avwx-engine | af0ec16630d1d79bca19f2610b5d2b84a782333f | [
"MIT"
] | 16 | 2019-11-18T01:55:49.000Z | 2021-09-20T03:22:58.000Z | """
ScrapeService API Tests
"""
# pylint: disable=protected-access,missing-class-docstring,unidiomatic-typecheck
# stdlib
import unittest
# library
import pytest
# module
from avwx import exceptions, service
# tests
from .test_base import BaseTestService
class TestStationScrape(BaseTestService):
service_class = service.scrape.StationScrape
report_type = "metar"
required_attrs = ("method", "_strip_whitespace", "_extract")
def test_service(self):
"""Tests for expected values and method implementation"""
# pylint: disable=no-member
if type(self.serv) == service.scrape.StationScrape:
self.assertIsNone(self.serv.url)
else:
self.assertIsInstance(self.serv.url, str)
self.assertIsInstance(self.serv.method, str)
self.assertIn(self.serv.method, ("GET", "POST"))
def test_make_err(self):
"""Tests that InvalidRequest exceptions are generated with the right message"""
# pylint: disable=no-member
key, msg = "test_key", "testing"
err = self.serv._make_err(msg, key)
err_str = (
f"Could not find {key} in {self.serv.__class__.__name__} response\n{msg}"
)
self.assertIsInstance(err, exceptions.InvalidRequest)
self.assertEqual(err.args, (err_str,))
self.assertEqual(str(err), err_str)
def test_fetch_exceptions(self):
"""Tests fetch exception handling"""
for station in ("12K", "MAYT"):
with self.assertRaises(exceptions.BadStation):
self.serv.fetch(station) # pylint: disable=no-member
# Should raise exception due to empty url
if type(self.serv) == service.scrape.ScrapeService:
with self.assertRaises(NotImplementedError):
self.serv.fetch("KJFK") # pylint: disable=no-member
@pytest.mark.asyncio
async def test_async_fetch_exceptions(self):
"""Tests async fetch exception handling"""
for station in ("12K", "MAYT"):
with self.assertRaises(exceptions.BadStation):
await self.serv.async_fetch(station) # pylint: disable=no-member
# Should raise exception due to empty url
if type(self.serv) == service.scrape.ScrapeService:
with self.assertRaises(NotImplementedError):
await self.serv.async_fetch("KJFK") # pylint: disable=no-member
class TestNOAA(TestStationScrape):
service_class = service.NOAA
stations = ["KJFK", "EGLL", "PHNL"]
class TestAMO(TestStationScrape):
service_class = service.AMO
stations = ["RKSI", "RKSS", "RKNY"]
# class TestMAC(TestStationScrape):
# service_class = service.MAC
# stations = ["SKBO"]
class TestAUBOM(TestStationScrape):
service_class = service.AUBOM
stations = ["YBBN", "YSSY", "YCNK"]
class TestOLBS(TestStationScrape):
service_class = service.OLBS
stations = ["VAPO", "VEGT"]
class TestNAM(TestStationScrape):
service_class = service.NAM
stations = ["EHAM", "ENGM", "BIRK"]
class TestAVT(TestStationScrape):
service_class = service.AVT
stations = ["ZJQH", "ZYCC", "ZSWZ"]
class TestModule(unittest.TestCase):
def test_get_service(self):
"""Tests that the correct service class is returned"""
for stations, country, serv in (
(("KJFK", "PHNL"), "US", service.NOAA),
(("EGLL",), "GB", service.NOAA),
(("RKSI",), "KR", service.AMO),
# (("SKBO", "SKPP"), "CO", service.MAC),
(("YWOL", "YSSY"), "AU", service.AUBOM),
(("VAPO", "VEGT"), "IN", service.OLBS),
(("ZJQH", "ZYCC", "ZSWZ"), "CN", service.AVT),
):
for station in stations:
self.assertIsInstance(
service.get_service(station, country)("metar"), serv
)
| 30.265625 | 87 | 0.626226 |
import unittest
import pytest
from avwx import exceptions, service
from .test_base import BaseTestService
class TestStationScrape(BaseTestService):
service_class = service.scrape.StationScrape
report_type = "metar"
required_attrs = ("method", "_strip_whitespace", "_extract")
def test_service(self):
if type(self.serv) == service.scrape.StationScrape:
self.assertIsNone(self.serv.url)
else:
self.assertIsInstance(self.serv.url, str)
self.assertIsInstance(self.serv.method, str)
self.assertIn(self.serv.method, ("GET", "POST"))
def test_make_err(self):
key, msg = "test_key", "testing"
err = self.serv._make_err(msg, key)
err_str = (
f"Could not find {key} in {self.serv.__class__.__name__} response\n{msg}"
)
self.assertIsInstance(err, exceptions.InvalidRequest)
self.assertEqual(err.args, (err_str,))
self.assertEqual(str(err), err_str)
def test_fetch_exceptions(self):
for station in ("12K", "MAYT"):
with self.assertRaises(exceptions.BadStation):
self.serv.fetch(station)
if type(self.serv) == service.scrape.ScrapeService:
with self.assertRaises(NotImplementedError):
self.serv.fetch("KJFK")
@pytest.mark.asyncio
async def test_async_fetch_exceptions(self):
for station in ("12K", "MAYT"):
with self.assertRaises(exceptions.BadStation):
await self.serv.async_fetch(station)
if type(self.serv) == service.scrape.ScrapeService:
with self.assertRaises(NotImplementedError):
await self.serv.async_fetch("KJFK")
class TestNOAA(TestStationScrape):
service_class = service.NOAA
stations = ["KJFK", "EGLL", "PHNL"]
class TestAMO(TestStationScrape):
service_class = service.AMO
stations = ["RKSI", "RKSS", "RKNY"]
class TestAUBOM(TestStationScrape):
service_class = service.AUBOM
stations = ["YBBN", "YSSY", "YCNK"]
class TestOLBS(TestStationScrape):
service_class = service.OLBS
stations = ["VAPO", "VEGT"]
class TestNAM(TestStationScrape):
service_class = service.NAM
stations = ["EHAM", "ENGM", "BIRK"]
class TestAVT(TestStationScrape):
service_class = service.AVT
stations = ["ZJQH", "ZYCC", "ZSWZ"]
class TestModule(unittest.TestCase):
def test_get_service(self):
for stations, country, serv in (
(("KJFK", "PHNL"), "US", service.NOAA),
(("EGLL",), "GB", service.NOAA),
(("RKSI",), "KR", service.AMO),
(("YWOL", "YSSY"), "AU", service.AUBOM),
(("VAPO", "VEGT"), "IN", service.OLBS),
(("ZJQH", "ZYCC", "ZSWZ"), "CN", service.AVT),
):
for station in stations:
self.assertIsInstance(
service.get_service(station, country)("metar"), serv
)
| true | true |
f73bb3030d3a369073536d546c00b44f374d40c0 | 179 | py | Python | backend/posts/admin.py | dla1635/hyLink | 8f3d1b6b0cad57ce2f6861583eb2b523f9fceee7 | [
"MIT"
] | 1 | 2020-07-17T05:57:47.000Z | 2020-07-17T05:57:47.000Z | backend/posts/admin.py | dla1635/hyLink | 8f3d1b6b0cad57ce2f6861583eb2b523f9fceee7 | [
"MIT"
] | 11 | 2020-06-06T00:30:23.000Z | 2022-02-26T19:59:06.000Z | backend/posts/admin.py | dla1635/hylink | 8f3d1b6b0cad57ce2f6861583eb2b523f9fceee7 | [
"MIT"
] | null | null | null | from django.contrib import admin
from .models import Post
from .models import PostComment
# Register your models here.
admin.site.register(Post)
admin.site.register(PostComment) | 22.375 | 32 | 0.815642 | from django.contrib import admin
from .models import Post
from .models import PostComment
admin.site.register(Post)
admin.site.register(PostComment) | true | true |
f73bb4353fbece8fa2efde026b648fd372c22f99 | 1,763 | py | Python | src/final/cloud.py | andy971022/acg-project | e42b0f9010f5f9fc2c7eb4b9b306ae6321ddfd51 | [
"MIT"
] | null | null | null | src/final/cloud.py | andy971022/acg-project | e42b0f9010f5f9fc2c7eb4b9b306ae6321ddfd51 | [
"MIT"
] | null | null | null | src/final/cloud.py | andy971022/acg-project | e42b0f9010f5f9fc2c7eb4b9b306ae6321ddfd51 | [
"MIT"
] | null | null | null | import taichi as ti
class Atom:
def __init__(self, radius, dim=3):
self.radius = radius
self.dim = dim
self.color = ti.Vector.field(dim, ti.f32, shape=1)
self.pos = ti.Vector.field(dim, ti.f32, shape=1)
def display(self, scene):
scene.particles(self.pos, self.radius, per_vertex_color=self.color)
@ti.data_oriented
class Proton(Atom):
@ti.kernel
def initialize(self, color: ti.template(), pos: ti.template()):
self.color[0] = color
self.pos[0] = pos
@ti.data_oriented
class Neutron(Atom):
@ti.kernel
def initialize(self, color: ti.template(), pos: ti.template()):
self.color[0] = color
self.pos[0] = pos
@ti.data_oriented
class Electron(Atom):
def __init__(self, radius, dim=3):
super().__init__(radius)
self.vel = ti.Vector.field(dim, ti.f32, shape=1)
@ti.kernel
def initialize(self, color: ti.template(), pos: ti.template(), vel: ti.template()):
self.color[0] = color
self.pos[0] = pos
self.vel[0] = vel
@ti.data_oriented
class ElectronCloud:
def __init__(self):
self.protons = []
self.neutrons = []
self.electrons = []
self.step = 0
self.time = 0.0
def add_proton(self, proton):
self.protons.append(proton)
def add_neutron(self, neutron):
self.neutrons.append(neutron)
def add_electron(self, electron):
self.electrons.append(electron)
def display(self, scene):
for i in self.protons:
i.display(scene)
for j in self.neutrons:
j.display(scene)
for k in self.electrons:
k.display(scene)
| 25.550725 | 88 | 0.577425 | import taichi as ti
class Atom:
def __init__(self, radius, dim=3):
self.radius = radius
self.dim = dim
self.color = ti.Vector.field(dim, ti.f32, shape=1)
self.pos = ti.Vector.field(dim, ti.f32, shape=1)
def display(self, scene):
scene.particles(self.pos, self.radius, per_vertex_color=self.color)
@ti.data_oriented
class Proton(Atom):
@ti.kernel
def initialize(self, color: ti.template(), pos: ti.template()):
self.color[0] = color
self.pos[0] = pos
@ti.data_oriented
class Neutron(Atom):
@ti.kernel
def initialize(self, color: ti.template(), pos: ti.template()):
self.color[0] = color
self.pos[0] = pos
@ti.data_oriented
class Electron(Atom):
def __init__(self, radius, dim=3):
super().__init__(radius)
self.vel = ti.Vector.field(dim, ti.f32, shape=1)
@ti.kernel
def initialize(self, color: ti.template(), pos: ti.template(), vel: ti.template()):
self.color[0] = color
self.pos[0] = pos
self.vel[0] = vel
@ti.data_oriented
class ElectronCloud:
def __init__(self):
self.protons = []
self.neutrons = []
self.electrons = []
self.step = 0
self.time = 0.0
def add_proton(self, proton):
self.protons.append(proton)
def add_neutron(self, neutron):
self.neutrons.append(neutron)
def add_electron(self, electron):
self.electrons.append(electron)
def display(self, scene):
for i in self.protons:
i.display(scene)
for j in self.neutrons:
j.display(scene)
for k in self.electrons:
k.display(scene)
| true | true |
f73bb5c57e0e4c85d49cc6ebc11d319b37811b8c | 13,400 | py | Python | mlflow/projects/databricks.py | ToonKBC/mlflow | fb9abd87afdefc8409adea409bca329215701e6e | [
"Apache-2.0"
] | 2 | 2019-08-31T10:18:47.000Z | 2022-02-13T13:34:14.000Z | mlflow/projects/databricks.py | ToonKBC/mlflow | fb9abd87afdefc8409adea409bca329215701e6e | [
"Apache-2.0"
] | 5 | 2018-08-29T00:46:14.000Z | 2018-08-31T07:17:58.000Z | mlflow/projects/databricks.py | ToonKBC/mlflow | fb9abd87afdefc8409adea409bca329215701e6e | [
"Apache-2.0"
] | 2 | 2019-11-06T23:26:40.000Z | 2020-12-18T08:59:20.000Z | import hashlib
import json
import os
import shutil
import tempfile
import textwrap
import time
from six.moves import shlex_quote, urllib
from mlflow.entities import RunStatus
from mlflow.projects import _fetch_project
from mlflow.projects.submitted_run import SubmittedRun
from mlflow.utils import rest_utils, file_utils
from mlflow.utils.exception import ExecutionException
from mlflow.utils.logging_utils import eprint
from mlflow import tracking
from mlflow.version import VERSION
# Base directory within driver container for storing files related to MLflow
DB_CONTAINER_BASE = "/databricks/mlflow"
# Base directory within driver container for storing project archives
DB_TARFILE_BASE = os.path.join(DB_CONTAINER_BASE, "project-tars")
# Base directory directory within driver container for storing extracted project directories
DB_PROJECTS_BASE = os.path.join(DB_CONTAINER_BASE, "projects")
# Name to use for project directory when archiving it for upload to DBFS; the TAR will contain
# a single directory with this name
DB_TARFILE_ARCHIVE_NAME = "mlflow-project"
# Base directory within DBFS for storing code for project runs for experiments
DBFS_EXPERIMENT_DIR_BASE = "mlflow-experiments"
def _jobs_runs_get(databricks_run_id):
return rest_utils.databricks_api_request(
endpoint="jobs/runs/get", method="GET", json={"run_id": databricks_run_id})
def _jobs_runs_cancel(databricks_run_id):
return rest_utils.databricks_api_request(
endpoint="jobs/runs/cancel", method="POST", json={"run_id": databricks_run_id})
def _jobs_runs_submit(req_body_json):
return rest_utils.databricks_api_request(
endpoint="jobs/runs/submit", method="POST", json=req_body_json)
def _get_databricks_run_cmd(dbfs_fuse_tar_uri, run_id, entry_point, parameters):
"""
Generates MLflow CLI command to run on Databricks cluster in order to launch a run on Databricks
"""
# Strip ".gz" and ".tar" file extensions from base filename of the tarfile
tar_hash = os.path.splitext(os.path.splitext(os.path.basename(dbfs_fuse_tar_uri))[0])[0]
container_tar_path = os.path.abspath(os.path.join(DB_TARFILE_BASE,
os.path.basename(dbfs_fuse_tar_uri)))
project_dir = os.path.join(DB_PROJECTS_BASE, tar_hash)
mlflow_run_arr = list(map(shlex_quote, ["mlflow", "run", project_dir,
"--entry-point", entry_point]))
if run_id:
mlflow_run_arr.extend(["--run-id", run_id])
if parameters:
for key, value in parameters.items():
mlflow_run_arr.extend(["-P", "%s=%s" % (key, value)])
mlflow_run_cmd = " ".join(mlflow_run_arr)
shell_command = textwrap.dedent("""
export PATH=$DB_HOME/conda/bin:$DB_HOME/python/bin:$PATH &&
mlflow --version &&
# Make local directories in the container into which to copy/extract the tarred project
mkdir -p {tarfile_base} {projects_base} &&
# Rsync from DBFS FUSE to avoid copying archive into local filesystem if it already exists
rsync -a -v --ignore-existing {dbfs_fuse_tar_path} {tarfile_base} &&
# Extract project into a temporary directory. We don't extract directly into the desired
# directory as tar extraction isn't guaranteed to be atomic
cd $(mktemp -d) &&
tar --no-same-owner -xzvf {container_tar_path} &&
# Atomically move the extracted project into the desired directory
mv -T {tarfile_archive_name} {work_dir} &&
{mlflow_run}
""".format(tarfile_base=DB_TARFILE_BASE, projects_base=DB_PROJECTS_BASE,
dbfs_fuse_tar_path=dbfs_fuse_tar_uri, container_tar_path=container_tar_path,
tarfile_archive_name=DB_TARFILE_ARCHIVE_NAME, work_dir=project_dir,
mlflow_run=mlflow_run_cmd))
return ["bash", "-c", shell_command]
def _check_databricks_auth_available():
"""
Verifies that information for making API requests to Databricks is available to MLflow, raising
an exception if not.
"""
rest_utils.get_databricks_http_request_kwargs_or_fail()
def _upload_to_dbfs(src_path, dbfs_fuse_uri):
"""
Uploads the file at `src_path` to the specified DBFS URI within the Databricks workspace
corresponding to the default Databricks CLI profile.
"""
eprint("=== Uploading project to DBFS path %s ===" % dbfs_fuse_uri)
http_endpoint = dbfs_fuse_uri
http_request_kwargs = rest_utils.get_databricks_http_request_kwargs_or_fail()
with open(src_path, 'rb') as f:
rest_utils.http_request(
endpoint=http_endpoint, method='POST', data=f,
**http_request_kwargs)
def _dbfs_path_exists(dbfs_uri):
"""
Returns True if the passed-in path exists in DBFS for the workspace corresponding to the
default Databricks CLI profile.
"""
dbfs_path = _parse_dbfs_uri_path(dbfs_uri)
json_response_obj = rest_utils.databricks_api_request(
endpoint="dbfs/get-status", method="GET", json={"path": dbfs_path})
# If request fails with a RESOURCE_DOES_NOT_EXIST error, the file does not exist on DBFS
error_code_field = "error_code"
if error_code_field in json_response_obj:
if json_response_obj[error_code_field] == "RESOURCE_DOES_NOT_EXIST":
return False
raise ExecutionException("Got unexpected error response when checking whether file %s "
"exists in DBFS: %s" % json_response_obj)
return True
def _upload_project_to_dbfs(project_dir, experiment_id):
"""
Tars a project directory into an archive in a temp dir and uploads it to DBFS, returning
the HDFS-style URI of the tarball in DBFS (e.g. dbfs:/path/to/tar).
:param project_dir: Path to a directory containing an MLflow project to upload to DBFS (e.g.
a directory containing an MLproject file).
"""
temp_tarfile_dir = tempfile.mkdtemp()
temp_tar_filename = file_utils.build_path(temp_tarfile_dir, "project.tar.gz")
def custom_filter(x):
return None if os.path.basename(x.name) == "mlruns" else x
try:
file_utils.make_tarfile(temp_tar_filename, project_dir, DB_TARFILE_ARCHIVE_NAME,
custom_filter=custom_filter)
with open(temp_tar_filename, "rb") as tarred_project:
tarfile_hash = hashlib.sha256(tarred_project.read()).hexdigest()
# TODO: Get subdirectory for experiment from the tracking server
dbfs_fuse_uri = os.path.join("/dbfs", DBFS_EXPERIMENT_DIR_BASE, str(experiment_id),
"projects-code", "%s.tar.gz" % tarfile_hash)
if not _dbfs_path_exists(dbfs_fuse_uri):
_upload_to_dbfs(temp_tar_filename, dbfs_fuse_uri)
eprint("=== Finished uploading project to %s ===" % dbfs_fuse_uri)
else:
eprint("=== Project already exists in DBFS ===")
finally:
shutil.rmtree(temp_tarfile_dir)
return dbfs_fuse_uri
def _get_run_result_state(databricks_run_id):
"""
Returns the run result state (string) of the Databricks run with the passed-in ID, or None
if the run is still active. See possible values at
https://docs.databricks.com/api/latest/jobs.html#runresultstate.
"""
res = _jobs_runs_get(databricks_run_id)
return res["state"].get("result_state", None)
def _run_shell_command_job(project_uri, command, env_vars, cluster_spec):
"""
Runs the specified shell command on a Databricks cluster.
:param project_uri: URI of the project from which our shell command originates
:param command: Shell command to run
:param env_vars: Environment variables to set in the process running `command`
:param cluster_spec: Dictionary describing the cluster, expected to contain the fields for a
NewCluster (see
https://docs.databricks.com/api/latest/jobs.html#jobsclusterspecnewcluster)
:return: The ID of the Databricks Job Run. Can be used to query the run's status via the
Databricks Runs Get API (https://docs.databricks.com/api/latest/jobs.html#runs-get).
"""
# Make jobs API request to launch run.
req_body_json = {
'run_name': 'MLflow Run for %s' % project_uri,
'new_cluster': cluster_spec,
'shell_command_task': {
'command': command,
"env_vars": env_vars
},
"libraries": [{"pypi": {"package": "mlflow==%s" % VERSION}}]
}
run_submit_res = _jobs_runs_submit(req_body_json)
databricks_run_id = run_submit_res["run_id"]
eprint("=== Launched MLflow run as Databricks job run with ID %s. Getting run status "
"page URL... ===" % databricks_run_id)
run_info = _jobs_runs_get(databricks_run_id)
jobs_page_url = run_info["run_page_url"]
eprint("=== Check the run's status at %s ===" % jobs_page_url)
return databricks_run_id
def _parse_dbfs_uri_path(dbfs_uri):
"""
Parses and returns the absolute path within DBFS of the file with the specified URI. For
example, given an input of "dbfs:/my/dbfs/path", this method will return "/my/dbfs/path"
"""
return urllib.parse.urlparse(dbfs_uri).path
def _fetch_and_clean_project(uri, version=None, git_username=None, git_password=None):
"""
Fetches the project at the passed-in URI & prepares it for upload to DBFS. Returns the path of
the temporary directory into which the project was fetched.
"""
work_dir = _fetch_project(
uri=uri, force_tempdir=True, version=version, git_username=git_username,
git_password=git_password)
# Remove the mlruns directory from the fetched project to avoid cache-busting
mlruns_dir = os.path.join(work_dir, "mlruns")
if os.path.exists(mlruns_dir):
shutil.rmtree(mlruns_dir)
return work_dir
def _before_run_validations(tracking_uri, cluster_spec):
"""Validations to perform before running a project on Databricks."""
_check_databricks_auth_available()
if cluster_spec is None:
raise ExecutionException("Cluster spec must be provided when launching MLflow project runs "
"on Databricks.")
if tracking.utils._is_local_uri(tracking_uri):
raise ExecutionException(
"When running on Databricks, the MLflow tracking URI must be set to a remote URI "
"accessible to both the current client and code running on Databricks. Got local "
"tracking URI %s." % tracking_uri)
def run_databricks(remote_run, uri, entry_point, work_dir, parameters, experiment_id, cluster_spec):
"""
Runs the project at the specified URI on Databricks, returning a `SubmittedRun` that can be
used to query the run's status or wait for the resulting Databricks Job run to terminate.
"""
tracking_uri = tracking.get_tracking_uri()
_before_run_validations(tracking_uri, cluster_spec)
dbfs_fuse_uri = _upload_project_to_dbfs(work_dir, experiment_id)
env_vars = {
tracking._TRACKING_URI_ENV_VAR: tracking_uri,
tracking._EXPERIMENT_ID_ENV_VAR: experiment_id,
}
run_id = remote_run.info.run_uuid
eprint("=== Running entry point %s of project %s on Databricks. ===" % (entry_point, uri))
# Launch run on Databricks
with open(cluster_spec, 'r') as handle:
try:
cluster_spec = json.load(handle)
except ValueError:
eprint("Error when attempting to load and parse JSON cluster spec from file "
"%s. " % cluster_spec)
raise
command = _get_databricks_run_cmd(dbfs_fuse_uri, run_id, entry_point, parameters)
db_run_id = _run_shell_command_job(uri, command, env_vars, cluster_spec)
return DatabricksSubmittedRun(db_run_id, run_id)
def _cancel_databricks(databricks_run_id):
_jobs_runs_cancel(databricks_run_id)
def _monitor_databricks(databricks_run_id, sleep_interval=30):
"""
Polls a Databricks Job run (with run ID `databricks_run_id`) for termination, checking the
run's status every `sleep_interval` seconds.
"""
result_state = _get_run_result_state(databricks_run_id)
while result_state is None:
time.sleep(sleep_interval)
result_state = _get_run_result_state(databricks_run_id)
return result_state == "SUCCESS"
class DatabricksSubmittedRun(SubmittedRun):
"""
Instance of SubmittedRun corresponding to a Databricks Job run launched to run an MLflow
project. Note that run_id may be None, e.g. if we did not launch the run against a tracking
server accessible to the local client.
"""
def __init__(self, databricks_run_id, run_id):
super(DatabricksSubmittedRun, self).__init__()
self.databricks_run_id = databricks_run_id
self._run_id = run_id
@property
def run_id(self):
return self._run_id
def wait(self):
return _monitor_databricks(self.databricks_run_id)
def cancel(self):
_cancel_databricks(self.databricks_run_id)
self.wait()
def _get_status(self):
run_state = _get_run_result_state(self.databricks_run_id)
if run_state is None:
return RunStatus.RUNNING
if run_state == "SUCCESS":
return RunStatus.FINISHED
return RunStatus.FAILED
def get_status(self):
return RunStatus.to_string(self._get_status())
| 42.948718 | 100 | 0.705522 | import hashlib
import json
import os
import shutil
import tempfile
import textwrap
import time
from six.moves import shlex_quote, urllib
from mlflow.entities import RunStatus
from mlflow.projects import _fetch_project
from mlflow.projects.submitted_run import SubmittedRun
from mlflow.utils import rest_utils, file_utils
from mlflow.utils.exception import ExecutionException
from mlflow.utils.logging_utils import eprint
from mlflow import tracking
from mlflow.version import VERSION
DB_CONTAINER_BASE = "/databricks/mlflow"
DB_TARFILE_BASE = os.path.join(DB_CONTAINER_BASE, "project-tars")
DB_PROJECTS_BASE = os.path.join(DB_CONTAINER_BASE, "projects")
DB_TARFILE_ARCHIVE_NAME = "mlflow-project"
DBFS_EXPERIMENT_DIR_BASE = "mlflow-experiments"
def _jobs_runs_get(databricks_run_id):
return rest_utils.databricks_api_request(
endpoint="jobs/runs/get", method="GET", json={"run_id": databricks_run_id})
def _jobs_runs_cancel(databricks_run_id):
return rest_utils.databricks_api_request(
endpoint="jobs/runs/cancel", method="POST", json={"run_id": databricks_run_id})
def _jobs_runs_submit(req_body_json):
return rest_utils.databricks_api_request(
endpoint="jobs/runs/submit", method="POST", json=req_body_json)
def _get_databricks_run_cmd(dbfs_fuse_tar_uri, run_id, entry_point, parameters):
tar_hash = os.path.splitext(os.path.splitext(os.path.basename(dbfs_fuse_tar_uri))[0])[0]
container_tar_path = os.path.abspath(os.path.join(DB_TARFILE_BASE,
os.path.basename(dbfs_fuse_tar_uri)))
project_dir = os.path.join(DB_PROJECTS_BASE, tar_hash)
mlflow_run_arr = list(map(shlex_quote, ["mlflow", "run", project_dir,
"--entry-point", entry_point]))
if run_id:
mlflow_run_arr.extend(["--run-id", run_id])
if parameters:
for key, value in parameters.items():
mlflow_run_arr.extend(["-P", "%s=%s" % (key, value)])
mlflow_run_cmd = " ".join(mlflow_run_arr)
shell_command = textwrap.dedent("""
export PATH=$DB_HOME/conda/bin:$DB_HOME/python/bin:$PATH &&
mlflow --version &&
# Make local directories in the container into which to copy/extract the tarred project
mkdir -p {tarfile_base} {projects_base} &&
# Rsync from DBFS FUSE to avoid copying archive into local filesystem if it already exists
rsync -a -v --ignore-existing {dbfs_fuse_tar_path} {tarfile_base} &&
# Extract project into a temporary directory. We don't extract directly into the desired
# directory as tar extraction isn't guaranteed to be atomic
cd $(mktemp -d) &&
tar --no-same-owner -xzvf {container_tar_path} &&
# Atomically move the extracted project into the desired directory
mv -T {tarfile_archive_name} {work_dir} &&
{mlflow_run}
""".format(tarfile_base=DB_TARFILE_BASE, projects_base=DB_PROJECTS_BASE,
dbfs_fuse_tar_path=dbfs_fuse_tar_uri, container_tar_path=container_tar_path,
tarfile_archive_name=DB_TARFILE_ARCHIVE_NAME, work_dir=project_dir,
mlflow_run=mlflow_run_cmd))
return ["bash", "-c", shell_command]
def _check_databricks_auth_available():
rest_utils.get_databricks_http_request_kwargs_or_fail()
def _upload_to_dbfs(src_path, dbfs_fuse_uri):
eprint("=== Uploading project to DBFS path %s ===" % dbfs_fuse_uri)
http_endpoint = dbfs_fuse_uri
http_request_kwargs = rest_utils.get_databricks_http_request_kwargs_or_fail()
with open(src_path, 'rb') as f:
rest_utils.http_request(
endpoint=http_endpoint, method='POST', data=f,
**http_request_kwargs)
def _dbfs_path_exists(dbfs_uri):
dbfs_path = _parse_dbfs_uri_path(dbfs_uri)
json_response_obj = rest_utils.databricks_api_request(
endpoint="dbfs/get-status", method="GET", json={"path": dbfs_path})
error_code_field = "error_code"
if error_code_field in json_response_obj:
if json_response_obj[error_code_field] == "RESOURCE_DOES_NOT_EXIST":
return False
raise ExecutionException("Got unexpected error response when checking whether file %s "
"exists in DBFS: %s" % json_response_obj)
return True
def _upload_project_to_dbfs(project_dir, experiment_id):
temp_tarfile_dir = tempfile.mkdtemp()
temp_tar_filename = file_utils.build_path(temp_tarfile_dir, "project.tar.gz")
def custom_filter(x):
return None if os.path.basename(x.name) == "mlruns" else x
try:
file_utils.make_tarfile(temp_tar_filename, project_dir, DB_TARFILE_ARCHIVE_NAME,
custom_filter=custom_filter)
with open(temp_tar_filename, "rb") as tarred_project:
tarfile_hash = hashlib.sha256(tarred_project.read()).hexdigest()
dbfs_fuse_uri = os.path.join("/dbfs", DBFS_EXPERIMENT_DIR_BASE, str(experiment_id),
"projects-code", "%s.tar.gz" % tarfile_hash)
if not _dbfs_path_exists(dbfs_fuse_uri):
_upload_to_dbfs(temp_tar_filename, dbfs_fuse_uri)
eprint("=== Finished uploading project to %s ===" % dbfs_fuse_uri)
else:
eprint("=== Project already exists in DBFS ===")
finally:
shutil.rmtree(temp_tarfile_dir)
return dbfs_fuse_uri
def _get_run_result_state(databricks_run_id):
res = _jobs_runs_get(databricks_run_id)
return res["state"].get("result_state", None)
def _run_shell_command_job(project_uri, command, env_vars, cluster_spec):
req_body_json = {
'run_name': 'MLflow Run for %s' % project_uri,
'new_cluster': cluster_spec,
'shell_command_task': {
'command': command,
"env_vars": env_vars
},
"libraries": [{"pypi": {"package": "mlflow==%s" % VERSION}}]
}
run_submit_res = _jobs_runs_submit(req_body_json)
databricks_run_id = run_submit_res["run_id"]
eprint("=== Launched MLflow run as Databricks job run with ID %s. Getting run status "
"page URL... ===" % databricks_run_id)
run_info = _jobs_runs_get(databricks_run_id)
jobs_page_url = run_info["run_page_url"]
eprint("=== Check the run's status at %s ===" % jobs_page_url)
return databricks_run_id
def _parse_dbfs_uri_path(dbfs_uri):
return urllib.parse.urlparse(dbfs_uri).path
def _fetch_and_clean_project(uri, version=None, git_username=None, git_password=None):
work_dir = _fetch_project(
uri=uri, force_tempdir=True, version=version, git_username=git_username,
git_password=git_password)
# Remove the mlruns directory from the fetched project to avoid cache-busting
mlruns_dir = os.path.join(work_dir, "mlruns")
if os.path.exists(mlruns_dir):
shutil.rmtree(mlruns_dir)
return work_dir
def _before_run_validations(tracking_uri, cluster_spec):
_check_databricks_auth_available()
if cluster_spec is None:
raise ExecutionException("Cluster spec must be provided when launching MLflow project runs "
"on Databricks.")
if tracking.utils._is_local_uri(tracking_uri):
raise ExecutionException(
"When running on Databricks, the MLflow tracking URI must be set to a remote URI "
"accessible to both the current client and code running on Databricks. Got local "
"tracking URI %s." % tracking_uri)
def run_databricks(remote_run, uri, entry_point, work_dir, parameters, experiment_id, cluster_spec):
tracking_uri = tracking.get_tracking_uri()
_before_run_validations(tracking_uri, cluster_spec)
dbfs_fuse_uri = _upload_project_to_dbfs(work_dir, experiment_id)
env_vars = {
tracking._TRACKING_URI_ENV_VAR: tracking_uri,
tracking._EXPERIMENT_ID_ENV_VAR: experiment_id,
}
run_id = remote_run.info.run_uuid
eprint("=== Running entry point %s of project %s on Databricks. ===" % (entry_point, uri))
# Launch run on Databricks
with open(cluster_spec, 'r') as handle:
try:
cluster_spec = json.load(handle)
except ValueError:
eprint("Error when attempting to load and parse JSON cluster spec from file "
"%s. " % cluster_spec)
raise
command = _get_databricks_run_cmd(dbfs_fuse_uri, run_id, entry_point, parameters)
db_run_id = _run_shell_command_job(uri, command, env_vars, cluster_spec)
return DatabricksSubmittedRun(db_run_id, run_id)
def _cancel_databricks(databricks_run_id):
_jobs_runs_cancel(databricks_run_id)
def _monitor_databricks(databricks_run_id, sleep_interval=30):
result_state = _get_run_result_state(databricks_run_id)
while result_state is None:
time.sleep(sleep_interval)
result_state = _get_run_result_state(databricks_run_id)
return result_state == "SUCCESS"
class DatabricksSubmittedRun(SubmittedRun):
def __init__(self, databricks_run_id, run_id):
super(DatabricksSubmittedRun, self).__init__()
self.databricks_run_id = databricks_run_id
self._run_id = run_id
@property
def run_id(self):
return self._run_id
def wait(self):
return _monitor_databricks(self.databricks_run_id)
def cancel(self):
_cancel_databricks(self.databricks_run_id)
self.wait()
def _get_status(self):
run_state = _get_run_result_state(self.databricks_run_id)
if run_state is None:
return RunStatus.RUNNING
if run_state == "SUCCESS":
return RunStatus.FINISHED
return RunStatus.FAILED
def get_status(self):
return RunStatus.to_string(self._get_status())
| true | true |
f73bb630fbd813595c7ca9679483fccab4cbf015 | 3,746 | py | Python | tfx/orchestration/portable/beam_executor_operator.py | ssoudan/tfx | 13979ced62b50292a5dea7be2f15205fe8469400 | [
"Apache-2.0"
] | null | null | null | tfx/orchestration/portable/beam_executor_operator.py | ssoudan/tfx | 13979ced62b50292a5dea7be2f15205fe8469400 | [
"Apache-2.0"
] | null | null | null | tfx/orchestration/portable/beam_executor_operator.py | ssoudan/tfx | 13979ced62b50292a5dea7be2f15205fe8469400 | [
"Apache-2.0"
] | null | null | null | # Copyright 2021 Google LLC. 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.
"""Base class to define how to operator a Beam based executor."""
from typing import Optional, cast
from tfx.dsl.components.base import base_beam_executor
from tfx.orchestration.portable import base_executor_operator
from tfx.orchestration.portable import data_types
from tfx.orchestration.portable import python_executor_operator
from tfx.proto.orchestration import executable_spec_pb2
from tfx.proto.orchestration import execution_result_pb2
from tfx.utils import import_utils
from google.protobuf import message
class BeamExecutorOperator(base_executor_operator.BaseExecutorOperator):
"""BeamExecutorOperator handles Beam based executor's init and execution.
Attributes:
extra_flags: Extra flags that will pass to Beam executors. It come from
two sources in the order:
1. The `extra_flags` set in the executor spec.
2. The flags passed in when starting the program by users or by other
systems. The interpretation of these flags relying on the executor
implementation.
beam_pipeline_args: Beam specific arguments that will pass to Beam
executors. It comes from `beam_pipeline_args` set in the Beam executor
spec.
"""
SUPPORTED_EXECUTOR_SPEC_TYPE = [executable_spec_pb2.BeamExecutableSpec]
SUPPORTED_PLATFORM_CONFIG_TYPE = []
def __init__(self,
executor_spec: message.Message,
platform_config: Optional[message.Message] = None):
"""Initializes a BeamExecutorOperator.
Args:
executor_spec: The specification of how to initialize the executor.
platform_config: The specification of how to allocate resource for the
executor.
"""
del platform_config
super().__init__(executor_spec)
beam_executor_spec = cast(executable_spec_pb2.BeamExecutableSpec,
self._executor_spec)
self._executor_cls = import_utils.import_class_by_path(
beam_executor_spec.python_executor_spec.class_path)
self.extra_flags = []
self.extra_flags.extend(beam_executor_spec.python_executor_spec.extra_flags)
self.beam_pipeline_args = []
self.beam_pipeline_args.extend(beam_executor_spec.beam_pipeline_args)
def run_executor(
self, execution_info: data_types.ExecutionInfo
) -> execution_result_pb2.ExecutorOutput:
"""Invokes executors given input from the Launcher.
Args:
execution_info: A wrapper of the details of this execution.
Returns:
The output from executor.
"""
context = base_beam_executor.BaseBeamExecutor.Context(
beam_pipeline_args=self.beam_pipeline_args,
extra_flags=self.extra_flags,
tmp_dir=execution_info.tmp_dir,
unique_id=str(execution_info.execution_id),
executor_output_uri=execution_info.execution_output_uri,
stateful_working_dir=execution_info.stateful_working_dir,
pipeline_node=execution_info.pipeline_node,
pipeline_info=execution_info.pipeline_info,
pipeline_run_id=execution_info.pipeline_run_id)
executor = self._executor_cls(context=context)
return python_executor_operator.run_with_executor(execution_info, executor)
| 41.622222 | 80 | 0.761612 |
from typing import Optional, cast
from tfx.dsl.components.base import base_beam_executor
from tfx.orchestration.portable import base_executor_operator
from tfx.orchestration.portable import data_types
from tfx.orchestration.portable import python_executor_operator
from tfx.proto.orchestration import executable_spec_pb2
from tfx.proto.orchestration import execution_result_pb2
from tfx.utils import import_utils
from google.protobuf import message
class BeamExecutorOperator(base_executor_operator.BaseExecutorOperator):
SUPPORTED_EXECUTOR_SPEC_TYPE = [executable_spec_pb2.BeamExecutableSpec]
SUPPORTED_PLATFORM_CONFIG_TYPE = []
def __init__(self,
executor_spec: message.Message,
platform_config: Optional[message.Message] = None):
del platform_config
super().__init__(executor_spec)
beam_executor_spec = cast(executable_spec_pb2.BeamExecutableSpec,
self._executor_spec)
self._executor_cls = import_utils.import_class_by_path(
beam_executor_spec.python_executor_spec.class_path)
self.extra_flags = []
self.extra_flags.extend(beam_executor_spec.python_executor_spec.extra_flags)
self.beam_pipeline_args = []
self.beam_pipeline_args.extend(beam_executor_spec.beam_pipeline_args)
def run_executor(
self, execution_info: data_types.ExecutionInfo
) -> execution_result_pb2.ExecutorOutput:
context = base_beam_executor.BaseBeamExecutor.Context(
beam_pipeline_args=self.beam_pipeline_args,
extra_flags=self.extra_flags,
tmp_dir=execution_info.tmp_dir,
unique_id=str(execution_info.execution_id),
executor_output_uri=execution_info.execution_output_uri,
stateful_working_dir=execution_info.stateful_working_dir,
pipeline_node=execution_info.pipeline_node,
pipeline_info=execution_info.pipeline_info,
pipeline_run_id=execution_info.pipeline_run_id)
executor = self._executor_cls(context=context)
return python_executor_operator.run_with_executor(execution_info, executor)
| true | true |
f73bb67ebf26cb9ef88d356d3860f76c135ab477 | 9,421 | py | Python | graph.py | govindak-umd/PlanningTkinter | a4a1a908a6b314f04d818f2430f63708e8472889 | [
"MIT"
] | null | null | null | graph.py | govindak-umd/PlanningTkinter | a4a1a908a6b314f04d818f2430f63708e8472889 | [
"MIT"
] | null | null | null | graph.py | govindak-umd/PlanningTkinter | a4a1a908a6b314f04d818f2430f63708e8472889 | [
"MIT"
] | null | null | null | from map import map_canvas
from maps_utils import Node, resolution, map_size, border_size, Obstacles
from maps_utils import cost
def compareNodes(node_1, node_2):
"""
Compares two nodes to check if they are equal
:param node_1: The first node to check
:type node_1: Node type
:param node_2: The second node to check
:type node_2: Node type
:returns: True or False
:rtype: Boolean type
"""
if (node_1.x == node_2.x) and (node_1.y == node_2.y):
return True
else:
return False
def checkinThis(node_to_check, set_to_check_in):
"""
Checks if a node is there in a list or a set
:param node_to_check: The node to check
:type node_to_check: Node
:param set_to_check_in: The set to check in
:type set_to_check_in: List, Set
:returns: True or False
:rtype: Boolean type
"""
for node in set_to_check_in:
if compareNodes(node, node_to_check):
return True
return False
def getSameNode(node_to_check, set_to_check_in):
"""
Gets the same node from the set or the list.
:param node_to_check: The node to check for
:type node_to_check: Node
:param set_to_check_in: The set/list to check in
:type set_to_check_in: Set or List
:returns: The equivalent node with the same x and y coordinate
:rtype: The node, else 0
"""
for node in set_to_check_in:
if compareNodes(node, node_to_check):
return node
return 0
def checkinGraph(node_to_check, graph_to_check_in):
"""
Checks for teh nnode in the graph, by looking at all the
keys / parent nodes
:param node_to_check: The node to check for
:type node_to_check: Node type
:param graph_to_check_in: The graph to check in
:type graph_to_check_in: Graph type
:returns: True or False
:rtype: Boolean type
"""
graph_keys = list(graph_to_check_in.getVertices())
for node in graph_keys:
if compareNodes(node, node_to_check):
return True
return False
def printNode(node):
"""
Prints the node, making it easy for debugging
:param node: The node
:type node: Node type
:returns: None
:rtype: None
"""
print('Node is : ', node.x, ',', node.y)
def checkNodeInObstacle(node, img):
"""
To check the color of the image at a particular Node
:param node: node to check
:type node: Node type
:param img: the image to check in
:type img: np.array
:return: Boolean of True or False
:rtype: Boolean
"""
if img[node.y, node.x][0] == 0 and img[node.y, node.x][1] == 0 and img[node.y, node.x][2] == 0:
return True
return False
class Graph:
"""
This is a class that describes the entire map as a graph
"""
def __init__(self, graph_dict):
self.graph_dict = graph_dict
def getVertices(self):
"""
Gets the vertices of the graph
:returns: The vertices of the graph
:rtype: list
"""
key_list = list(self.graph_dict.keys())
return key_list
def getNeighbors(self, node):
"""
Gets the neighbors of every vertex
:param node: The parent node
:type node: Node
:returns: The neighbors / adjacent nodes to the parent
:rtype: Graph
"""
key_list = list(self.graph_dict.keys())
if checkinThis(node, key_list):
similar_node = getSameNode(node, key_list)
return self.graph_dict[similar_node]
def getEdges(self):
"""
Gets the edges of the graph
:returns: The edges of the graph
:rtype: set
"""
val_set = set()
val_node_list = list(self.graph_dict.values())
for val_nodes in val_node_list:
for val in val_nodes:
val_set.add(val)
return val_set
def generateCostGraph():
"""
Function generates cost graph to be used to solve with
Dijkstra and A* path planning algorithms
:return: Cost Graph
:rtype: Graph
"""
print('Generating Cost Graph')
cost_graph = {}
for row_range in range(border_size - 1, map_size - border_size + 1):
for col_range in range(border_size, map_size - border_size + 1):
# When obstacles are present
if Obstacles:
node = Node(col_range, row_range)
# Adding only white cells into the graph
if not checkNodeInObstacle(node, map_canvas):
# Parent Node
cost_graph[node] = {}
# Child Nodes
node_top = Node(col_range - resolution, row_range)
if not checkNodeInObstacle(node_top, map_canvas):
cost_graph[node][node_top] = cost
node_below = Node(col_range + resolution, row_range)
if not checkNodeInObstacle(node_below, map_canvas):
cost_graph[node][node_below] = cost
node_right = Node(col_range, row_range + resolution)
if not checkNodeInObstacle(node_right, map_canvas):
cost_graph[node][node_right] = cost
node_left = Node(col_range, row_range - resolution)
if not checkNodeInObstacle(node_left, map_canvas):
cost_graph[node][node_left] = cost
# When obstacles are NOT present
else:
# Parent Node
node = Node(row_range, col_range)
cost_graph[node] = {}
# Child Nodes
node_left = Node(row_range - resolution, col_range)
cost_graph[node][node_left] = cost
node_right = Node(row_range + resolution, col_range)
cost_graph[node][node_right] = cost
node_below = Node(row_range, col_range + resolution)
cost_graph[node][node_below] = cost
node_top = Node(row_range, col_range - resolution)
cost_graph[node][node_top] = cost
# Assigning the graph with all the connections
cost_graph_img = Graph(cost_graph)
print('Cost Graphs updated')
return cost_graph_img
def generateGraph():
"""
Generates the graph, from the critical map dimensions
:returns: graph_img, a graph
:rtype: Graph
"""
print('Generating Graph')
graph_dic = {}
for row_range in range(border_size, map_size - border_size + 1):
for col_range in range(border_size, map_size - border_size + 1):
# When obstacles are present
if Obstacles:
node = Node(col_range, row_range)
if not checkNodeInObstacle(node, map_canvas):
# Parent Node
graph_dic[node] = []
# Child Nodes
# Checking for the child node to not be in a
# boundary / obstacle
node_top = Node(col_range - resolution, row_range)
if not checkNodeInObstacle(node_top, map_canvas):
graph_dic[node].append(node_top)
# Checking for the child node to not be in a
# boundary / obstacle
node_below = Node(col_range + resolution, row_range)
if not checkNodeInObstacle(node_below, map_canvas):
graph_dic[node].append(node_below)
# Checking for the child node to not be in a
# boundary / obstacle
node_right = Node(col_range, row_range + resolution)
if not checkNodeInObstacle(node_right, map_canvas):
graph_dic[node].append(node_right)
# Checking for the child node to not be in a
# boundary / obstacle
node_left = Node(col_range, row_range - resolution)
if not checkNodeInObstacle(node_left, map_canvas):
graph_dic[node].append(node_left)
# When obstacles are NOT present
else:
# Parent Node
node = Node(row_range, col_range)
graph_dic[node] = []
# Child Nodes
node_left = Node(row_range - resolution, col_range)
graph_dic[node].append(node_left)
node_right = Node(row_range + resolution, col_range)
graph_dic[node].append(node_right)
node_below = Node(row_range, col_range + resolution)
graph_dic[node].append(node_below)
node_top = Node(row_range, col_range - resolution)
graph_dic[node].append(node_top)
# Assigning the graph with all the connections
graph_img = Graph(graph_dic)
print('Graphs updated')
return graph_img
# Generating the graph
# For DFS, BFS
graph_generated = generateGraph()
# Generating a cost graph
# For Dijkstra, A*
cost_graph_generated = generateCostGraph()
| 30.390323 | 99 | 0.569685 | from map import map_canvas
from maps_utils import Node, resolution, map_size, border_size, Obstacles
from maps_utils import cost
def compareNodes(node_1, node_2):
if (node_1.x == node_2.x) and (node_1.y == node_2.y):
return True
else:
return False
def checkinThis(node_to_check, set_to_check_in):
for node in set_to_check_in:
if compareNodes(node, node_to_check):
return True
return False
def getSameNode(node_to_check, set_to_check_in):
for node in set_to_check_in:
if compareNodes(node, node_to_check):
return node
return 0
def checkinGraph(node_to_check, graph_to_check_in):
graph_keys = list(graph_to_check_in.getVertices())
for node in graph_keys:
if compareNodes(node, node_to_check):
return True
return False
def printNode(node):
print('Node is : ', node.x, ',', node.y)
def checkNodeInObstacle(node, img):
if img[node.y, node.x][0] == 0 and img[node.y, node.x][1] == 0 and img[node.y, node.x][2] == 0:
return True
return False
class Graph:
def __init__(self, graph_dict):
self.graph_dict = graph_dict
def getVertices(self):
key_list = list(self.graph_dict.keys())
return key_list
def getNeighbors(self, node):
key_list = list(self.graph_dict.keys())
if checkinThis(node, key_list):
similar_node = getSameNode(node, key_list)
return self.graph_dict[similar_node]
def getEdges(self):
val_set = set()
val_node_list = list(self.graph_dict.values())
for val_nodes in val_node_list:
for val in val_nodes:
val_set.add(val)
return val_set
def generateCostGraph():
print('Generating Cost Graph')
cost_graph = {}
for row_range in range(border_size - 1, map_size - border_size + 1):
for col_range in range(border_size, map_size - border_size + 1):
if Obstacles:
node = Node(col_range, row_range)
if not checkNodeInObstacle(node, map_canvas):
cost_graph[node] = {}
node_top = Node(col_range - resolution, row_range)
if not checkNodeInObstacle(node_top, map_canvas):
cost_graph[node][node_top] = cost
node_below = Node(col_range + resolution, row_range)
if not checkNodeInObstacle(node_below, map_canvas):
cost_graph[node][node_below] = cost
node_right = Node(col_range, row_range + resolution)
if not checkNodeInObstacle(node_right, map_canvas):
cost_graph[node][node_right] = cost
node_left = Node(col_range, row_range - resolution)
if not checkNodeInObstacle(node_left, map_canvas):
cost_graph[node][node_left] = cost
else:
node = Node(row_range, col_range)
cost_graph[node] = {}
node_left = Node(row_range - resolution, col_range)
cost_graph[node][node_left] = cost
node_right = Node(row_range + resolution, col_range)
cost_graph[node][node_right] = cost
node_below = Node(row_range, col_range + resolution)
cost_graph[node][node_below] = cost
node_top = Node(row_range, col_range - resolution)
cost_graph[node][node_top] = cost
cost_graph_img = Graph(cost_graph)
print('Cost Graphs updated')
return cost_graph_img
def generateGraph():
print('Generating Graph')
graph_dic = {}
for row_range in range(border_size, map_size - border_size + 1):
for col_range in range(border_size, map_size - border_size + 1):
if Obstacles:
node = Node(col_range, row_range)
if not checkNodeInObstacle(node, map_canvas):
graph_dic[node] = []
node_top = Node(col_range - resolution, row_range)
if not checkNodeInObstacle(node_top, map_canvas):
graph_dic[node].append(node_top)
node_below = Node(col_range + resolution, row_range)
if not checkNodeInObstacle(node_below, map_canvas):
graph_dic[node].append(node_below)
node_right = Node(col_range, row_range + resolution)
if not checkNodeInObstacle(node_right, map_canvas):
graph_dic[node].append(node_right)
node_left = Node(col_range, row_range - resolution)
if not checkNodeInObstacle(node_left, map_canvas):
graph_dic[node].append(node_left)
else:
node = Node(row_range, col_range)
graph_dic[node] = []
node_left = Node(row_range - resolution, col_range)
graph_dic[node].append(node_left)
node_right = Node(row_range + resolution, col_range)
graph_dic[node].append(node_right)
node_below = Node(row_range, col_range + resolution)
graph_dic[node].append(node_below)
node_top = Node(row_range, col_range - resolution)
graph_dic[node].append(node_top)
graph_img = Graph(graph_dic)
print('Graphs updated')
return graph_img
graph_generated = generateGraph()
cost_graph_generated = generateCostGraph()
| true | true |
f73bb6858525c37b2b1a3791a2397b54c1991023 | 5,837 | py | Python | ivi/interface/pyserial.py | lude-ma/python-ivi | f62907a2922d5fc98e0a524ef6ddbaa62791ff14 | [
"MIT"
] | 1 | 2017-09-09T06:04:14.000Z | 2017-09-09T06:04:14.000Z | ivi/interface/pyserial.py | lude-ma/python-ivi | f62907a2922d5fc98e0a524ef6ddbaa62791ff14 | [
"MIT"
] | null | null | null | ivi/interface/pyserial.py | lude-ma/python-ivi | f62907a2922d5fc98e0a524ef6ddbaa62791ff14 | [
"MIT"
] | null | null | null | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2014 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, 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 serial
import time
class SerialInstrument:
"Serial instrument interface client"
def __init__(self, port = None, baudrate=9600, bytesize=8, paritymode=0, stopbits=1, timeout=None,
xonxoff=False, rtscts=False, dsrdtr=False):
self.serial = serial.Serial(port)
self.term_char = '\n'
self.port = port
self.baudrate = baudrate
self.bytesize = bytesize
self.paritymode = paritymode
self.stopbits = stopbits
self.timeout = timeout
self.xonxoff = xonxoff
self.rtscts = rtscts
self.dsrdtr = dsrdtr
self.wait_dsr = False
self.message_delay = 0
self.update_settings()
def update_settings(self):
self.serial.baudrate = self.baudrate
if self.bytesize == 5:
self.serial.bytesize = serial.FIVEBITS
elif self.bytesize == 6:
self.serial.bytesize = serial.SIXBITS
elif self.bytesize == 7:
self.serial.bytesize = serial.SEVENBITS
else:
self.serial.bytesize = serial.EIGHTBITS
if self.paritymode == 1:
self.serial.paritymode = serial.PARITY_ODD
elif self.paritymode == 2:
self.serial.paritymode = serial.PARITY_EVEN
elif self.paritymode == 3:
self.serial.paritymode = serial.PARITY_MARK
elif self.paritymode == 4:
self.serial.paritymode = serial.PARITY_SPACE
else:
self.serial.paritymode = serial.PARITY_NONE
if self.stopbits == 1.5:
self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
elif self.stopbits == 2:
self.serial.stopbits = serial.STOPBITS_TWO
else:
self.serial.stopbits = serial.STOPBITS_ONE
self.serial.timeout = self.timeout
self.serial.xonxoff = self.xonxoff
self.serial.rtscts = self.rtscts
self.serial.dsrdtr = self.dsrdtr
if self.dsrdtr:
self.wait_dsr = True
self.message_delay = 0.1
def write_raw(self, data):
"Write binary data to instrument"
if self.term_char is not None:
data += str(self.term_char).encode('utf-8')[0]
self.serial.write(data)
if self.message_delay > 0:
time.sleep(self.message_delay)
if self.wait_dsr:
while not self.serial.getDSR():
time.sleep(0.01)
def read_raw(self, num=-1):
"Read binary data from instrument"
data = b''
term_char = str(self.term_char).encode('utf-8')[0]
while True:
c = self.serial.read(1)
data += c
num -= 1
if c == term_char:
break
if num == 0:
break
return data
def ask_raw(self, data, num=-1):
"Write then read binary data"
self.write_raw(data)
return self.read_raw(num)
def write(self, message, encoding = 'utf-8'):
"Write string to instrument"
if type(message) is tuple or type(message) is list:
# recursive call for a list of commands
for message_i in message:
self.write(message_i, encoding)
return
self.write_raw(str(message).encode(encoding))
def read(self, num=-1, encoding = 'utf-8'):
"Read string from instrument"
return self.read_raw(num).decode(encoding).rstrip('\r\n')
def ask(self, message, num=-1, encoding = 'utf-8'):
"Write then read string"
if type(message) is tuple or type(message) is list:
# recursive call for a list of commands
val = list()
for message_i in message:
val.append(self.ask(message_i, num, encoding))
return val
self.write(message, encoding)
return self.read(num, encoding)
def read_stb(self):
"Read status byte"
raise NotImplementedError()
def trigger(self):
"Send trigger command"
self.write("*TRG")
def clear(self):
"Send clear command"
self.write("*CLS")
def remote(self):
"Send remote command"
raise NotImplementedError()
def local(self):
"Send local command"
raise NotImplementedError()
def lock(self):
"Send lock command"
raise NotImplementedError()
def unlock(self):
"Send unlock command"
raise NotImplementedError()
| 31.38172 | 102 | 0.601336 |
import serial
import time
class SerialInstrument:
def __init__(self, port = None, baudrate=9600, bytesize=8, paritymode=0, stopbits=1, timeout=None,
xonxoff=False, rtscts=False, dsrdtr=False):
self.serial = serial.Serial(port)
self.term_char = '\n'
self.port = port
self.baudrate = baudrate
self.bytesize = bytesize
self.paritymode = paritymode
self.stopbits = stopbits
self.timeout = timeout
self.xonxoff = xonxoff
self.rtscts = rtscts
self.dsrdtr = dsrdtr
self.wait_dsr = False
self.message_delay = 0
self.update_settings()
def update_settings(self):
self.serial.baudrate = self.baudrate
if self.bytesize == 5:
self.serial.bytesize = serial.FIVEBITS
elif self.bytesize == 6:
self.serial.bytesize = serial.SIXBITS
elif self.bytesize == 7:
self.serial.bytesize = serial.SEVENBITS
else:
self.serial.bytesize = serial.EIGHTBITS
if self.paritymode == 1:
self.serial.paritymode = serial.PARITY_ODD
elif self.paritymode == 2:
self.serial.paritymode = serial.PARITY_EVEN
elif self.paritymode == 3:
self.serial.paritymode = serial.PARITY_MARK
elif self.paritymode == 4:
self.serial.paritymode = serial.PARITY_SPACE
else:
self.serial.paritymode = serial.PARITY_NONE
if self.stopbits == 1.5:
self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
elif self.stopbits == 2:
self.serial.stopbits = serial.STOPBITS_TWO
else:
self.serial.stopbits = serial.STOPBITS_ONE
self.serial.timeout = self.timeout
self.serial.xonxoff = self.xonxoff
self.serial.rtscts = self.rtscts
self.serial.dsrdtr = self.dsrdtr
if self.dsrdtr:
self.wait_dsr = True
self.message_delay = 0.1
def write_raw(self, data):
if self.term_char is not None:
data += str(self.term_char).encode('utf-8')[0]
self.serial.write(data)
if self.message_delay > 0:
time.sleep(self.message_delay)
if self.wait_dsr:
while not self.serial.getDSR():
time.sleep(0.01)
def read_raw(self, num=-1):
data = b''
term_char = str(self.term_char).encode('utf-8')[0]
while True:
c = self.serial.read(1)
data += c
num -= 1
if c == term_char:
break
if num == 0:
break
return data
def ask_raw(self, data, num=-1):
self.write_raw(data)
return self.read_raw(num)
def write(self, message, encoding = 'utf-8'):
if type(message) is tuple or type(message) is list:
for message_i in message:
self.write(message_i, encoding)
return
self.write_raw(str(message).encode(encoding))
def read(self, num=-1, encoding = 'utf-8'):
return self.read_raw(num).decode(encoding).rstrip('\r\n')
def ask(self, message, num=-1, encoding = 'utf-8'):
if type(message) is tuple or type(message) is list:
val = list()
for message_i in message:
val.append(self.ask(message_i, num, encoding))
return val
self.write(message, encoding)
return self.read(num, encoding)
def read_stb(self):
raise NotImplementedError()
def trigger(self):
self.write("*TRG")
def clear(self):
self.write("*CLS")
def remote(self):
raise NotImplementedError()
def local(self):
raise NotImplementedError()
def lock(self):
raise NotImplementedError()
def unlock(self):
raise NotImplementedError()
| true | true |
f73bb6c9a1c6370708bf1d807f69c3b493c975e9 | 2,100 | py | Python | pyler/euler_test_base.py | ewjoachim/pyler | e672f790f1160905fc01e30893e068f4bf301317 | [
"MIT"
] | 1 | 2015-11-02T14:26:34.000Z | 2015-11-02T14:26:34.000Z | pyler/euler_test_base.py | ewjoachim/pyler | e672f790f1160905fc01e30893e068f4bf301317 | [
"MIT"
] | 8 | 2015-11-05T06:23:07.000Z | 2017-08-31T17:10:56.000Z | pyler/euler_test_base.py | ewjoachim/pyler | e672f790f1160905fc01e30893e068f4bf301317 | [
"MIT"
] | 2 | 2016-06-12T07:16:46.000Z | 2017-08-31T14:48:41.000Z | import signal
import unittest
import time
from . import website as w
class EulerProblem(unittest.TestCase):
problem_id = None
def solver(self, input_val):
raise NotImplementedError()
simple_input = None
simple_output = None
real_input = None
def solve_real(self):
"""
Returns the solution of the Problem for the real input
"""
return self.solver(self.real_input)
def solve_simple(self):
"""
Returns the solution of the Problem for the simple input
"""
return self.solver(self.simple_input)
@classmethod
def setUpClass(cls):
if cls.solver is EulerProblem.solver:
raise unittest.SkipTest(
"Not running the tests for a not implemented problem")
def test_simple(self):
"""
Checks the simple example
"""
self.assertEqual(self.solve_simple(), self.simple_output)
def test_real(self):
"""
Checks the real problem against the website
"""
website = w.Website()
real_output = self.solve_real()
self.assertTrue(w.check_solution(
website, self.problem_id, solution=real_output))
# Windows has no Alarm signal. Sorry pal.
use_signal = hasattr(signal, "SIGALRM")
def test_time(self):
"""
Checks that the real problem runs under a minute
"""
time_limit = 60
try:
if self.use_signal:
def handler(signum, frame): # pylint: disable=unused-argument
raise TimeoutError()
old_handler = signal.signal(signal.SIGALRM, handler)
signal.alarm(time_limit)
before = time.time()
self.solve_real()
after = time.time()
if after - before > time_limit:
raise TimeoutError()
except TimeoutError:
self.fail("Test failed to end in less than a minute.")
finally:
if self.use_signal:
signal.signal(signal.SIGALRM, old_handler)
| 27.272727 | 78 | 0.587143 | import signal
import unittest
import time
from . import website as w
class EulerProblem(unittest.TestCase):
problem_id = None
def solver(self, input_val):
raise NotImplementedError()
simple_input = None
simple_output = None
real_input = None
def solve_real(self):
return self.solver(self.real_input)
def solve_simple(self):
return self.solver(self.simple_input)
@classmethod
def setUpClass(cls):
if cls.solver is EulerProblem.solver:
raise unittest.SkipTest(
"Not running the tests for a not implemented problem")
def test_simple(self):
self.assertEqual(self.solve_simple(), self.simple_output)
def test_real(self):
website = w.Website()
real_output = self.solve_real()
self.assertTrue(w.check_solution(
website, self.problem_id, solution=real_output))
use_signal = hasattr(signal, "SIGALRM")
def test_time(self):
time_limit = 60
try:
if self.use_signal:
def handler(signum, frame):
raise TimeoutError()
old_handler = signal.signal(signal.SIGALRM, handler)
signal.alarm(time_limit)
before = time.time()
self.solve_real()
after = time.time()
if after - before > time_limit:
raise TimeoutError()
except TimeoutError:
self.fail("Test failed to end in less than a minute.")
finally:
if self.use_signal:
signal.signal(signal.SIGALRM, old_handler)
| true | true |
f73bba4db4a97e0ebfc82fc883c1b0a11f38eb55 | 26,654 | py | Python | sdk/storage/azure-mgmt-storage/azure/mgmt/storage/v2019_06_01/aio/operations/_file_shares_operations.py | beltr0n/azure-sdk-for-python | 2f7fb8bee881b0fc0386a0ad5385755ceedd0453 | [
"MIT"
] | 2 | 2021-03-24T06:26:11.000Z | 2021-04-18T15:55:59.000Z | sdk/storage/azure-mgmt-storage/azure/mgmt/storage/v2019_06_01/aio/operations/_file_shares_operations.py | beltr0n/azure-sdk-for-python | 2f7fb8bee881b0fc0386a0ad5385755ceedd0453 | [
"MIT"
] | 4 | 2019-04-17T17:57:49.000Z | 2020-04-24T21:11:22.000Z | sdk/storage/azure-mgmt-storage/azure/mgmt/storage/v2019_06_01/aio/operations/_file_shares_operations.py | beltr0n/azure-sdk-for-python | 2f7fb8bee881b0fc0386a0ad5385755ceedd0453 | [
"MIT"
] | 2 | 2021-05-23T16:46:31.000Z | 2021-05-26T23:51:09.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class FileSharesOperations:
"""FileSharesOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.storage.v2019_06_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def list(
self,
resource_group_name: str,
account_name: str,
maxpagesize: Optional[str] = None,
filter: Optional[str] = None,
expand: Optional[str] = "deleted",
**kwargs
) -> AsyncIterable["_models.FileShareItems"]:
"""Lists all shares.
:param resource_group_name: The name of the resource group within the user's subscription. The
name is case insensitive.
:type resource_group_name: str
:param account_name: The name of the storage account within the specified resource group.
Storage account names must be between 3 and 24 characters in length and use numbers and lower-
case letters only.
:type account_name: str
:param maxpagesize: Optional. Specified maximum number of shares that can be included in the
list.
:type maxpagesize: str
:param filter: Optional. When specified, only share names starting with the filter will be
listed.
:type filter: str
:param expand: Optional, used to expand the properties within share's properties.
:type expand: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either FileShareItems or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.storage.v2019_06_01.models.FileShareItems]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.FileShareItems"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
if maxpagesize is not None:
query_parameters['$maxpagesize'] = self._serialize.query("maxpagesize", maxpagesize, 'str')
if filter is not None:
query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('FileShareItems', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares'} # type: ignore
async def create(
self,
resource_group_name: str,
account_name: str,
share_name: str,
file_share: "_models.FileShare",
**kwargs
) -> "_models.FileShare":
"""Creates a new share under the specified account as described by request body. The share
resource includes metadata and properties for that share. It does not include a list of the
files contained by the share.
:param resource_group_name: The name of the resource group within the user's subscription. The
name is case insensitive.
:type resource_group_name: str
:param account_name: The name of the storage account within the specified resource group.
Storage account names must be between 3 and 24 characters in length and use numbers and lower-
case letters only.
:type account_name: str
:param share_name: The name of the file share within the specified storage account. File share
names must be between 3 and 63 characters in length and use numbers, lower-case letters and
dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter
or number.
:type share_name: str
:param file_share: Properties of the file share to create.
:type file_share: ~azure.mgmt.storage.v2019_06_01.models.FileShare
:keyword callable cls: A custom type or function that will be passed the direct response
:return: FileShare, or the result of cls(response)
:rtype: ~azure.mgmt.storage.v2019_06_01.models.FileShare
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.FileShare"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.create.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'shareName': self._serialize.url("share_name", share_name, 'str', max_length=63, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(file_share, 'FileShare')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('FileShare', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('FileShare', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}'} # type: ignore
async def update(
self,
resource_group_name: str,
account_name: str,
share_name: str,
file_share: "_models.FileShare",
**kwargs
) -> "_models.FileShare":
"""Updates share properties as specified in request body. Properties not mentioned in the request
will not be changed. Update fails if the specified share does not already exist.
:param resource_group_name: The name of the resource group within the user's subscription. The
name is case insensitive.
:type resource_group_name: str
:param account_name: The name of the storage account within the specified resource group.
Storage account names must be between 3 and 24 characters in length and use numbers and lower-
case letters only.
:type account_name: str
:param share_name: The name of the file share within the specified storage account. File share
names must be between 3 and 63 characters in length and use numbers, lower-case letters and
dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter
or number.
:type share_name: str
:param file_share: Properties to update for the file share.
:type file_share: ~azure.mgmt.storage.v2019_06_01.models.FileShare
:keyword callable cls: A custom type or function that will be passed the direct response
:return: FileShare, or the result of cls(response)
:rtype: ~azure.mgmt.storage.v2019_06_01.models.FileShare
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.FileShare"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.update.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'shareName': self._serialize.url("share_name", share_name, 'str', max_length=63, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(file_share, 'FileShare')
body_content_kwargs['content'] = body_content
request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('FileShare', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}'} # type: ignore
async def get(
self,
resource_group_name: str,
account_name: str,
share_name: str,
expand: Optional[str] = "stats",
**kwargs
) -> "_models.FileShare":
"""Gets properties of a specified share.
:param resource_group_name: The name of the resource group within the user's subscription. The
name is case insensitive.
:type resource_group_name: str
:param account_name: The name of the storage account within the specified resource group.
Storage account names must be between 3 and 24 characters in length and use numbers and lower-
case letters only.
:type account_name: str
:param share_name: The name of the file share within the specified storage account. File share
names must be between 3 and 63 characters in length and use numbers, lower-case letters and
dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter
or number.
:type share_name: str
:param expand: Optional, used to expand the properties within share's properties.
:type expand: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: FileShare, or the result of cls(response)
:rtype: ~azure.mgmt.storage.v2019_06_01.models.FileShare
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.FileShare"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'shareName': self._serialize.url("share_name", share_name, 'str', max_length=63, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('FileShare', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}'} # type: ignore
async def delete(
self,
resource_group_name: str,
account_name: str,
share_name: str,
**kwargs
) -> None:
"""Deletes specified share under its account.
:param resource_group_name: The name of the resource group within the user's subscription. The
name is case insensitive.
:type resource_group_name: str
:param account_name: The name of the storage account within the specified resource group.
Storage account names must be between 3 and 24 characters in length and use numbers and lower-
case letters only.
:type account_name: str
:param share_name: The name of the file share within the specified storage account. File share
names must be between 3 and 63 characters in length and use numbers, lower-case letters and
dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter
or number.
:type share_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01"
accept = "application/json"
# Construct URL
url = self.delete.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'shareName': self._serialize.url("share_name", share_name, 'str', max_length=63, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}'} # type: ignore
async def restore(
self,
resource_group_name: str,
account_name: str,
share_name: str,
deleted_share: "_models.DeletedShare",
**kwargs
) -> None:
"""Restore a file share within a valid retention days if share soft delete is enabled.
:param resource_group_name: The name of the resource group within the user's subscription. The
name is case insensitive.
:type resource_group_name: str
:param account_name: The name of the storage account within the specified resource group.
Storage account names must be between 3 and 24 characters in length and use numbers and lower-
case letters only.
:type account_name: str
:param share_name: The name of the file share within the specified storage account. File share
names must be between 3 and 63 characters in length and use numbers, lower-case letters and
dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter
or number.
:type share_name: str
:param deleted_share:
:type deleted_share: ~azure.mgmt.storage.v2019_06_01.models.DeletedShare
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.restore.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'shareName': self._serialize.url("share_name", share_name, 'str', max_length=63, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(deleted_share, 'DeletedShare')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
restore.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}/restore'} # type: ignore
| 52.571992 | 222 | 0.66928 |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class FileSharesOperations:
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def list(
self,
resource_group_name: str,
account_name: str,
maxpagesize: Optional[str] = None,
filter: Optional[str] = None,
expand: Optional[str] = "deleted",
**kwargs
) -> AsyncIterable["_models.FileShareItems"]:
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01"
accept = "application/json"
def prepare_request(next_link=None):
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
url = self.list.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
if maxpagesize is not None:
query_parameters['$maxpagesize'] = self._serialize.query("maxpagesize", maxpagesize, 'str')
if filter is not None:
query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {}
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('FileShareItems', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares'}
async def create(
self,
resource_group_name: str,
account_name: str,
share_name: str,
file_share: "_models.FileShare",
**kwargs
) -> "_models.FileShare":
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
url = self.create.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'shareName': self._serialize.url("share_name", share_name, 'str', max_length=63, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {}
body_content = self._serialize.body(file_share, 'FileShare')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('FileShare', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('FileShare', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}'}
async def update(
self,
resource_group_name: str,
account_name: str,
share_name: str,
file_share: "_models.FileShare",
**kwargs
) -> "_models.FileShare":
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
url = self.update.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'shareName': self._serialize.url("share_name", share_name, 'str', max_length=63, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {}
body_content = self._serialize.body(file_share, 'FileShare')
body_content_kwargs['content'] = body_content
request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('FileShare', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}'}
async def get(
self,
resource_group_name: str,
account_name: str,
share_name: str,
expand: Optional[str] = "stats",
**kwargs
) -> "_models.FileShare":
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01"
accept = "application/json"
url = self.get.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'shareName': self._serialize.url("share_name", share_name, 'str', max_length=63, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('FileShare', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}'}
async def delete(
self,
resource_group_name: str,
account_name: str,
share_name: str,
**kwargs
) -> None:
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01"
accept = "application/json"
url = self.delete.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'shareName': self._serialize.url("share_name", share_name, 'str', max_length=63, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}'}
async def restore(
self,
resource_group_name: str,
account_name: str,
share_name: str,
deleted_share: "_models.DeletedShare",
**kwargs
) -> None:
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
url = self.restore.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=24, min_length=3),
'shareName': self._serialize.url("share_name", share_name, 'str', max_length=63, min_length=3),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {}
body_content = self._serialize.body(deleted_share, 'DeletedShare')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
restore.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}/restore'}
| true | true |
f73bbcedcd25303f7209490e28a550849e1245fb | 3,711 | py | Python | supriya/ugens/MulAdd.py | deeuu/supriya | 14fcb5316eccb4dafbe498932ceff56e1abb9d27 | [
"MIT"
] | null | null | null | supriya/ugens/MulAdd.py | deeuu/supriya | 14fcb5316eccb4dafbe498932ceff56e1abb9d27 | [
"MIT"
] | null | null | null | supriya/ugens/MulAdd.py | deeuu/supriya | 14fcb5316eccb4dafbe498932ceff56e1abb9d27 | [
"MIT"
] | null | null | null | import collections
from supriya import CalculationRate
from supriya.synthdefs import UGen
class MulAdd(UGen):
"""
An Optimized multiplication / addition ugen.
::
>>> source = supriya.ugens.SinOsc.ar()
>>> mul_add = supriya.ugens.MulAdd.new(
... addend=0.5,
... multiplier=-1.5,
... source=source,
... )
>>> mul_add
MulAdd.ar()
"""
### CLASS VARIABLES ###
__documentation_section__ = "Basic Operator UGens"
_ordered_input_names = collections.OrderedDict(
[("source", None), ("multiplier", 1.0), ("addend", 0.0)]
)
### INITIALIZER ###
def __init__(self, addend=0.0, multiplier=1.0, calculation_rate=None, source=None):
UGen.__init__(
self,
addend=addend,
multiplier=multiplier,
calculation_rate=calculation_rate,
source=source,
)
### PRIVATE METHODS ###
@staticmethod
def _inputs_are_valid(source, multiplier, addend):
if CalculationRate.from_expr(source) == CalculationRate.AUDIO:
return True
if CalculationRate.from_expr(source) == CalculationRate.CONTROL:
if CalculationRate.from_expr(multiplier) in (
CalculationRate.CONTROL,
CalculationRate.SCALAR,
):
if CalculationRate.from_expr(addend) in (
CalculationRate.CONTROL,
CalculationRate.SCALAR,
):
return True
return False
@classmethod
def _new_single(
cls, addend=None, multiplier=None, calculation_rate=None, source=None
):
if multiplier == 0.0:
return addend
minus = multiplier == -1
no_multiplier = multiplier == 1
no_addend = addend == 0
if no_multiplier and no_addend:
return source
if minus and no_addend:
return -source
if no_addend:
return source * multiplier
if minus:
return addend - source
if no_multiplier:
return source + addend
if cls._inputs_are_valid(source, multiplier, addend):
return cls(
addend=addend,
multiplier=multiplier,
calculation_rate=calculation_rate,
source=source,
)
if cls._inputs_are_valid(multiplier, source, addend):
return cls(
addend=addend,
multiplier=source,
calculation_rate=calculation_rate,
source=multiplier,
)
return (source * multiplier) + addend
### PUBLIC METHODS ###
@classmethod
def new(cls, source=None, multiplier=1.0, addend=0.0):
"""
Constructs a multiplication / addition ugen.
::
>>> addend = 0.5
>>> multiplier = 1.5
>>> source = supriya.ugens.SinOsc.ar(frequency=[440, 442])
>>> mul_add = supriya.ugens.MulAdd.new(
... addend=addend,
... multiplier=multiplier,
... source=source,
... )
>>> mul_add
UGenArray({2})
Returns ugen graph.
"""
import supriya.synthdefs
# TODO: handle case of array as source
calculation_rate = supriya.CalculationRate.from_expr(
(source, multiplier, addend)
)
ugen = cls._new_expanded(
addend=addend,
multiplier=multiplier,
calculation_rate=calculation_rate,
source=source,
)
return ugen
| 28.328244 | 87 | 0.537591 | import collections
from supriya import CalculationRate
from supriya.synthdefs import UGen
class MulAdd(UGen):
UGens"
_ordered_input_names = collections.OrderedDict(
[("source", None), ("multiplier", 1.0), ("addend", 0.0)]
)
iplier=1.0, calculation_rate=None, source=None):
UGen.__init__(
self,
addend=addend,
multiplier=multiplier,
calculation_rate=calculation_rate,
source=source,
)
rce, multiplier, addend):
if CalculationRate.from_expr(source) == CalculationRate.AUDIO:
return True
if CalculationRate.from_expr(source) == CalculationRate.CONTROL:
if CalculationRate.from_expr(multiplier) in (
CalculationRate.CONTROL,
CalculationRate.SCALAR,
):
if CalculationRate.from_expr(addend) in (
CalculationRate.CONTROL,
CalculationRate.SCALAR,
):
return True
return False
@classmethod
def _new_single(
cls, addend=None, multiplier=None, calculation_rate=None, source=None
):
if multiplier == 0.0:
return addend
minus = multiplier == -1
no_multiplier = multiplier == 1
no_addend = addend == 0
if no_multiplier and no_addend:
return source
if minus and no_addend:
return -source
if no_addend:
return source * multiplier
if minus:
return addend - source
if no_multiplier:
return source + addend
if cls._inputs_are_valid(source, multiplier, addend):
return cls(
addend=addend,
multiplier=multiplier,
calculation_rate=calculation_rate,
source=source,
)
if cls._inputs_are_valid(multiplier, source, addend):
return cls(
addend=addend,
multiplier=source,
calculation_rate=calculation_rate,
source=multiplier,
)
return (source * multiplier) + addend
, multiplier=1.0, addend=0.0):
import supriya.synthdefs
calculation_rate = supriya.CalculationRate.from_expr(
(source, multiplier, addend)
)
ugen = cls._new_expanded(
addend=addend,
multiplier=multiplier,
calculation_rate=calculation_rate,
source=source,
)
return ugen
| true | true |
f73bbdcc0b57b7ad395633254e4bb235902586b0 | 1,400 | py | Python | pictures/tests.py | leezichanga/gallery | cd1b84ab204098b85109d4030024a04494500c83 | [
"MIT"
] | null | null | null | pictures/tests.py | leezichanga/gallery | cd1b84ab204098b85109d4030024a04494500c83 | [
"MIT"
] | null | null | null | pictures/tests.py | leezichanga/gallery | cd1b84ab204098b85109d4030024a04494500c83 | [
"MIT"
] | null | null | null | from django.test import TestCase
import datetime as dt
# Create your tests here.
from .models import Photos, categories, Location
class LocationTestClass(TestCase):
def setUp(self):
self.location = Location(name = 'Nairobi')
def test_instance(self):
self.assertTrue(isinstance(self.location, Location))
def test_save_method(self):
self.location.save_location()
locations = Location.objects.all()
self.assertTrue(len(locations)>0)
def test_delete_method(self):
self.location.save_location()
locations = Location.objects.all()
self.location.delete_location()
locations = Location.objects.all()
self.assertTrue(len(locations)==0)
class CategoriesTestClass(TestCase):
def setUp(self):
self.category = categories(name='nature')
def test_category_instance(self):
self.assertTrue(isinstance(self.category, categories))
def test_save_category_method(self):
self.category.save_category()
categories_object = categories.objects.all()
self.assertTrue(len(categories_object)>0)
def test_delete_category_method(self):
self.category.save_category()
categories_object = categories.objects.all()
self.category.delete_category()
categories_object = categories.objects.all()
self.assertTrue(len(categories_object)==0)
| 32.55814 | 62 | 0.697857 | from django.test import TestCase
import datetime as dt
from .models import Photos, categories, Location
class LocationTestClass(TestCase):
def setUp(self):
self.location = Location(name = 'Nairobi')
def test_instance(self):
self.assertTrue(isinstance(self.location, Location))
def test_save_method(self):
self.location.save_location()
locations = Location.objects.all()
self.assertTrue(len(locations)>0)
def test_delete_method(self):
self.location.save_location()
locations = Location.objects.all()
self.location.delete_location()
locations = Location.objects.all()
self.assertTrue(len(locations)==0)
class CategoriesTestClass(TestCase):
def setUp(self):
self.category = categories(name='nature')
def test_category_instance(self):
self.assertTrue(isinstance(self.category, categories))
def test_save_category_method(self):
self.category.save_category()
categories_object = categories.objects.all()
self.assertTrue(len(categories_object)>0)
def test_delete_category_method(self):
self.category.save_category()
categories_object = categories.objects.all()
self.category.delete_category()
categories_object = categories.objects.all()
self.assertTrue(len(categories_object)==0)
| true | true |
f73bc0c617b8098d0b17d0993ff0d79ec005a361 | 4,853 | py | Python | nova/tests/api/test_auth.py | bopopescu/nova-34 | b037993984229bb698050f20e8719b8c06ff2be3 | [
"Apache-2.0"
] | null | null | null | nova/tests/api/test_auth.py | bopopescu/nova-34 | b037993984229bb698050f20e8719b8c06ff2be3 | [
"Apache-2.0"
] | null | null | null | nova/tests/api/test_auth.py | bopopescu/nova-34 | b037993984229bb698050f20e8719b8c06ff2be3 | [
"Apache-2.0"
] | 1 | 2020-07-24T08:52:14.000Z | 2020-07-24T08:52:14.000Z | # Copyright (c) 2012 OpenStack Foundation
#
# 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 json
import webob
import webob.exc
import nova.api.auth
from nova.openstack.common.gettextutils import _
from nova import test
class TestNovaKeystoneContextMiddleware(test.TestCase):
def setUp(self):
super(TestNovaKeystoneContextMiddleware, self).setUp()
@webob.dec.wsgify()
def fake_app(req):
self.context = req.environ['nova.context']
return webob.Response()
self.context = None
self.middleware = nova.api.auth.NovaKeystoneContext(fake_app)
self.request = webob.Request.blank('/')
self.request.headers['X_TENANT_ID'] = 'testtenantid'
self.request.headers['X_AUTH_TOKEN'] = 'testauthtoken'
self.request.headers['X_SERVICE_CATALOG'] = json.dumps({})
def test_no_user_or_user_id(self):
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '401 Unauthorized')
def test_user_only(self):
self.request.headers['X_USER_ID'] = 'testuserid'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 OK')
self.assertEqual(self.context.user_id, 'testuserid')
def test_user_id_only(self):
self.request.headers['X_USER'] = 'testuser'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 OK')
self.assertEqual(self.context.user_id, 'testuser')
def test_user_id_trumps_user(self):
self.request.headers['X_USER_ID'] = 'testuserid'
self.request.headers['X_USER'] = 'testuser'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 OK')
self.assertEqual(self.context.user_id, 'testuserid')
def test_invalid_service_catalog(self):
self.request.headers['X_USER'] = 'testuser'
self.request.headers['X_SERVICE_CATALOG'] = "bad json"
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '500 Internal Server Error')
class TestKeystoneMiddlewareRoles(test.TestCase):
def setUp(self):
super(TestKeystoneMiddlewareRoles, self).setUp()
@webob.dec.wsgify()
def role_check_app(req):
context = req.environ['nova.context']
if "knight" in context.roles and "bad" not in context.roles:
return webob.Response(status="200 Role Match")
elif context.roles == ['']:
return webob.Response(status="200 No Roles")
else:
raise webob.exc.HTTPBadRequest(_("unexpected role header"))
self.middleware = nova.api.auth.NovaKeystoneContext(role_check_app)
self.request = webob.Request.blank('/')
self.request.headers['X_USER'] = 'testuser'
self.request.headers['X_TENANT_ID'] = 'testtenantid'
self.request.headers['X_AUTH_TOKEN'] = 'testauthtoken'
self.request.headers['X_SERVICE_CATALOG'] = json.dumps({})
self.roles = "pawn, knight, rook"
def test_roles(self):
# Test that the newer style role header takes precedence.
self.request.headers['X_ROLES'] = 'pawn,knight,rook'
self.request.headers['X_ROLE'] = 'bad'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 Role Match')
def test_roles_empty(self):
self.request.headers['X_ROLES'] = ''
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 No Roles')
def test_deprecated_role(self):
# Test fallback to older role header.
self.request.headers['X_ROLE'] = 'pawn,knight,rook'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 Role Match')
def test_role_empty(self):
self.request.headers['X_ROLE'] = ''
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 No Roles')
def test_no_role_headers(self):
# Test with no role headers set.
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 No Roles')
| 38.515873 | 78 | 0.675665 |
import json
import webob
import webob.exc
import nova.api.auth
from nova.openstack.common.gettextutils import _
from nova import test
class TestNovaKeystoneContextMiddleware(test.TestCase):
def setUp(self):
super(TestNovaKeystoneContextMiddleware, self).setUp()
@webob.dec.wsgify()
def fake_app(req):
self.context = req.environ['nova.context']
return webob.Response()
self.context = None
self.middleware = nova.api.auth.NovaKeystoneContext(fake_app)
self.request = webob.Request.blank('/')
self.request.headers['X_TENANT_ID'] = 'testtenantid'
self.request.headers['X_AUTH_TOKEN'] = 'testauthtoken'
self.request.headers['X_SERVICE_CATALOG'] = json.dumps({})
def test_no_user_or_user_id(self):
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '401 Unauthorized')
def test_user_only(self):
self.request.headers['X_USER_ID'] = 'testuserid'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 OK')
self.assertEqual(self.context.user_id, 'testuserid')
def test_user_id_only(self):
self.request.headers['X_USER'] = 'testuser'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 OK')
self.assertEqual(self.context.user_id, 'testuser')
def test_user_id_trumps_user(self):
self.request.headers['X_USER_ID'] = 'testuserid'
self.request.headers['X_USER'] = 'testuser'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 OK')
self.assertEqual(self.context.user_id, 'testuserid')
def test_invalid_service_catalog(self):
self.request.headers['X_USER'] = 'testuser'
self.request.headers['X_SERVICE_CATALOG'] = "bad json"
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '500 Internal Server Error')
class TestKeystoneMiddlewareRoles(test.TestCase):
def setUp(self):
super(TestKeystoneMiddlewareRoles, self).setUp()
@webob.dec.wsgify()
def role_check_app(req):
context = req.environ['nova.context']
if "knight" in context.roles and "bad" not in context.roles:
return webob.Response(status="200 Role Match")
elif context.roles == ['']:
return webob.Response(status="200 No Roles")
else:
raise webob.exc.HTTPBadRequest(_("unexpected role header"))
self.middleware = nova.api.auth.NovaKeystoneContext(role_check_app)
self.request = webob.Request.blank('/')
self.request.headers['X_USER'] = 'testuser'
self.request.headers['X_TENANT_ID'] = 'testtenantid'
self.request.headers['X_AUTH_TOKEN'] = 'testauthtoken'
self.request.headers['X_SERVICE_CATALOG'] = json.dumps({})
self.roles = "pawn, knight, rook"
def test_roles(self):
self.request.headers['X_ROLES'] = 'pawn,knight,rook'
self.request.headers['X_ROLE'] = 'bad'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 Role Match')
def test_roles_empty(self):
self.request.headers['X_ROLES'] = ''
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 No Roles')
def test_deprecated_role(self):
self.request.headers['X_ROLE'] = 'pawn,knight,rook'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 Role Match')
def test_role_empty(self):
self.request.headers['X_ROLE'] = ''
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 No Roles')
def test_no_role_headers(self):
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 No Roles')
| true | true |
f73bc0eac30c71689b230efc46d89e81363191f5 | 5,271 | py | Python | tests/test_tools_pdf2txt.py | ehtec/pdfminer.six | 5b1823f25ab998e904fc5d81687732580f23e3b9 | [
"MIT"
] | null | null | null | tests/test_tools_pdf2txt.py | ehtec/pdfminer.six | 5b1823f25ab998e904fc5d81687732580f23e3b9 | [
"MIT"
] | 1 | 2022-01-31T22:58:07.000Z | 2022-01-31T22:58:07.000Z | tests/test_tools_pdf2txt.py | phantomcyber/pdfminer.six | e35a9319a6ae5d310f08f07a5edf16aadc529c1e | [
"MIT"
] | null | null | null | import os
from shutil import rmtree
from tempfile import mkdtemp
import filecmp
import tools.pdf2txt as pdf2txt
from helpers import absolute_sample_path
from tempfilepath import TemporaryFilePath
def run(sample_path, options=None):
absolute_path = absolute_sample_path(sample_path)
with TemporaryFilePath() as output_file_name:
if options:
s = 'pdf2txt -o{} {} {}' \
.format(output_file_name, options, absolute_path)
else:
s = 'pdf2txt -o{} {}'.format(output_file_name, absolute_path)
pdf2txt.main(s.split(' ')[1:])
class TestPdf2Txt():
def test_jo(self):
run('jo.pdf')
def test_simple1(self):
run('simple1.pdf')
def test_simple2(self):
run('simple2.pdf')
def test_simple3(self):
run('simple3.pdf')
def test_sample_one_byte_identity_encode(self):
run('sampleOneByteIdentityEncode.pdf')
def test_nonfree_175(self):
"""Regression test for:
https://github.com/pdfminer/pdfminer.six/issues/65
"""
run('nonfree/175.pdf')
def test_nonfree_dmca(self):
run('nonfree/dmca.pdf')
def test_nonfree_f1040nr(self):
run('nonfree/f1040nr.pdf')
def test_nonfree_i1040nr(self):
run('nonfree/i1040nr.pdf')
def test_nonfree_kampo(self):
run('nonfree/kampo.pdf')
def test_nonfree_naacl06_shinyama(self):
run('nonfree/naacl06-shinyama.pdf')
def test_nlp2004slides(self):
run('nonfree/nlp2004slides.pdf')
def test_contrib_2b(self):
run('contrib/2b.pdf', '-A -t xml')
def test_contrib_issue_350(self):
"""Regression test for
https://github.com/pdfminer/pdfminer.six/issues/350"""
run('contrib/issue-00352-asw-oct96-p41.pdf')
def test_scancode_patchelf(self):
"""Regression test for https://github.com/euske/pdfminer/issues/96"""
run('scancode/patchelf.pdf')
def test_contrib_hash_two_complement(self):
"""Check that unsigned integer is added correctly to encryption hash.et
See https://github.com/pdfminer/pdfminer.six/issues/186
"""
run('contrib/issue-00352-hash-twos-complement.pdf')
def test_contrib_excel(self):
"""Regression test for
https://github.com/pdfminer/pdfminer.six/issues/369
"""
run('contrib/issue-00369-excel.pdf', '-t html')
def test_encryption_aes128(self):
run('encryption/aes-128.pdf', '-P foo')
def test_encryption_aes128m(self):
run('encryption/aes-128-m.pdf', '-P foo')
def test_encryption_aes256(self):
run('encryption/aes-256.pdf', '-P foo')
def test_encryption_aes256m(self):
run('encryption/aes-256-m.pdf', '-P foo')
def test_encryption_aes256_r6_user(self):
run('encryption/aes-256-r6.pdf', '-P usersecret')
def test_encryption_aes256_r6_owner(self):
run('encryption/aes-256-r6.pdf', '-P ownersecret')
def test_encryption_base(self):
run('encryption/base.pdf', '-P foo')
def test_encryption_rc4_40(self):
run('encryption/rc4-40.pdf', '-P foo')
def test_encryption_rc4_128(self):
run('encryption/rc4-128.pdf', '-P foo')
class TestDumpImages:
@staticmethod
def extract_images(input_file):
output_dir = mkdtemp()
with TemporaryFilePath() as output_file_name:
commands = ['-o', output_file_name, '--output-dir',
output_dir, input_file]
pdf2txt.main(commands)
image_files = os.listdir(output_dir)
rmtree(output_dir)
return image_files
def test_nonfree_dmca(self):
"""Extract images of pdf containing bmp images
Regression test for:
https://github.com/pdfminer/pdfminer.six/issues/131
"""
image_files = self.extract_images(
absolute_sample_path('../samples/nonfree/dmca.pdf'))
assert image_files[0].endswith('bmp')
def test_nonfree_175(self):
"""Extract images of pdf containing jpg images"""
self.extract_images(absolute_sample_path('../samples/nonfree/175.pdf'))
def test_jbig2_image_export(self):
"""Extract images of pdf containing jbig2 images
Feature test for: https://github.com/pdfminer/pdfminer.six/pull/46
"""
input_file = absolute_sample_path(
'../samples/contrib/pdf-with-jbig2.pdf')
output_dir = mkdtemp()
with TemporaryFilePath() as output_file_name:
commands = ['-o', output_file_name, '--output-dir',
output_dir, input_file]
pdf2txt.main(commands)
image_files = os.listdir(output_dir)
try:
assert image_files[0].endswith('.jb2')
assert filecmp.cmp(output_dir + '/' + image_files[0],
absolute_sample_path(
'../samples/contrib/XIPLAYER0.jb2'))
finally:
rmtree(output_dir)
def test_contrib_matplotlib(self):
"""Test a pdf with Type3 font"""
run('contrib/matplotlib.pdf')
def test_nonfree_cmp_itext_logo(self):
"""Test a pdf with Type3 font"""
run('nonfree/cmp_itext_logo.pdf')
| 30.824561 | 79 | 0.631379 | import os
from shutil import rmtree
from tempfile import mkdtemp
import filecmp
import tools.pdf2txt as pdf2txt
from helpers import absolute_sample_path
from tempfilepath import TemporaryFilePath
def run(sample_path, options=None):
absolute_path = absolute_sample_path(sample_path)
with TemporaryFilePath() as output_file_name:
if options:
s = 'pdf2txt -o{} {} {}' \
.format(output_file_name, options, absolute_path)
else:
s = 'pdf2txt -o{} {}'.format(output_file_name, absolute_path)
pdf2txt.main(s.split(' ')[1:])
class TestPdf2Txt():
def test_jo(self):
run('jo.pdf')
def test_simple1(self):
run('simple1.pdf')
def test_simple2(self):
run('simple2.pdf')
def test_simple3(self):
run('simple3.pdf')
def test_sample_one_byte_identity_encode(self):
run('sampleOneByteIdentityEncode.pdf')
def test_nonfree_175(self):
run('nonfree/175.pdf')
def test_nonfree_dmca(self):
run('nonfree/dmca.pdf')
def test_nonfree_f1040nr(self):
run('nonfree/f1040nr.pdf')
def test_nonfree_i1040nr(self):
run('nonfree/i1040nr.pdf')
def test_nonfree_kampo(self):
run('nonfree/kampo.pdf')
def test_nonfree_naacl06_shinyama(self):
run('nonfree/naacl06-shinyama.pdf')
def test_nlp2004slides(self):
run('nonfree/nlp2004slides.pdf')
def test_contrib_2b(self):
run('contrib/2b.pdf', '-A -t xml')
def test_contrib_issue_350(self):
run('contrib/issue-00352-asw-oct96-p41.pdf')
def test_scancode_patchelf(self):
run('scancode/patchelf.pdf')
def test_contrib_hash_two_complement(self):
run('contrib/issue-00352-hash-twos-complement.pdf')
def test_contrib_excel(self):
run('contrib/issue-00369-excel.pdf', '-t html')
def test_encryption_aes128(self):
run('encryption/aes-128.pdf', '-P foo')
def test_encryption_aes128m(self):
run('encryption/aes-128-m.pdf', '-P foo')
def test_encryption_aes256(self):
run('encryption/aes-256.pdf', '-P foo')
def test_encryption_aes256m(self):
run('encryption/aes-256-m.pdf', '-P foo')
def test_encryption_aes256_r6_user(self):
run('encryption/aes-256-r6.pdf', '-P usersecret')
def test_encryption_aes256_r6_owner(self):
run('encryption/aes-256-r6.pdf', '-P ownersecret')
def test_encryption_base(self):
run('encryption/base.pdf', '-P foo')
def test_encryption_rc4_40(self):
run('encryption/rc4-40.pdf', '-P foo')
def test_encryption_rc4_128(self):
run('encryption/rc4-128.pdf', '-P foo')
class TestDumpImages:
@staticmethod
def extract_images(input_file):
output_dir = mkdtemp()
with TemporaryFilePath() as output_file_name:
commands = ['-o', output_file_name, '--output-dir',
output_dir, input_file]
pdf2txt.main(commands)
image_files = os.listdir(output_dir)
rmtree(output_dir)
return image_files
def test_nonfree_dmca(self):
image_files = self.extract_images(
absolute_sample_path('../samples/nonfree/dmca.pdf'))
assert image_files[0].endswith('bmp')
def test_nonfree_175(self):
self.extract_images(absolute_sample_path('../samples/nonfree/175.pdf'))
def test_jbig2_image_export(self):
input_file = absolute_sample_path(
'../samples/contrib/pdf-with-jbig2.pdf')
output_dir = mkdtemp()
with TemporaryFilePath() as output_file_name:
commands = ['-o', output_file_name, '--output-dir',
output_dir, input_file]
pdf2txt.main(commands)
image_files = os.listdir(output_dir)
try:
assert image_files[0].endswith('.jb2')
assert filecmp.cmp(output_dir + '/' + image_files[0],
absolute_sample_path(
'../samples/contrib/XIPLAYER0.jb2'))
finally:
rmtree(output_dir)
def test_contrib_matplotlib(self):
run('contrib/matplotlib.pdf')
def test_nonfree_cmp_itext_logo(self):
run('nonfree/cmp_itext_logo.pdf')
| true | true |
f73bc29ff3af8410bbb96bd8e7e64ac5bb1fdf19 | 15,260 | py | Python | electrumsv/plugins/keepkey/plugin.py | bakketun/electrumsv | 1ed5b3d5b3f7e25d742d8634258322eee616d31a | [
"MIT"
] | null | null | null | electrumsv/plugins/keepkey/plugin.py | bakketun/electrumsv | 1ed5b3d5b3f7e25d742d8634258322eee616d31a | [
"MIT"
] | null | null | null | electrumsv/plugins/keepkey/plugin.py | bakketun/electrumsv | 1ed5b3d5b3f7e25d742d8634258322eee616d31a | [
"MIT"
] | null | null | null | from binascii import hexlify, unhexlify
import logging
import threading
from electrumsv.util import bfh, bh2u
from electrumsv.bitcoin import (xpub_from_pubkey, TYPE_ADDRESS, TYPE_SCRIPT)
from electrumsv.i18n import _
from electrumsv.transaction import deserialize
from electrumsv.keystore import Hardware_KeyStore, is_xpubkey, parse_xpubkey
from ..hw_wallet import HW_PluginBase
# TREZOR initialization methods
TIM_NEW, TIM_RECOVER, TIM_MNEMONIC, TIM_PRIVKEY = range(0, 4)
class KeepKeyCompatibleKeyStore(Hardware_KeyStore):
def get_derivation(self):
return self.derivation
def get_client(self, force_pair=True):
return self.plugin.get_client(self, force_pair)
def decrypt_message(self, sequence, message, password):
raise RuntimeError(_('Encryption and decryption are not implemented by {}').format(
self.device))
def sign_message(self, sequence, message, password):
client = self.get_client()
address_path = self.get_derivation() + "/%d/%d"%sequence
address_n = client.expand_path(address_path)
msg_sig = client.sign_message(self.plugin.get_coin_name(), address_n, message)
return msg_sig.signature
def sign_transaction(self, tx, password):
if tx.is_complete():
return
# previous transactions used as inputs
prev_tx = {}
# path of the xpubs that are involved
xpub_path = {}
for txin in tx.inputs():
pubkeys, x_pubkeys = tx.get_sorted_pubkeys(txin)
tx_hash = txin['prevout_hash']
prev_tx[tx_hash] = txin['prev_tx']
for x_pubkey in x_pubkeys:
if not is_xpubkey(x_pubkey):
continue
xpub, s = parse_xpubkey(x_pubkey)
if xpub == self.get_master_public_key():
xpub_path[xpub] = self.get_derivation()
self.plugin.sign_transaction(self, tx, prev_tx, xpub_path)
class KeepKeyCompatiblePlugin(HW_PluginBase):
# Derived classes provide:
#
# class-static variables: client_class, firmware_URL, handler_class,
# libraries_available, libraries_URL, minimum_firmware,
# wallet_class, ckd_public, types, HidTransport
MAX_LABEL_LEN = 32
def __init__(self, parent, config, name):
HW_PluginBase.__init__(self, parent, config, name)
self.logger = logging.getLogger("plugin.keepkey")
self.main_thread = threading.current_thread()
# FIXME: move to base class when Ledger is fixed
if self.libraries_available:
self.device_manager().register_devices(self.DEVICE_IDS)
def _try_hid(self, device):
self.logger.debug("Trying to connect over USB...")
if device.interface_number == 1:
pair = [None, device.path]
else:
pair = [device.path, None]
try:
return self.hid_transport(pair)
except BaseException as e:
# see fdb810ba622dc7dbe1259cbafb5b28e19d2ab114
# raise
self.logger.error("cannot connect at %s %s", device.path, e)
return None
def _try_bridge(self, device):
self.logger.debug("Trying to connect over Trezor Bridge...")
try:
return self.bridge_transport({'path': hexlify(device.path)})
except BaseException as e:
self.logger.error("cannot connect to bridge %s", e)
return None
def create_client(self, device, handler):
# disable bridge because it seems to never returns if keepkey is plugged
#transport = self._try_bridge(device) or self._try_hid(device)
transport = self._try_hid(device)
if not transport:
self.logger.error("cannot connect to device")
return
self.logger.debug("connected to device at %s", device.path)
client = self.client_class(transport, handler, self)
# Try a ping for device sanity
try:
client.ping('t')
except BaseException as e:
self.logger.error("ping failed %s", e)
return None
if not client.atleast_version(*self.minimum_firmware):
msg = (_('Outdated {} firmware for device labelled {}. Please '
'download the updated firmware from {}')
.format(self.device, client.label(), self.firmware_URL))
self.logger.error(msg)
handler.show_error(msg)
return None
return client
def get_client(self, keystore, force_pair=True):
devmgr = self.device_manager()
handler = keystore.handler
with devmgr.hid_lock:
client = devmgr.client_for_keystore(self, handler, keystore, force_pair)
# returns the client for a given keystore. can use xpub
if client:
client.used()
return client
def initialize_device(self, device_id, wizard, handler):
# Initialization method
msg = _("Choose how you want to initialize your {}.\n\n"
"The first two methods are secure as no secret information "
"is entered into your computer.\n\n"
"For the last two methods you input secrets on your keyboard "
"and upload them to your {}, and so you should "
"only do those on a computer you know to be trustworthy "
"and free of malware."
).format(self.device, self.device)
choices = [
# Must be short as QT doesn't word-wrap radio button text
(TIM_NEW, _("Let the device generate a completely new seed randomly")),
(TIM_RECOVER, _("Recover from a seed you have previously written down")),
(TIM_MNEMONIC, _("Upload a BIP39 mnemonic to generate the seed")),
(TIM_PRIVKEY, _("Upload a master private key"))
]
def f(method):
settings = self.request_trezor_init_settings(wizard, method, self.device)
t = threading.Thread(target = self._initialize_device,
args=(settings, method, device_id, wizard, handler))
t.setDaemon(True)
t.start()
wizard.loop.exec_()
wizard.choice_dialog(title=_('Initialize Device'), message=msg,
choices=choices, run_next=f)
def _initialize_device(self, settings, method, device_id, wizard, handler):
item, label, pin_protection, passphrase_protection = settings
language = 'english'
devmgr = self.device_manager()
client = devmgr.client_by_id(device_id)
if method == TIM_NEW:
strength = 64 * (item + 2) # 128, 192 or 256
client.reset_device(True, strength, passphrase_protection,
pin_protection, label, language)
elif method == TIM_RECOVER:
word_count = 6 * (item + 2) # 12, 18 or 24
client.step = 0
client.recovery_device(word_count, passphrase_protection,
pin_protection, label, language)
elif method == TIM_MNEMONIC:
pin = pin_protection # It's the pin, not a boolean
client.load_device_by_mnemonic(str(item), pin,
passphrase_protection,
label, language)
else:
pin = pin_protection # It's the pin, not a boolean
client.load_device_by_xprv(item, pin, passphrase_protection,
label, language)
wizard.loop.exit(0)
def setup_device(self, device_info, wizard):
'''Called when creating a new wallet. Select the device to use. If
the device is uninitialized, go through the intialization
process.'''
devmgr = self.device_manager()
device_id = device_info.device.id_
client = devmgr.client_by_id(device_id)
# fixme: we should use: client.handler = wizard
client.handler = self.create_handler(wizard)
if not device_info.initialized:
self.initialize_device(device_id, wizard, client.handler)
client.get_xpub('m', 'standard')
client.used()
def get_xpub(self, device_id, derivation, xtype, wizard):
devmgr = self.device_manager()
client = devmgr.client_by_id(device_id)
client.handler = wizard
xpub = client.get_xpub(derivation, xtype)
client.used()
return xpub
def sign_transaction(self, keystore, tx, prev_tx, xpub_path):
self.prev_tx = prev_tx
self.xpub_path = xpub_path
client = self.get_client(keystore)
inputs = self.tx_inputs(tx, True)
outputs = self.tx_outputs(keystore.get_derivation(), tx)
signed_tx = client.sign_tx(self.get_coin_name(), inputs, outputs, lock_time=tx.locktime)[1]
raw = bh2u(signed_tx)
tx.update_signatures(raw)
def show_address(self, wallet, address):
client = self.get_client(wallet.keystore)
change, index = wallet.get_address_index(address)
derivation = wallet.keystore.derivation
address_path = "%s/%d/%d"%(derivation, change, index)
address_n = client.expand_path(address_path)
script_type = self.types.SPENDADDRESS
client.get_address(self.get_display_coin_name(), address_n,
True, script_type=script_type)
def tx_inputs(self, tx, for_sig=False):
inputs = []
for txin in tx.inputs():
txinputtype = self.types.TxInputType()
if txin['type'] == 'coinbase':
prev_hash = "\0"*32
prev_index = 0xffffffff # signed int -1
else:
if for_sig:
x_pubkeys = txin['x_pubkeys']
if len(x_pubkeys) == 1:
x_pubkey = x_pubkeys[0]
xpub, s = parse_xpubkey(x_pubkey)
xpub_n = self.client_class.expand_path(self.xpub_path[xpub])
txinputtype.address_n.extend(xpub_n + s)
txinputtype.script_type = self.types.SPENDADDRESS
else:
def f(x_pubkey):
if is_xpubkey(x_pubkey):
xpub, s = parse_xpubkey(x_pubkey)
else:
xpub = xpub_from_pubkey('standard', bfh(x_pubkey))
s = []
node = self.ckd_public.deserialize(xpub)
return self.types.HDNodePathType(node=node, address_n=s)
pubkeys = [f(x) for x in x_pubkeys]
multisig = self.types.MultisigRedeemScriptType(
pubkeys=pubkeys,
signatures=[bfh(x)[:-1] if x else b'' for x in txin.get('signatures')],
m=txin.get('num_sig'),
)
script_type = self.types.SPENDMULTISIG
txinputtype = self.types.TxInputType(
script_type=script_type,
multisig=multisig
)
# find which key is mine
for x_pubkey in x_pubkeys:
if is_xpubkey(x_pubkey):
xpub, s = parse_xpubkey(x_pubkey)
if xpub in self.xpub_path:
xpub_n = self.client_class.expand_path(self.xpub_path[xpub])
txinputtype.address_n.extend(xpub_n + s)
break
prev_hash = unhexlify(txin['prevout_hash'])
prev_index = txin['prevout_n']
if 'value' in txin:
txinputtype.amount = txin['value']
txinputtype.prev_hash = prev_hash
txinputtype.prev_index = prev_index
if 'scriptSig' in txin:
script_sig = bfh(txin['scriptSig'])
txinputtype.script_sig = script_sig
txinputtype.sequence = txin.get('sequence', 0xffffffff - 1)
inputs.append(txinputtype)
return inputs
def tx_outputs(self, derivation, tx):
outputs = []
has_change = False
for _type, address, amount in tx.outputs():
info = tx.output_info.get(address)
if info is not None and not has_change:
has_change = True # no more than one change address
index, xpubs, m = info
if len(xpubs) == 1:
script_type = self.types.PAYTOADDRESS
address_n = self.client_class.expand_path(derivation + "/%d/%d"%index)
txoutputtype = self.types.TxOutputType(
amount = amount,
script_type = script_type,
address_n = address_n,
)
else:
script_type = self.types.PAYTOMULTISIG
address_n = self.client_class.expand_path("/%d/%d"%index)
nodes = [self.ckd_public.deserialize(xpub) for xpub in xpubs]
pubkeys = [self.types.HDNodePathType(node=node, address_n=address_n)
for node in nodes]
multisig = self.types.MultisigRedeemScriptType(
pubkeys = pubkeys,
signatures = [b''] * len(pubkeys),
m = m)
txoutputtype = self.types.TxOutputType(
multisig = multisig,
amount = amount,
address_n = self.client_class.expand_path(derivation + "/%d/%d"%index),
script_type = script_type)
else:
txoutputtype = self.types.TxOutputType()
txoutputtype.amount = amount
if _type == TYPE_SCRIPT:
txoutputtype.script_type = self.types.PAYTOOPRETURN
txoutputtype.op_return_data = address.to_script()[2:]
elif _type == TYPE_ADDRESS:
addr_format = address.FMT_BITCOIN
txoutputtype.script_type = self.types.PAYTOADDRESS
txoutputtype.address = address.to_full_string(addr_format)
outputs.append(txoutputtype)
return outputs
def electrumsv_tx_to_txtype(self, tx):
t = self.types.TransactionType()
d = deserialize(tx.raw)
t.version = d['version']
t.lock_time = d['lockTime']
inputs = self.tx_inputs(tx)
t.inputs.extend(inputs)
for vout in d['outputs']:
o = t.bin_outputs.add()
o.amount = vout['value']
o.script_pubkey = bfh(vout['scriptPubKey'])
return t
# This function is called from the trezor libraries (via tx_api)
def get_tx(self, tx_hash):
tx = self.prev_tx[tx_hash]
return self.electrumsv_tx_to_txtype(tx)
| 42.506964 | 99 | 0.570052 | from binascii import hexlify, unhexlify
import logging
import threading
from electrumsv.util import bfh, bh2u
from electrumsv.bitcoin import (xpub_from_pubkey, TYPE_ADDRESS, TYPE_SCRIPT)
from electrumsv.i18n import _
from electrumsv.transaction import deserialize
from electrumsv.keystore import Hardware_KeyStore, is_xpubkey, parse_xpubkey
from ..hw_wallet import HW_PluginBase
TIM_NEW, TIM_RECOVER, TIM_MNEMONIC, TIM_PRIVKEY = range(0, 4)
class KeepKeyCompatibleKeyStore(Hardware_KeyStore):
def get_derivation(self):
return self.derivation
def get_client(self, force_pair=True):
return self.plugin.get_client(self, force_pair)
def decrypt_message(self, sequence, message, password):
raise RuntimeError(_('Encryption and decryption are not implemented by {}').format(
self.device))
def sign_message(self, sequence, message, password):
client = self.get_client()
address_path = self.get_derivation() + "/%d/%d"%sequence
address_n = client.expand_path(address_path)
msg_sig = client.sign_message(self.plugin.get_coin_name(), address_n, message)
return msg_sig.signature
def sign_transaction(self, tx, password):
if tx.is_complete():
return
prev_tx = {}
xpub_path = {}
for txin in tx.inputs():
pubkeys, x_pubkeys = tx.get_sorted_pubkeys(txin)
tx_hash = txin['prevout_hash']
prev_tx[tx_hash] = txin['prev_tx']
for x_pubkey in x_pubkeys:
if not is_xpubkey(x_pubkey):
continue
xpub, s = parse_xpubkey(x_pubkey)
if xpub == self.get_master_public_key():
xpub_path[xpub] = self.get_derivation()
self.plugin.sign_transaction(self, tx, prev_tx, xpub_path)
class KeepKeyCompatiblePlugin(HW_PluginBase):
MAX_LABEL_LEN = 32
def __init__(self, parent, config, name):
HW_PluginBase.__init__(self, parent, config, name)
self.logger = logging.getLogger("plugin.keepkey")
self.main_thread = threading.current_thread()
if self.libraries_available:
self.device_manager().register_devices(self.DEVICE_IDS)
def _try_hid(self, device):
self.logger.debug("Trying to connect over USB...")
if device.interface_number == 1:
pair = [None, device.path]
else:
pair = [device.path, None]
try:
return self.hid_transport(pair)
except BaseException as e:
self.logger.error("cannot connect at %s %s", device.path, e)
return None
def _try_bridge(self, device):
self.logger.debug("Trying to connect over Trezor Bridge...")
try:
return self.bridge_transport({'path': hexlify(device.path)})
except BaseException as e:
self.logger.error("cannot connect to bridge %s", e)
return None
def create_client(self, device, handler):
transport = self._try_hid(device)
if not transport:
self.logger.error("cannot connect to device")
return
self.logger.debug("connected to device at %s", device.path)
client = self.client_class(transport, handler, self)
try:
client.ping('t')
except BaseException as e:
self.logger.error("ping failed %s", e)
return None
if not client.atleast_version(*self.minimum_firmware):
msg = (_('Outdated {} firmware for device labelled {}. Please '
'download the updated firmware from {}')
.format(self.device, client.label(), self.firmware_URL))
self.logger.error(msg)
handler.show_error(msg)
return None
return client
def get_client(self, keystore, force_pair=True):
devmgr = self.device_manager()
handler = keystore.handler
with devmgr.hid_lock:
client = devmgr.client_for_keystore(self, handler, keystore, force_pair)
if client:
client.used()
return client
def initialize_device(self, device_id, wizard, handler):
msg = _("Choose how you want to initialize your {}.\n\n"
"The first two methods are secure as no secret information "
"is entered into your computer.\n\n"
"For the last two methods you input secrets on your keyboard "
"and upload them to your {}, and so you should "
"only do those on a computer you know to be trustworthy "
"and free of malware."
).format(self.device, self.device)
choices = [
(TIM_NEW, _("Let the device generate a completely new seed randomly")),
(TIM_RECOVER, _("Recover from a seed you have previously written down")),
(TIM_MNEMONIC, _("Upload a BIP39 mnemonic to generate the seed")),
(TIM_PRIVKEY, _("Upload a master private key"))
]
def f(method):
settings = self.request_trezor_init_settings(wizard, method, self.device)
t = threading.Thread(target = self._initialize_device,
args=(settings, method, device_id, wizard, handler))
t.setDaemon(True)
t.start()
wizard.loop.exec_()
wizard.choice_dialog(title=_('Initialize Device'), message=msg,
choices=choices, run_next=f)
def _initialize_device(self, settings, method, device_id, wizard, handler):
item, label, pin_protection, passphrase_protection = settings
language = 'english'
devmgr = self.device_manager()
client = devmgr.client_by_id(device_id)
if method == TIM_NEW:
strength = 64 * (item + 2) # 128, 192 or 256
client.reset_device(True, strength, passphrase_protection,
pin_protection, label, language)
elif method == TIM_RECOVER:
word_count = 6 * (item + 2) # 12, 18 or 24
client.step = 0
client.recovery_device(word_count, passphrase_protection,
pin_protection, label, language)
elif method == TIM_MNEMONIC:
pin = pin_protection # It's the pin, not a boolean
client.load_device_by_mnemonic(str(item), pin,
passphrase_protection,
label, language)
else:
pin = pin_protection
client.load_device_by_xprv(item, pin, passphrase_protection,
label, language)
wizard.loop.exit(0)
def setup_device(self, device_info, wizard):
devmgr = self.device_manager()
device_id = device_info.device.id_
client = devmgr.client_by_id(device_id)
# fixme: we should use: client.handler = wizard
client.handler = self.create_handler(wizard)
if not device_info.initialized:
self.initialize_device(device_id, wizard, client.handler)
client.get_xpub('m', 'standard')
client.used()
def get_xpub(self, device_id, derivation, xtype, wizard):
devmgr = self.device_manager()
client = devmgr.client_by_id(device_id)
client.handler = wizard
xpub = client.get_xpub(derivation, xtype)
client.used()
return xpub
def sign_transaction(self, keystore, tx, prev_tx, xpub_path):
self.prev_tx = prev_tx
self.xpub_path = xpub_path
client = self.get_client(keystore)
inputs = self.tx_inputs(tx, True)
outputs = self.tx_outputs(keystore.get_derivation(), tx)
signed_tx = client.sign_tx(self.get_coin_name(), inputs, outputs, lock_time=tx.locktime)[1]
raw = bh2u(signed_tx)
tx.update_signatures(raw)
def show_address(self, wallet, address):
client = self.get_client(wallet.keystore)
change, index = wallet.get_address_index(address)
derivation = wallet.keystore.derivation
address_path = "%s/%d/%d"%(derivation, change, index)
address_n = client.expand_path(address_path)
script_type = self.types.SPENDADDRESS
client.get_address(self.get_display_coin_name(), address_n,
True, script_type=script_type)
def tx_inputs(self, tx, for_sig=False):
inputs = []
for txin in tx.inputs():
txinputtype = self.types.TxInputType()
if txin['type'] == 'coinbase':
prev_hash = "\0"*32
prev_index = 0xffffffff # signed int -1
else:
if for_sig:
x_pubkeys = txin['x_pubkeys']
if len(x_pubkeys) == 1:
x_pubkey = x_pubkeys[0]
xpub, s = parse_xpubkey(x_pubkey)
xpub_n = self.client_class.expand_path(self.xpub_path[xpub])
txinputtype.address_n.extend(xpub_n + s)
txinputtype.script_type = self.types.SPENDADDRESS
else:
def f(x_pubkey):
if is_xpubkey(x_pubkey):
xpub, s = parse_xpubkey(x_pubkey)
else:
xpub = xpub_from_pubkey('standard', bfh(x_pubkey))
s = []
node = self.ckd_public.deserialize(xpub)
return self.types.HDNodePathType(node=node, address_n=s)
pubkeys = [f(x) for x in x_pubkeys]
multisig = self.types.MultisigRedeemScriptType(
pubkeys=pubkeys,
signatures=[bfh(x)[:-1] if x else b'' for x in txin.get('signatures')],
m=txin.get('num_sig'),
)
script_type = self.types.SPENDMULTISIG
txinputtype = self.types.TxInputType(
script_type=script_type,
multisig=multisig
)
# find which key is mine
for x_pubkey in x_pubkeys:
if is_xpubkey(x_pubkey):
xpub, s = parse_xpubkey(x_pubkey)
if xpub in self.xpub_path:
xpub_n = self.client_class.expand_path(self.xpub_path[xpub])
txinputtype.address_n.extend(xpub_n + s)
break
prev_hash = unhexlify(txin['prevout_hash'])
prev_index = txin['prevout_n']
if 'value' in txin:
txinputtype.amount = txin['value']
txinputtype.prev_hash = prev_hash
txinputtype.prev_index = prev_index
if 'scriptSig' in txin:
script_sig = bfh(txin['scriptSig'])
txinputtype.script_sig = script_sig
txinputtype.sequence = txin.get('sequence', 0xffffffff - 1)
inputs.append(txinputtype)
return inputs
def tx_outputs(self, derivation, tx):
outputs = []
has_change = False
for _type, address, amount in tx.outputs():
info = tx.output_info.get(address)
if info is not None and not has_change:
has_change = True # no more than one change address
index, xpubs, m = info
if len(xpubs) == 1:
script_type = self.types.PAYTOADDRESS
address_n = self.client_class.expand_path(derivation + "/%d/%d"%index)
txoutputtype = self.types.TxOutputType(
amount = amount,
script_type = script_type,
address_n = address_n,
)
else:
script_type = self.types.PAYTOMULTISIG
address_n = self.client_class.expand_path("/%d/%d"%index)
nodes = [self.ckd_public.deserialize(xpub) for xpub in xpubs]
pubkeys = [self.types.HDNodePathType(node=node, address_n=address_n)
for node in nodes]
multisig = self.types.MultisigRedeemScriptType(
pubkeys = pubkeys,
signatures = [b''] * len(pubkeys),
m = m)
txoutputtype = self.types.TxOutputType(
multisig = multisig,
amount = amount,
address_n = self.client_class.expand_path(derivation + "/%d/%d"%index),
script_type = script_type)
else:
txoutputtype = self.types.TxOutputType()
txoutputtype.amount = amount
if _type == TYPE_SCRIPT:
txoutputtype.script_type = self.types.PAYTOOPRETURN
txoutputtype.op_return_data = address.to_script()[2:]
elif _type == TYPE_ADDRESS:
addr_format = address.FMT_BITCOIN
txoutputtype.script_type = self.types.PAYTOADDRESS
txoutputtype.address = address.to_full_string(addr_format)
outputs.append(txoutputtype)
return outputs
def electrumsv_tx_to_txtype(self, tx):
t = self.types.TransactionType()
d = deserialize(tx.raw)
t.version = d['version']
t.lock_time = d['lockTime']
inputs = self.tx_inputs(tx)
t.inputs.extend(inputs)
for vout in d['outputs']:
o = t.bin_outputs.add()
o.amount = vout['value']
o.script_pubkey = bfh(vout['scriptPubKey'])
return t
# This function is called from the trezor libraries (via tx_api)
def get_tx(self, tx_hash):
tx = self.prev_tx[tx_hash]
return self.electrumsv_tx_to_txtype(tx)
| true | true |
f73bc3c35cf8b628e17a0d52b9fa434563da7ac3 | 1,723 | py | Python | nicos_ess/devices/sample.py | ebadkamil/nicos | 0355a970d627aae170c93292f08f95759c97f3b5 | [
"CC-BY-3.0",
"Apache-2.0",
"CC-BY-4.0"
] | 12 | 2019-11-06T15:40:36.000Z | 2022-01-01T16:23:00.000Z | nicos_ess/devices/sample.py | ebadkamil/nicos | 0355a970d627aae170c93292f08f95759c97f3b5 | [
"CC-BY-3.0",
"Apache-2.0",
"CC-BY-4.0"
] | 4 | 2019-11-08T10:18:16.000Z | 2021-01-13T13:07:29.000Z | nicos_ess/devices/sample.py | ISISComputingGroup/nicos | 94cb4d172815919481f8c6ee686f21ebb76f2068 | [
"CC-BY-3.0",
"Apache-2.0",
"CC-BY-4.0"
] | 6 | 2020-01-11T10:52:30.000Z | 2022-02-25T12:35:23.000Z | # -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Module authors:
# Matt Clarke <matt.clarke@ess.eu>
#
# *****************************************************************************
from nicos.core import Param
from nicos.devices.sample import Sample
class EssSample(Sample):
"""Device that collects the various sample properties specific to
samples at ESS.
"""
parameters = {
'sample_formula': Param('formula', type=str, settable=True,
category='sample'),
'number_of': Param('number_of', type=int, settable=True,
category='sample'),
'mass_volume': Param('mass/volume', type=str, settable=True,
category='sample'),
'density': Param('density', type=str, settable=True, category='sample'),
}
| 41.02381 | 80 | 0.617528 |
from nicos.core import Param
from nicos.devices.sample import Sample
class EssSample(Sample):
parameters = {
'sample_formula': Param('formula', type=str, settable=True,
category='sample'),
'number_of': Param('number_of', type=int, settable=True,
category='sample'),
'mass_volume': Param('mass/volume', type=str, settable=True,
category='sample'),
'density': Param('density', type=str, settable=True, category='sample'),
}
| true | true |
f73bc42bb01cf765912667e9767ac3fa3ea463af | 958 | py | Python | stubs.min/Autodesk/Revit/DB/Structure/__init___parts/FabricLocation.py | ricardyn/ironpython-stubs | 4d2b405eda3ceed186e8adca55dd97c332c6f49d | [
"MIT"
] | 1 | 2021-02-02T13:39:16.000Z | 2021-02-02T13:39:16.000Z | stubs.min/Autodesk/Revit/DB/Structure/__init___parts/FabricLocation.py | hdm-dt-fb/ironpython-stubs | 4d2b405eda3ceed186e8adca55dd97c332c6f49d | [
"MIT"
] | null | null | null | stubs.min/Autodesk/Revit/DB/Structure/__init___parts/FabricLocation.py | hdm-dt-fb/ironpython-stubs | 4d2b405eda3ceed186e8adca55dd97c332c6f49d | [
"MIT"
] | null | null | null | class FabricLocation(Enum,IComparable,IFormattable,IConvertible):
"""
Fabric location in the host
enum FabricLocation,values: BottomOrInternal (1),TopOrExternal (0)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self,*args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self,*args):
pass
def __gt__(self,*args):
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self,*args):
pass
def __lt__(self,*args):
pass
def __ne__(self,*args):
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
BottomOrInternal=None
TopOrExternal=None
value__=None
| 28.176471 | 215 | 0.670146 | class FabricLocation(Enum,IComparable,IFormattable,IConvertible):
pass
""" __format__(formattable: IFormattable,format: str) -> str """
pass
pass
def __gt__(self,*args):
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
pass
def __lt__(self,*args):
pass
def __ne__(self,*args):
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
BottomOrInternal=None
TopOrExternal=None
value__=None
| true | true |
f73bc4c189664fae6606da82f7b39a941a5cbaaf | 1,126 | py | Python | chanjet_openapi_python_sdk/response/get_token_by_permanent_code_response.py | Chanjet/chanjet-openapi-python-sdk- | a076ce11d6d1789e657b96d72bbbcff594dbb4e9 | [
"MIT"
] | 2 | 2021-08-12T05:22:56.000Z | 2021-09-08T09:03:38.000Z | chanjet_openapi_python_sdk/response/get_token_by_permanent_code_response.py | Chanjet/chanjet-openapi-python-sdk | a076ce11d6d1789e657b96d72bbbcff594dbb4e9 | [
"MIT"
] | null | null | null | chanjet_openapi_python_sdk/response/get_token_by_permanent_code_response.py | Chanjet/chanjet-openapi-python-sdk | a076ce11d6d1789e657b96d72bbbcff594dbb4e9 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# @Time : 2021/8/10 17:00
# @Author : zc
# @Desc : 使用用户永久授权码获取token返回值实体
from chanjet_openapi_python_sdk.chanjet_response import ChanjetResponse
class GetTokenByPermanentCodeResponse(ChanjetResponse):
def __init__(self, data=None):
# 错误码,200为成功,其余均为失败
self.code = ''
# 错误提示信息
self.message = ''
# 返回结果
self.result = self.Result()
if data:
self.__dict__ = data
def __str__(self):
return str(self.__dict__)
class Result:
def __init__(self):
# 访问令牌
self.access_token = ''
# 过期时间,单位s
self.expires_in = 0
# 更新令牌
self.refresh_token = ''
# 更新令牌过期时间,单位s
self.refresh_expires_in = 0
# 授权域
self.scope = ''
# 用户ID
self.user_id = ''
# 企业ID
self.org_id = ''
# 应用名
self.app_name = ''
# T+产品部分接口需要传在Cookie中的值
self.sid = ''
# 用户永久授权码
self.user_auth_permanent_code = ''
| 23.957447 | 71 | 0.498224 |
from chanjet_openapi_python_sdk.chanjet_response import ChanjetResponse
class GetTokenByPermanentCodeResponse(ChanjetResponse):
def __init__(self, data=None):
self.code = ''
self.message = ''
self.result = self.Result()
if data:
self.__dict__ = data
def __str__(self):
return str(self.__dict__)
class Result:
def __init__(self):
self.access_token = ''
self.expires_in = 0
self.refresh_token = ''
self.refresh_expires_in = 0
self.scope = ''
self.user_id = ''
self.org_id = ''
self.app_name = ''
self.sid = ''
self.user_auth_permanent_code = ''
| true | true |
f73bc4db4816d2dbd36250077c5be4d509744fdc | 1,588 | py | Python | tests/test_stack_trace.py | PostCenter/botlang | 09f59cc4f8870507fab6101aecea65b316a347e8 | [
"MIT"
] | 1 | 2020-11-27T14:41:47.000Z | 2020-11-27T14:41:47.000Z | tests/test_stack_trace.py | PostCenter/botlang | 09f59cc4f8870507fab6101aecea65b316a347e8 | [
"MIT"
] | 8 | 2019-01-03T17:33:14.000Z | 2019-07-15T21:16:30.000Z | tests/test_stack_trace.py | PostCenter/botlang | 09f59cc4f8870507fab6101aecea65b316a347e8 | [
"MIT"
] | 1 | 2019-05-01T22:13:07.000Z | 2019-05-01T22:13:07.000Z | import unittest
from botlang import BotlangSystem, BotlangErrorException
class StackTraceTestCase(unittest.TestCase):
def test_stack_trace(self):
code = """
(begin
(define f
(fun (n)
(fun (x) (n x))
)
)
(define g (f 3))
(+ (g 3) (g 2))
)
"""
try:
BotlangSystem().eval(code)
self.fail('Should not reach this')
except BotlangErrorException as e:
self.assertEqual(len(e.stack), 5)
self.assertTrue(
e.print_stack_trace().endswith('3 is not a function')
)
self.assertTrue(
'line 5' in e.print_stack_trace()
)
code = """
[define API_KEY "Yzy4kaJjPsWz7LVRB6Q86GcnJX9SvxaC"]
[define ACCESS_HEADERS
(make-dict
(list
(cons "Content-Type" "application/json")
(cons "ApiKey" API_KEY)
)
)
]
(non-existent-function 1)
"""
try:
BotlangSystem().eval(code)
except BotlangErrorException as e:
self.assertEqual(len(e.stack), 2)
def test_primitives_exception(self):
try:
BotlangSystem().eval('(+ (list 1) #f)')
self.fail('Should not reach this')
except BotlangErrorException as e:
self.assertEqual(len(e.stack), 1)
| 27.37931 | 69 | 0.460327 | import unittest
from botlang import BotlangSystem, BotlangErrorException
class StackTraceTestCase(unittest.TestCase):
def test_stack_trace(self):
code = """
(begin
(define f
(fun (n)
(fun (x) (n x))
)
)
(define g (f 3))
(+ (g 3) (g 2))
)
"""
try:
BotlangSystem().eval(code)
self.fail('Should not reach this')
except BotlangErrorException as e:
self.assertEqual(len(e.stack), 5)
self.assertTrue(
e.print_stack_trace().endswith('3 is not a function')
)
self.assertTrue(
'line 5' in e.print_stack_trace()
)
code = """
[define API_KEY "Yzy4kaJjPsWz7LVRB6Q86GcnJX9SvxaC"]
[define ACCESS_HEADERS
(make-dict
(list
(cons "Content-Type" "application/json")
(cons "ApiKey" API_KEY)
)
)
]
(non-existent-function 1)
"""
try:
BotlangSystem().eval(code)
except BotlangErrorException as e:
self.assertEqual(len(e.stack), 2)
def test_primitives_exception(self):
try:
BotlangSystem().eval('(+ (list 1) #f)')
self.fail('Should not reach this')
except BotlangErrorException as e:
self.assertEqual(len(e.stack), 1)
| true | true |
f73bc50bfe94c33ef3618b2328c15b59c71f9efa | 1,841 | py | Python | pylot/planning/messages.py | mageofboy/pylot | c3154dc24c9429b9916274894c72ef92e03c946d | [
"Apache-2.0"
] | 231 | 2019-06-05T00:22:00.000Z | 2022-03-28T06:15:00.000Z | pylot/planning/messages.py | mageofboy/pylot | c3154dc24c9429b9916274894c72ef92e03c946d | [
"Apache-2.0"
] | 108 | 2019-06-27T16:28:01.000Z | 2022-03-28T19:14:18.000Z | pylot/planning/messages.py | mageofboy/pylot | c3154dc24c9429b9916274894c72ef92e03c946d | [
"Apache-2.0"
] | 80 | 2019-06-07T01:08:13.000Z | 2022-03-28T01:44:42.000Z | import erdos
class WaypointsMessage(erdos.Message):
"""Message class to be used to send waypoints.
Optionally can also send a target speed for each waypoint.
Args:
timestamp (:py:class:`erdos.timestamp.Timestamp`): The timestamp of
the message.
waypoints (:py:class:`~pylot.planning.Waypoints`): Waypoints.
"""
def __init__(self,
timestamp: erdos.Timestamp,
waypoints,
agent_state=None):
super(WaypointsMessage, self).__init__(timestamp, None)
self.waypoints = waypoints
self.agent_state = agent_state
def __repr__(self):
return self.__str__()
def __str__(self):
return 'WaypointMessage(timestamp: {}, waypoints: {}, '\
'agent_state: {}'.format(self.timestamp, self.waypoints,
self.agent_state)
class BehaviorMessage(erdos.Message):
def __init__(self,
timestamp: erdos.Timestamp,
target_lane_id: int,
target_speed: float,
target_deadline: float,
target_leading_vehicle_id: int = None):
super(BehaviorMessage, self).__init__(timestamp, None)
self.target_lane_id = target_lane_id
self.target_speed = target_speed
self.target_deadline = target_deadline
self.target_leading_vehicle_id = target_leading_vehicle_id
def __repr__(self):
return self.__str__()
def __str__(self):
return 'BehaviorMessage(timestamp: {}, target_lane_id: {}, '\
'target_speed: {}, target_deadline: {}, '\
'target_leading_vehicle_id: {})'.format(
self.timestamp, self.target_lane_id, self.target_speed,
self.target_deadline, self.target_leading_vehicle_id)
| 34.735849 | 75 | 0.614883 | import erdos
class WaypointsMessage(erdos.Message):
def __init__(self,
timestamp: erdos.Timestamp,
waypoints,
agent_state=None):
super(WaypointsMessage, self).__init__(timestamp, None)
self.waypoints = waypoints
self.agent_state = agent_state
def __repr__(self):
return self.__str__()
def __str__(self):
return 'WaypointMessage(timestamp: {}, waypoints: {}, '\
'agent_state: {}'.format(self.timestamp, self.waypoints,
self.agent_state)
class BehaviorMessage(erdos.Message):
def __init__(self,
timestamp: erdos.Timestamp,
target_lane_id: int,
target_speed: float,
target_deadline: float,
target_leading_vehicle_id: int = None):
super(BehaviorMessage, self).__init__(timestamp, None)
self.target_lane_id = target_lane_id
self.target_speed = target_speed
self.target_deadline = target_deadline
self.target_leading_vehicle_id = target_leading_vehicle_id
def __repr__(self):
return self.__str__()
def __str__(self):
return 'BehaviorMessage(timestamp: {}, target_lane_id: {}, '\
'target_speed: {}, target_deadline: {}, '\
'target_leading_vehicle_id: {})'.format(
self.timestamp, self.target_lane_id, self.target_speed,
self.target_deadline, self.target_leading_vehicle_id)
| true | true |
f73bc58554bc45d34294bd53ef6960d1a81ec583 | 16,074 | py | Python | dev-tools/create_bwc_index.py | WuXinxinJH/elasticsearch | b3105bd316f29666d0dbbbc36630911a6505c64e | [
"Apache-2.0"
] | null | null | null | dev-tools/create_bwc_index.py | WuXinxinJH/elasticsearch | b3105bd316f29666d0dbbbc36630911a6505c64e | [
"Apache-2.0"
] | null | null | null | dev-tools/create_bwc_index.py | WuXinxinJH/elasticsearch | b3105bd316f29666d0dbbbc36630911a6505c64e | [
"Apache-2.0"
] | null | null | null | # Licensed to Elasticsearch under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch 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.
import argparse
import glob
import logging
import os
import random
import shutil
import subprocess
import sys
import tempfile
import time
DEFAULT_TRANSPORT_TCP_PORT = 9300
DEFAULT_HTTP_TCP_PORT = 9200
if sys.version_info[0] < 3:
print('%s must use python 3.x (for the ES python client)' % sys.argv[0])
from datetime import datetime
try:
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import ConnectionError
from elasticsearch.exceptions import TransportError
except ImportError as e:
print('Can\'t import elasticsearch please install `sudo pip3 install elasticsearch`')
sys.exit(1)
# sometimes returns True
def rarely():
return random.randint(0, 10) == 0
# usually returns True
def frequently():
return not rarely()
# asserts the correctness of the given hits given they are sorted asc
def assert_sort(hits):
values = [hit['sort'] for hit in hits['hits']['hits']]
assert len(values) > 0, 'expected non emtpy result'
val = min(values)
for x in values:
assert x >= val, '%s >= %s' % (x, val)
val = x
# Indexes the given number of document into the given index
# and randomly runs refresh, optimize and flush commands
def index_documents(es, index_name, type, num_docs):
logging.info('Indexing %s docs' % num_docs)
for id in range(0, num_docs):
es.index(index=index_name, doc_type=type, id=id, body={'string': str(random.randint(0, 100)),
'long_sort': random.randint(0, 100),
'double_sort' : float(random.randint(0, 100)),
'bool' : random.choice([True, False])})
if rarely():
es.indices.refresh(index=index_name)
if rarely():
es.indices.flush(index=index_name, force=frequently())
logging.info('Flushing index')
es.indices.flush(index=index_name)
def delete_by_query(es, version, index_name, doc_type):
logging.info('Deleting long_sort:[10..20] docs')
query = {'query':
{'range':
{'long_sort':
{'gte': 10,
'lte': 20}}}}
if version.startswith('0.') or version in ('1.0.0.Beta1', '1.0.0.Beta2'):
# TODO #10262: we can't write DBQ into the translog for these old versions until we fix this back-compat bug:
# #4074: these versions don't expect to see the top-level 'query' to count/delete_by_query:
query = query['query']
return
deleted_count = es.count(index=index_name, doc_type=doc_type, body=query)['count']
result = es.delete_by_query(index=index_name,
doc_type=doc_type,
body=query)
# make sure no shards failed:
assert result['_indices'][index_name]['_shards']['failed'] == 0, 'delete by query failed: %s' % result
logging.info('Deleted %d docs' % deleted_count)
def run_basic_asserts(es, index_name, type, num_docs):
count = es.count(index=index_name)['count']
assert count == num_docs, 'Expected %r but got %r documents' % (num_docs, count)
for _ in range(0, num_docs):
random_doc_id = random.randint(0, num_docs-1)
doc = es.get(index=index_name, doc_type=type, id=random_doc_id)
assert doc, 'Expected document for id %s but got %s' % (random_doc_id, doc)
assert_sort(es.search(index=index_name,
body={
'sort': [
{'double_sort': {'order': 'asc'}}
]
}))
assert_sort(es.search(index=index_name,
body={
'sort': [
{'long_sort': {'order': 'asc'}}
]
}))
def build_version(version_tuple):
return '.'.join([str(x) for x in version_tuple])
def build_tuple(version_string):
return [int(x) for x in version_string.split('.')]
def start_node(version, release_dir, data_dir, repo_dir, tcp_port=DEFAULT_TRANSPORT_TCP_PORT, http_port=DEFAULT_HTTP_TCP_PORT, cluster_name=None):
logging.info('Starting node from %s on port %s/%s, data_dir %s' % (release_dir, tcp_port, http_port, data_dir))
if cluster_name is None:
cluster_name = 'bwc_index_' + version
cmd = [
os.path.join(release_dir, 'bin/elasticsearch'),
'-Epath.data=%s' % data_dir,
'-Epath.logs=logs',
'-Ecluster.name=%s' % cluster_name,
'-Enetwork.host=localhost',
'-Etransport.tcp.port=%s' % tcp_port,
'-Ehttp.port=%s' % http_port,
'-Epath.repo=%s' % repo_dir
]
if version.startswith('0.') or version.startswith('1.0.0.Beta') :
cmd.append('-f') # version before 1.0 start in background automatically
return subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def install_plugin(version, release_dir, plugin_name):
run_plugin(version, release_dir, 'install', [plugin_name])
def remove_plugin(version, release_dir, plugin_name):
run_plugin(version, release_dir, 'remove', [plugin_name])
def run_plugin(version, release_dir, plugin_cmd, args):
cmd = [os.path.join(release_dir, 'bin/elasticsearch-plugin'), plugin_cmd] + args
subprocess.check_call(cmd)
def create_client(http_port=DEFAULT_HTTP_TCP_PORT, timeout=30):
logging.info('Waiting for node to startup')
for _ in range(0, timeout):
# TODO: ask Honza if there is a better way to do this?
try:
client = Elasticsearch([{'host': 'localhost', 'port': http_port}])
client.cluster.health(wait_for_nodes=1)
client.count() # can we actually search or do we get a 503? -- anyway retry
return client
except (ConnectionError, TransportError):
pass
time.sleep(1)
assert False, 'Timed out waiting for node for %s seconds' % timeout
def generate_index(client, version, index_name):
client.indices.delete(index=index_name, ignore=404)
logging.info('Create single shard test index')
mappings = {}
if not version.startswith('2.'):
# TODO: we need better "before/onOr/after" logic in python
# backcompat test for legacy type level analyzer settings, see #8874
mappings['analyzer_type1'] = {
'analyzer': 'standard',
'properties': {
'string_with_index_analyzer': {
'type': 'string',
'index_analyzer': 'standard'
},
}
}
# completion type was added in 0.90.3
if not version.startswith('0.20') and version not in ['0.90.0.Beta1', '0.90.0.RC1', '0.90.0.RC2', '0.90.0', '0.90.1', '0.90.2']:
mappings['analyzer_type1']['properties']['completion_with_index_analyzer'] = {
'type': 'completion',
'index_analyzer': 'standard'
}
mappings['analyzer_type2'] = {
'index_analyzer': 'standard',
'search_analyzer': 'keyword',
'search_quote_analyzer': 'english',
}
mappings['index_name_and_path'] = {
'properties': {
'parent_multi_field': {
'type': 'string',
'path': 'just_name',
'fields': {
'raw': {'type': 'string', 'index': 'not_analyzed', 'index_name': 'raw_multi_field'}
}
},
'field_with_index_name': {
'type': 'string',
'index_name': 'custom_index_name_for_field'
}
}
}
mappings['meta_fields'] = {
'_id': {
'path': 'myid'
},
'_routing': {
'path': 'myrouting'
},
'_boost': {
'null_value': 2.0
}
}
mappings['custom_formats'] = {
'properties': {
'string_with_custom_postings': {
'type': 'string',
'postings_format': 'Lucene41'
},
'long_with_custom_doc_values': {
'type': 'long',
'doc_values_format': 'Lucene42'
}
}
}
mappings['auto_boost'] = {
'_all': {
'auto_boost': True
}
}
mappings['norms'] = {
'properties': {
'string_with_norms_disabled': {
'type': 'string',
'norms': {
'enabled': False
}
},
'string_with_norms_enabled': {
'type': 'string',
'index': 'not_analyzed',
'norms': {
'enabled': True,
'loading': 'eager'
}
}
}
}
mappings['doc'] = {
'properties': {
'string': {
'type': 'string',
'boost': 4
}
}
}
settings = {
'number_of_shards': 1,
'number_of_replicas': 0,
}
if version.startswith('0.') or version.startswith('1.'):
# Same as ES default (60 seconds), but missing the units to make sure they are inserted on upgrade:
settings['gc_deletes'] = '60000',
# Same as ES default (5 GB), but missing the units to make sure they are inserted on upgrade:
settings['merge.policy.max_merged_segment'] = '5368709120'
warmers = {}
warmers['warmer1'] = {
'source': {
'query': {
'match_all': {}
}
}
}
client.indices.create(index=index_name, body={
'settings': settings,
'mappings': mappings,
'warmers': warmers
})
health = client.cluster.health(wait_for_status='green', wait_for_relocating_shards=0)
assert health['timed_out'] == False, 'cluster health timed out %s' % health
num_docs = random.randint(2000, 3000)
if version == "1.1.0":
# 1.1.0 is buggy and creates lots and lots of segments, so we create a
# lighter index for it to keep bw tests reasonable
# see https://github.com/elastic/elasticsearch/issues/5817
num_docs = int(num_docs / 10)
index_documents(client, index_name, 'doc', num_docs)
logging.info('Running basic asserts on the data added')
run_basic_asserts(client, index_name, 'doc', num_docs)
def snapshot_index(client, version, repo_dir):
# Add bogus persistent settings to make sure they can be restored
client.cluster.put_settings(body={
'persistent': {
'cluster.routing.allocation.exclude.version_attr': version,
# Same as ES default (30 seconds), but missing the units to make sure they are inserted on upgrade:
'discovery.zen.publish_timeout': '30000',
# Same as ES default (512 KB), but missing the units to make sure they are inserted on upgrade:
'indices.recovery.file_chunk_size': '524288',
}
})
client.indices.put_template(name='template_' + version.lower(), order=0, body={
"template": "te*",
"settings": {
"number_of_shards" : 1
},
"mappings": {
"type1": {
"_source": { "enabled" : False }
}
},
"aliases": {
"alias1": {},
"alias2": {
"filter": {
"term": {"version" : version }
},
"routing": "kimchy"
},
"{index}-alias": {}
}
})
client.snapshot.create_repository(repository='test_repo', body={
'type': 'fs',
'settings': {
'location': repo_dir
}
})
client.snapshot.create(repository='test_repo', snapshot='test_1', wait_for_completion=True)
client.snapshot.delete_repository(repository='test_repo')
def compress_index(version, tmp_dir, output_dir):
compress(tmp_dir, output_dir, 'index-%s.zip' % version, 'data')
def compress_repo(version, tmp_dir, output_dir):
compress(tmp_dir, output_dir, 'repo-%s.zip' % version, 'repo')
def compress(tmp_dir, output_dir, zipfile, directory):
abs_output_dir = os.path.abspath(output_dir)
zipfile = os.path.join(abs_output_dir, zipfile)
if os.path.exists(zipfile):
os.remove(zipfile)
logging.info('Compressing index into %s, tmpDir %s', zipfile, tmp_dir)
olddir = os.getcwd()
os.chdir(tmp_dir)
subprocess.check_call('zip -r %s %s' % (zipfile, directory), shell=True)
os.chdir(olddir)
def parse_config():
parser = argparse.ArgumentParser(description='Builds an elasticsearch index for backwards compatibility tests')
required = parser.add_mutually_exclusive_group(required=True)
required.add_argument('versions', metavar='X.Y.Z', nargs='*', default=[],
help='The elasticsearch version to build an index for')
required.add_argument('--all', action='store_true', default=False,
help='Recreate all existing backwards compatibility indexes')
parser.add_argument('--releases-dir', '-d', default='backwards', metavar='DIR',
help='The directory containing elasticsearch releases')
parser.add_argument('--output-dir', '-o', default='core/src/test/resources/indices/bwc',
help='The directory to write the zipped index into')
parser.add_argument('--tcp-port', default=DEFAULT_TRANSPORT_TCP_PORT, type=int,
help='The port to use as the minimum port for TCP communication')
parser.add_argument('--http-port', default=DEFAULT_HTTP_TCP_PORT, type=int,
help='The port to use as the minimum port for HTTP communication')
cfg = parser.parse_args()
if not os.path.exists(cfg.output_dir):
parser.error('Output directory does not exist: %s' % cfg.output_dir)
if not cfg.versions:
# --all
for bwc_index in glob.glob(os.path.join(cfg.output_dir, 'index-*.zip')):
version = os.path.basename(bwc_index)[len('index-'):-len('.zip')]
cfg.versions.append(version)
return cfg
def create_bwc_index(cfg, version):
logging.info('--> Creating bwc index for %s' % version)
release_dir = os.path.join(cfg.releases_dir, 'elasticsearch-%s' % version)
if not os.path.exists(release_dir):
raise RuntimeError('ES version %s does not exist in %s' % (version, cfg.releases_dir))
snapshot_supported = not (version.startswith('0.') or version == '1.0.0.Beta1')
tmp_dir = tempfile.mkdtemp()
data_dir = os.path.join(tmp_dir, 'data')
repo_dir = os.path.join(tmp_dir, 'repo')
logging.info('Temp data dir: %s' % data_dir)
logging.info('Temp repo dir: %s' % repo_dir)
node = None
try:
node = start_node(version, release_dir, data_dir, repo_dir, cfg.tcp_port, cfg.http_port)
client = create_client(cfg.http_port)
index_name = 'index-%s' % version.lower()
generate_index(client, version, index_name)
if snapshot_supported:
snapshot_index(client, version, repo_dir)
# 10067: get a delete-by-query into the translog on upgrade. We must do
# this after the snapshot, because it calls flush. Otherwise the index
# will already have the deletions applied on upgrade.
if version.startswith('0.') or version.startswith('1.'):
delete_by_query(client, version, index_name, 'doc')
shutdown_node(node)
node = None
compress_index(version, tmp_dir, cfg.output_dir)
if snapshot_supported:
compress_repo(version, tmp_dir, cfg.output_dir)
finally:
if node is not None:
# This only happens if we've hit an exception:
shutdown_node(node)
shutil.rmtree(tmp_dir)
def shutdown_node(node):
logging.info('Shutting down node with pid %d', node.pid)
node.terminate()
node.wait()
def main():
logging.basicConfig(format='[%(levelname)s] [%(asctime)s] %(message)s', level=logging.INFO,
datefmt='%Y-%m-%d %I:%M:%S %p')
logging.getLogger('elasticsearch').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.WARN)
cfg = parse_config()
for version in cfg.versions:
create_bwc_index(cfg, version)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('Caught keyboard interrupt, exiting...')
| 34.642241 | 146 | 0.642466 |
import argparse
import glob
import logging
import os
import random
import shutil
import subprocess
import sys
import tempfile
import time
DEFAULT_TRANSPORT_TCP_PORT = 9300
DEFAULT_HTTP_TCP_PORT = 9200
if sys.version_info[0] < 3:
print('%s must use python 3.x (for the ES python client)' % sys.argv[0])
from datetime import datetime
try:
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import ConnectionError
from elasticsearch.exceptions import TransportError
except ImportError as e:
print('Can\'t import elasticsearch please install `sudo pip3 install elasticsearch`')
sys.exit(1)
# sometimes returns True
def rarely():
return random.randint(0, 10) == 0
# usually returns True
def frequently():
return not rarely()
# asserts the correctness of the given hits given they are sorted asc
def assert_sort(hits):
values = [hit['sort'] for hit in hits['hits']['hits']]
assert len(values) > 0, 'expected non emtpy result'
val = min(values)
for x in values:
assert x >= val, '%s >= %s' % (x, val)
val = x
# Indexes the given number of document into the given index
# and randomly runs refresh, optimize and flush commands
def index_documents(es, index_name, type, num_docs):
logging.info('Indexing %s docs' % num_docs)
for id in range(0, num_docs):
es.index(index=index_name, doc_type=type, id=id, body={'string': str(random.randint(0, 100)),
'long_sort': random.randint(0, 100),
'double_sort' : float(random.randint(0, 100)),
'bool' : random.choice([True, False])})
if rarely():
es.indices.refresh(index=index_name)
if rarely():
es.indices.flush(index=index_name, force=frequently())
logging.info('Flushing index')
es.indices.flush(index=index_name)
def delete_by_query(es, version, index_name, doc_type):
logging.info('Deleting long_sort:[10..20] docs')
query = {'query':
{'range':
{'long_sort':
{'gte': 10,
'lte': 20}}}}
if version.startswith('0.') or version in ('1.0.0.Beta1', '1.0.0.Beta2'):
# TODO #10262: we can't write DBQ into the translog for these old versions until we fix this back-compat bug:
type=doc_type, body=query)['count']
result = es.delete_by_query(index=index_name,
doc_type=doc_type,
body=query)
# make sure no shards failed:
assert result['_indices'][index_name]['_shards']['failed'] == 0, 'delete by query failed: %s' % result
logging.info('Deleted %d docs' % deleted_count)
def run_basic_asserts(es, index_name, type, num_docs):
count = es.count(index=index_name)['count']
assert count == num_docs, 'Expected %r but got %r documents' % (num_docs, count)
for _ in range(0, num_docs):
random_doc_id = random.randint(0, num_docs-1)
doc = es.get(index=index_name, doc_type=type, id=random_doc_id)
assert doc, 'Expected document for id %s but got %s' % (random_doc_id, doc)
assert_sort(es.search(index=index_name,
body={
'sort': [
{'double_sort': {'order': 'asc'}}
]
}))
assert_sort(es.search(index=index_name,
body={
'sort': [
{'long_sort': {'order': 'asc'}}
]
}))
def build_version(version_tuple):
return '.'.join([str(x) for x in version_tuple])
def build_tuple(version_string):
return [int(x) for x in version_string.split('.')]
def start_node(version, release_dir, data_dir, repo_dir, tcp_port=DEFAULT_TRANSPORT_TCP_PORT, http_port=DEFAULT_HTTP_TCP_PORT, cluster_name=None):
logging.info('Starting node from %s on port %s/%s, data_dir %s' % (release_dir, tcp_port, http_port, data_dir))
if cluster_name is None:
cluster_name = 'bwc_index_' + version
cmd = [
os.path.join(release_dir, 'bin/elasticsearch'),
'-Epath.data=%s' % data_dir,
'-Epath.logs=logs',
'-Ecluster.name=%s' % cluster_name,
'-Enetwork.host=localhost',
'-Etransport.tcp.port=%s' % tcp_port,
'-Ehttp.port=%s' % http_port,
'-Epath.repo=%s' % repo_dir
]
if version.startswith('0.') or version.startswith('1.0.0.Beta') :
cmd.append('-f') # version before 1.0 start in background automatically
return subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def install_plugin(version, release_dir, plugin_name):
run_plugin(version, release_dir, 'install', [plugin_name])
def remove_plugin(version, release_dir, plugin_name):
run_plugin(version, release_dir, 'remove', [plugin_name])
def run_plugin(version, release_dir, plugin_cmd, args):
cmd = [os.path.join(release_dir, 'bin/elasticsearch-plugin'), plugin_cmd] + args
subprocess.check_call(cmd)
def create_client(http_port=DEFAULT_HTTP_TCP_PORT, timeout=30):
logging.info('Waiting for node to startup')
for _ in range(0, timeout):
# TODO: ask Honza if there is a better way to do this?
try:
client = Elasticsearch([{'host': 'localhost', 'port': http_port}])
client.cluster.health(wait_for_nodes=1)
client.count() # can we actually search or do we get a 503? -- anyway retry
return client
except (ConnectionError, TransportError):
pass
time.sleep(1)
assert False, 'Timed out waiting for node for %s seconds' % timeout
def generate_index(client, version, index_name):
client.indices.delete(index=index_name, ignore=404)
logging.info('Create single shard test index')
mappings = {}
if not version.startswith('2.'):
# TODO: we need better "before/onOr/after" logic in python
# backcompat test for legacy type level analyzer settings, see #8874
mappings['analyzer_type1'] = {
'analyzer': 'standard',
'properties': {
'string_with_index_analyzer': {
'type': 'string',
'index_analyzer': 'standard'
},
}
}
# completion type was added in 0.90.3
if not version.startswith('0.20') and version not in ['0.90.0.Beta1', '0.90.0.RC1', '0.90.0.RC2', '0.90.0', '0.90.1', '0.90.2']:
mappings['analyzer_type1']['properties']['completion_with_index_analyzer'] = {
'type': 'completion',
'index_analyzer': 'standard'
}
mappings['analyzer_type2'] = {
'index_analyzer': 'standard',
'search_analyzer': 'keyword',
'search_quote_analyzer': 'english',
}
mappings['index_name_and_path'] = {
'properties': {
'parent_multi_field': {
'type': 'string',
'path': 'just_name',
'fields': {
'raw': {'type': 'string', 'index': 'not_analyzed', 'index_name': 'raw_multi_field'}
}
},
'field_with_index_name': {
'type': 'string',
'index_name': 'custom_index_name_for_field'
}
}
}
mappings['meta_fields'] = {
'_id': {
'path': 'myid'
},
'_routing': {
'path': 'myrouting'
},
'_boost': {
'null_value': 2.0
}
}
mappings['custom_formats'] = {
'properties': {
'string_with_custom_postings': {
'type': 'string',
'postings_format': 'Lucene41'
},
'long_with_custom_doc_values': {
'type': 'long',
'doc_values_format': 'Lucene42'
}
}
}
mappings['auto_boost'] = {
'_all': {
'auto_boost': True
}
}
mappings['norms'] = {
'properties': {
'string_with_norms_disabled': {
'type': 'string',
'norms': {
'enabled': False
}
},
'string_with_norms_enabled': {
'type': 'string',
'index': 'not_analyzed',
'norms': {
'enabled': True,
'loading': 'eager'
}
}
}
}
mappings['doc'] = {
'properties': {
'string': {
'type': 'string',
'boost': 4
}
}
}
settings = {
'number_of_shards': 1,
'number_of_replicas': 0,
}
if version.startswith('0.') or version.startswith('1.'):
# Same as ES default (60 seconds), but missing the units to make sure they are inserted on upgrade:
settings['gc_deletes'] = '60000',
# Same as ES default (5 GB), but missing the units to make sure they are inserted on upgrade:
settings['merge.policy.max_merged_segment'] = '5368709120'
warmers = {}
warmers['warmer1'] = {
'source': {
'query': {
'match_all': {}
}
}
}
client.indices.create(index=index_name, body={
'settings': settings,
'mappings': mappings,
'warmers': warmers
})
health = client.cluster.health(wait_for_status='green', wait_for_relocating_shards=0)
assert health['timed_out'] == False, 'cluster health timed out %s' % health
num_docs = random.randint(2000, 3000)
if version == "1.1.0":
# 1.1.0 is buggy and creates lots and lots of segments, so we create a
# lighter index for it to keep bw tests reasonable
# see https://github.com/elastic/elasticsearch/issues/5817
num_docs = int(num_docs / 10)
index_documents(client, index_name, 'doc', num_docs)
logging.info('Running basic asserts on the data added')
run_basic_asserts(client, index_name, 'doc', num_docs)
def snapshot_index(client, version, repo_dir):
# Add bogus persistent settings to make sure they can be restored
client.cluster.put_settings(body={
'persistent': {
'cluster.routing.allocation.exclude.version_attr': version,
# Same as ES default (30 seconds), but missing the units to make sure they are inserted on upgrade:
'discovery.zen.publish_timeout': '30000',
# Same as ES default (512 KB), but missing the units to make sure they are inserted on upgrade:
'indices.recovery.file_chunk_size': '524288',
}
})
client.indices.put_template(name='template_' + version.lower(), order=0, body={
"template": "te*",
"settings": {
"number_of_shards" : 1
},
"mappings": {
"type1": {
"_source": { "enabled" : False }
}
},
"aliases": {
"alias1": {},
"alias2": {
"filter": {
"term": {"version" : version }
},
"routing": "kimchy"
},
"{index}-alias": {}
}
})
client.snapshot.create_repository(repository='test_repo', body={
'type': 'fs',
'settings': {
'location': repo_dir
}
})
client.snapshot.create(repository='test_repo', snapshot='test_1', wait_for_completion=True)
client.snapshot.delete_repository(repository='test_repo')
def compress_index(version, tmp_dir, output_dir):
compress(tmp_dir, output_dir, 'index-%s.zip' % version, 'data')
def compress_repo(version, tmp_dir, output_dir):
compress(tmp_dir, output_dir, 'repo-%s.zip' % version, 'repo')
def compress(tmp_dir, output_dir, zipfile, directory):
abs_output_dir = os.path.abspath(output_dir)
zipfile = os.path.join(abs_output_dir, zipfile)
if os.path.exists(zipfile):
os.remove(zipfile)
logging.info('Compressing index into %s, tmpDir %s', zipfile, tmp_dir)
olddir = os.getcwd()
os.chdir(tmp_dir)
subprocess.check_call('zip -r %s %s' % (zipfile, directory), shell=True)
os.chdir(olddir)
def parse_config():
parser = argparse.ArgumentParser(description='Builds an elasticsearch index for backwards compatibility tests')
required = parser.add_mutually_exclusive_group(required=True)
required.add_argument('versions', metavar='X.Y.Z', nargs='*', default=[],
help='The elasticsearch version to build an index for')
required.add_argument('--all', action='store_true', default=False,
help='Recreate all existing backwards compatibility indexes')
parser.add_argument('--releases-dir', '-d', default='backwards', metavar='DIR',
help='The directory containing elasticsearch releases')
parser.add_argument('--output-dir', '-o', default='core/src/test/resources/indices/bwc',
help='The directory to write the zipped index into')
parser.add_argument('--tcp-port', default=DEFAULT_TRANSPORT_TCP_PORT, type=int,
help='The port to use as the minimum port for TCP communication')
parser.add_argument('--http-port', default=DEFAULT_HTTP_TCP_PORT, type=int,
help='The port to use as the minimum port for HTTP communication')
cfg = parser.parse_args()
if not os.path.exists(cfg.output_dir):
parser.error('Output directory does not exist: %s' % cfg.output_dir)
if not cfg.versions:
# --all
for bwc_index in glob.glob(os.path.join(cfg.output_dir, 'index-*.zip')):
version = os.path.basename(bwc_index)[len('index-'):-len('.zip')]
cfg.versions.append(version)
return cfg
def create_bwc_index(cfg, version):
logging.info('--> Creating bwc index for %s' % version)
release_dir = os.path.join(cfg.releases_dir, 'elasticsearch-%s' % version)
if not os.path.exists(release_dir):
raise RuntimeError('ES version %s does not exist in %s' % (version, cfg.releases_dir))
snapshot_supported = not (version.startswith('0.') or version == '1.0.0.Beta1')
tmp_dir = tempfile.mkdtemp()
data_dir = os.path.join(tmp_dir, 'data')
repo_dir = os.path.join(tmp_dir, 'repo')
logging.info('Temp data dir: %s' % data_dir)
logging.info('Temp repo dir: %s' % repo_dir)
node = None
try:
node = start_node(version, release_dir, data_dir, repo_dir, cfg.tcp_port, cfg.http_port)
client = create_client(cfg.http_port)
index_name = 'index-%s' % version.lower()
generate_index(client, version, index_name)
if snapshot_supported:
snapshot_index(client, version, repo_dir)
# 10067: get a delete-by-query into the translog on upgrade. We must do
# this after the snapshot, because it calls flush. Otherwise the index
# will already have the deletions applied on upgrade.
if version.startswith('0.') or version.startswith('1.'):
delete_by_query(client, version, index_name, 'doc')
shutdown_node(node)
node = None
compress_index(version, tmp_dir, cfg.output_dir)
if snapshot_supported:
compress_repo(version, tmp_dir, cfg.output_dir)
finally:
if node is not None:
# This only happens if we've hit an exception:
shutdown_node(node)
shutil.rmtree(tmp_dir)
def shutdown_node(node):
logging.info('Shutting down node with pid %d', node.pid)
node.terminate()
node.wait()
def main():
logging.basicConfig(format='[%(levelname)s] [%(asctime)s] %(message)s', level=logging.INFO,
datefmt='%Y-%m-%d %I:%M:%S %p')
logging.getLogger('elasticsearch').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.WARN)
cfg = parse_config()
for version in cfg.versions:
create_bwc_index(cfg, version)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('Caught keyboard interrupt, exiting...')
| true | true |
f73bc6614746699add4f9c6f4cb2086b981052b2 | 5,614 | py | Python | tools/nntool/generation/naming_convension.py | VishalSharma0309/gap_sdk | 09ccc594a3696a84953b732022cecae11e751c97 | [
"Apache-2.0"
] | null | null | null | tools/nntool/generation/naming_convension.py | VishalSharma0309/gap_sdk | 09ccc594a3696a84953b732022cecae11e751c97 | [
"Apache-2.0"
] | null | null | null | tools/nntool/generation/naming_convension.py | VishalSharma0309/gap_sdk | 09ccc594a3696a84953b732022cecae11e751c97 | [
"Apache-2.0"
] | null | null | null | # Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from abc import ABC, abstractmethod
from graph.types import (ConcatParameters, Conv2DParameters, FcParameters,
SoftMaxParameters, ConvFusionParameters, PoolingParameters,
ActivationParameters, MatrixAddParameters, ActivationFusion,
MatrixMulParameters, GlobalPoolParameters)
class NamingConvension(ABC):
def __init__(self, G):
self.G = G
@abstractmethod
def get_node_name(self, node_name, step_idx, params):
pass
@abstractmethod
def get_edge_name(self, node_name, step_idx, edge_type, edge_order=None):
pass
@abstractmethod
def get_global_name(self, name, step_idx, params, gtype):
pass
@abstractmethod
def get_project_name(self):
pass
class DefaultNamingConvension(NamingConvension):
def get_project_name(self):
return self.G.name
def get_global_name(self, name, step_idx, params, gtype):
return "S{}_{}".format(step_idx, gtype.capitalize())
# pylint: disable=too-many-return-statements
def get_node_name(self, node_name, step_idx, params):
if isinstance(params, ConcatParameters):
return "S{}_Concat".format(step_idx)
if isinstance(params, Conv2DParameters):
return "S{}_Conv2d_{}".format(step_idx, str(params.filter))
if isinstance(params, FcParameters):
return "S{}_Linear_{}".format(step_idx, str(params.filter))
if isinstance(params, SoftMaxParameters):
return "S{}_SoftMax".format(step_idx)
if isinstance(params, ConvFusionParameters):
nodes = params.contained_nodes()
if params.fusion_type == "conv_active_pool":
return "S{}_Conv2d_{}_{}Pool_{}_{}"\
.format(step_idx, nodes[0].filter,
nodes[2].pool_type.capitalize(), nodes[2].filter,
nodes[1].activation.capitalize())
if params.fusion_type == "conv_pool_active":
return "S{}_Conv2d_{}_{}Pool_{}_{}"\
.format(step_idx, nodes[0].filter,
nodes[1].pool_type.capitalize(), nodes[1].filter,
nodes[2].activation.capitalize())
if params.fusion_type == "conv_active":
return "S{}_Conv2d_{}_{}"\
.format(step_idx, nodes[0].filter,
nodes[1].activation.capitalize())
if params.fusion_type == "conv_pool":
return "S{}_Conv2d_{}_{}Pool_{}"\
.format(step_idx, nodes[0].filter,
nodes[1].pool_type.capitalize(), nodes[1].filter)
if isinstance(params, PoolingParameters):
return "S{}_{}Pool_{}".format(step_idx, params.pool_type.capitalize(), params.filter)
if isinstance(params, ActivationParameters):
return "S{}_Act_{}".format(step_idx, params.activation.capitalize())
if isinstance(params, MatrixAddParameters):
return "S{}_MatAdd_{}".format(step_idx, str(params.out_dims[0]))
if isinstance(params, MatrixMulParameters):
return "S{}_MatMul_{}".format(step_idx, str(params.out_dims[0]))
if isinstance(params, ActivationFusion):
nodes = params.contained_nodes()
if isinstance(nodes[0], MatrixAddParameters):
return "S{}_MatAdd_{}_{}".format(step_idx, str(nodes[0].out_dims[0]),
nodes[1].activation.capitalize())
if isinstance(nodes[0], (PoolingParameters)):
return "S{}_{}Pool_{}_{}".format(step_idx, nodes[0].pool_type.capitalize(),
nodes[0].filter, nodes[1].activation.capitalize())
if isinstance(nodes[0], (GlobalPoolParameters)):
return "S{}_{}Pool_{}_{}".format(step_idx, nodes[0].pool_type.capitalize(),
nodes[0].out_dims[0], nodes[1].activation.capitalize())
if isinstance(nodes[0], MatrixMulParameters):
return "S{}_MatMul_{}_{}".format(step_idx, str(nodes[0].out_dims[0]),
nodes[1].activation.capitalize())
return "S{}_Op_{}".format(step_idx, node_name)
def get_edge_name(self, node_name, step_idx, edge_type, edge_order=None, edge_params=None):
if edge_type == "in":
return node_name.capitalize()
if edge_type == "out":
if self.G.num_out_edges(node_name):
return self.G.out_edges(node_name)[0].to_node.name.capitalize()
return node_name.capitalize()
if edge_type == "in_out":
ename = "S{}_Output".format(step_idx)
return ename
assert False, "unknown edge type"
return None
| 47.576271 | 104 | 0.608479 |
from abc import ABC, abstractmethod
from graph.types import (ConcatParameters, Conv2DParameters, FcParameters,
SoftMaxParameters, ConvFusionParameters, PoolingParameters,
ActivationParameters, MatrixAddParameters, ActivationFusion,
MatrixMulParameters, GlobalPoolParameters)
class NamingConvension(ABC):
def __init__(self, G):
self.G = G
@abstractmethod
def get_node_name(self, node_name, step_idx, params):
pass
@abstractmethod
def get_edge_name(self, node_name, step_idx, edge_type, edge_order=None):
pass
@abstractmethod
def get_global_name(self, name, step_idx, params, gtype):
pass
@abstractmethod
def get_project_name(self):
pass
class DefaultNamingConvension(NamingConvension):
def get_project_name(self):
return self.G.name
def get_global_name(self, name, step_idx, params, gtype):
return "S{}_{}".format(step_idx, gtype.capitalize())
def get_node_name(self, node_name, step_idx, params):
if isinstance(params, ConcatParameters):
return "S{}_Concat".format(step_idx)
if isinstance(params, Conv2DParameters):
return "S{}_Conv2d_{}".format(step_idx, str(params.filter))
if isinstance(params, FcParameters):
return "S{}_Linear_{}".format(step_idx, str(params.filter))
if isinstance(params, SoftMaxParameters):
return "S{}_SoftMax".format(step_idx)
if isinstance(params, ConvFusionParameters):
nodes = params.contained_nodes()
if params.fusion_type == "conv_active_pool":
return "S{}_Conv2d_{}_{}Pool_{}_{}"\
.format(step_idx, nodes[0].filter,
nodes[2].pool_type.capitalize(), nodes[2].filter,
nodes[1].activation.capitalize())
if params.fusion_type == "conv_pool_active":
return "S{}_Conv2d_{}_{}Pool_{}_{}"\
.format(step_idx, nodes[0].filter,
nodes[1].pool_type.capitalize(), nodes[1].filter,
nodes[2].activation.capitalize())
if params.fusion_type == "conv_active":
return "S{}_Conv2d_{}_{}"\
.format(step_idx, nodes[0].filter,
nodes[1].activation.capitalize())
if params.fusion_type == "conv_pool":
return "S{}_Conv2d_{}_{}Pool_{}"\
.format(step_idx, nodes[0].filter,
nodes[1].pool_type.capitalize(), nodes[1].filter)
if isinstance(params, PoolingParameters):
return "S{}_{}Pool_{}".format(step_idx, params.pool_type.capitalize(), params.filter)
if isinstance(params, ActivationParameters):
return "S{}_Act_{}".format(step_idx, params.activation.capitalize())
if isinstance(params, MatrixAddParameters):
return "S{}_MatAdd_{}".format(step_idx, str(params.out_dims[0]))
if isinstance(params, MatrixMulParameters):
return "S{}_MatMul_{}".format(step_idx, str(params.out_dims[0]))
if isinstance(params, ActivationFusion):
nodes = params.contained_nodes()
if isinstance(nodes[0], MatrixAddParameters):
return "S{}_MatAdd_{}_{}".format(step_idx, str(nodes[0].out_dims[0]),
nodes[1].activation.capitalize())
if isinstance(nodes[0], (PoolingParameters)):
return "S{}_{}Pool_{}_{}".format(step_idx, nodes[0].pool_type.capitalize(),
nodes[0].filter, nodes[1].activation.capitalize())
if isinstance(nodes[0], (GlobalPoolParameters)):
return "S{}_{}Pool_{}_{}".format(step_idx, nodes[0].pool_type.capitalize(),
nodes[0].out_dims[0], nodes[1].activation.capitalize())
if isinstance(nodes[0], MatrixMulParameters):
return "S{}_MatMul_{}_{}".format(step_idx, str(nodes[0].out_dims[0]),
nodes[1].activation.capitalize())
return "S{}_Op_{}".format(step_idx, node_name)
def get_edge_name(self, node_name, step_idx, edge_type, edge_order=None, edge_params=None):
if edge_type == "in":
return node_name.capitalize()
if edge_type == "out":
if self.G.num_out_edges(node_name):
return self.G.out_edges(node_name)[0].to_node.name.capitalize()
return node_name.capitalize()
if edge_type == "in_out":
ename = "S{}_Output".format(step_idx)
return ename
assert False, "unknown edge type"
return None
| true | true |
f73bc714371e6e276e74ba36b3cb926f86c66561 | 315 | py | Python | custom_features/__init__.py | softmatterlab/DeepTrack-2.0-app | 3bc661987cba53519ebefcc0b7221994a6e2d317 | [
"MIT"
] | null | null | null | custom_features/__init__.py | softmatterlab/DeepTrack-2.0-app | 3bc661987cba53519ebefcc0b7221994a6e2d317 | [
"MIT"
] | 6 | 2020-10-27T15:50:49.000Z | 2021-10-19T14:37:47.000Z | custom_features/__init__.py | softmatterlab/DeepTrack-2.0-app | 3bc661987cba53519ebefcc0b7221994a6e2d317 | [
"MIT"
] | 3 | 2020-10-16T11:04:42.000Z | 2021-10-19T14:26:52.000Z | from os.path import dirname, basename, isfile, join, abspath
import glob
import sys
sys.path.append(abspath(join(dirname(__file__), "../python_src/")))
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]
from . import * | 39.375 | 93 | 0.71746 | from os.path import dirname, basename, isfile, join, abspath
import glob
import sys
sys.path.append(abspath(join(dirname(__file__), "../python_src/")))
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]
from . import * | true | true |
f73bc9082420d414d2f62dd154d0c60feed4bce3 | 1,948 | py | Python | tests/TestCar.py | TestowanieAutomatyczneUG/laboratorium-9-stokwiszadrian | 2bdb395bcbdcd86b30523841077705426ac0bdce | [
"MIT"
] | null | null | null | tests/TestCar.py | TestowanieAutomatyczneUG/laboratorium-9-stokwiszadrian | 2bdb395bcbdcd86b30523841077705426ac0bdce | [
"MIT"
] | null | null | null | tests/TestCar.py | TestowanieAutomatyczneUG/laboratorium-9-stokwiszadrian | 2bdb395bcbdcd86b30523841077705426ac0bdce | [
"MIT"
] | null | null | null | from src.Car import Car
from src.CarImpl import CarImpl
from unittest.mock import *
from unittest import TestCase, main
class test_Car(TestCase):
def test_needsfuel_true(self):
car = Car()
car.needsFuel = Mock(name='needsFuel')
car.needsFuel.return_value = True
carImpl = CarImpl(car)
self.assertEqual(carImpl.car_needsFuel(), "You need to refuel soon!")
def test_needsfuel_false(self):
car = Car()
car.needsFuel = Mock(name='needsFuel')
car.needsFuel.return_value = False
carImpl = CarImpl(car)
self.assertEqual(carImpl.car_needsFuel(), "No need to refuel now")
def test_getenginetemperature_toocold(self):
car = Car()
car.getEngineTemperature = Mock(name='getEngineTemperature')
car.getEngineTemperature.return_value = 60
carImpl = CarImpl(car)
self.assertEqual(carImpl.car_getEngineTemperature(), "Engine is running too cold!")
def test_getenginetemperature_toohot(self):
car = Car()
car.getEngineTemperature = Mock(name='getEngineTemperature')
car.getEngineTemperature.return_value = 120
carImpl = CarImpl(car)
self.assertEqual(carImpl.car_getEngineTemperature(), "Engine is running too hot!")
def test_getenginetemperature_optimal(self):
car = Car()
car.getEngineTemperature = Mock(name='getEngineTemperature')
car.getEngineTemperature.return_value = 85
carImpl = CarImpl(car)
self.assertEqual(carImpl.car_getEngineTemperature(), "Engine is running at an optimal temperature")
def test_driveto(self):
car = Car()
car.driveTo = Mock(name='driveTo')
destination = "Szczecin"
car.driveTo.return_value = destination
carImpl = CarImpl(car)
self.assertEqual(carImpl.car_driveTo(destination), f"The car is headed to {destination}")
if __name__ == '__main__':
main() | 36.754717 | 107 | 0.679158 | from src.Car import Car
from src.CarImpl import CarImpl
from unittest.mock import *
from unittest import TestCase, main
class test_Car(TestCase):
def test_needsfuel_true(self):
car = Car()
car.needsFuel = Mock(name='needsFuel')
car.needsFuel.return_value = True
carImpl = CarImpl(car)
self.assertEqual(carImpl.car_needsFuel(), "You need to refuel soon!")
def test_needsfuel_false(self):
car = Car()
car.needsFuel = Mock(name='needsFuel')
car.needsFuel.return_value = False
carImpl = CarImpl(car)
self.assertEqual(carImpl.car_needsFuel(), "No need to refuel now")
def test_getenginetemperature_toocold(self):
car = Car()
car.getEngineTemperature = Mock(name='getEngineTemperature')
car.getEngineTemperature.return_value = 60
carImpl = CarImpl(car)
self.assertEqual(carImpl.car_getEngineTemperature(), "Engine is running too cold!")
def test_getenginetemperature_toohot(self):
car = Car()
car.getEngineTemperature = Mock(name='getEngineTemperature')
car.getEngineTemperature.return_value = 120
carImpl = CarImpl(car)
self.assertEqual(carImpl.car_getEngineTemperature(), "Engine is running too hot!")
def test_getenginetemperature_optimal(self):
car = Car()
car.getEngineTemperature = Mock(name='getEngineTemperature')
car.getEngineTemperature.return_value = 85
carImpl = CarImpl(car)
self.assertEqual(carImpl.car_getEngineTemperature(), "Engine is running at an optimal temperature")
def test_driveto(self):
car = Car()
car.driveTo = Mock(name='driveTo')
destination = "Szczecin"
car.driveTo.return_value = destination
carImpl = CarImpl(car)
self.assertEqual(carImpl.car_driveTo(destination), f"The car is headed to {destination}")
if __name__ == '__main__':
main() | true | true |
f73bcc307906ada8eceee6a21267b925ade3c652 | 13,646 | py | Python | deeppavlov/core/layers/tf_csoftmax_attention.py | ineersa/DeepPavlov | 8200bf9a0f0b378baad4ee0eb75b59453f516004 | [
"Apache-2.0"
] | 3 | 2020-04-16T04:25:10.000Z | 2021-05-07T23:04:43.000Z | deeppavlov/core/layers/tf_csoftmax_attention.py | ineersa/DeepPavlov | 8200bf9a0f0b378baad4ee0eb75b59453f516004 | [
"Apache-2.0"
] | 12 | 2020-01-28T22:14:04.000Z | 2022-02-10T00:10:17.000Z | deeppavlov/core/layers/tf_csoftmax_attention.py | ineersa/DeepPavlov | 8200bf9a0f0b378baad4ee0eb75b59453f516004 | [
"Apache-2.0"
] | 1 | 2021-02-05T13:01:48.000Z | 2021-02-05T13:01:48.000Z | # Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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 tensorflow as tf
def csoftmax_for_slice(input):
""" It is a implementation of the constrained softmax (csoftmax) for slice.
Based on the paper:
https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy-First Taggers" (page 4)
Args:
input: A list of [input tensor, cumulative attention].
Returns:
output: A list of [csoftmax results, masks]
"""
[ten, u] = input
shape_t = ten.shape
shape_u = u.shape
ten -= tf.reduce_mean(ten)
q = tf.exp(ten)
active = tf.ones_like(u, dtype=tf.int32)
mass = tf.constant(0, dtype=tf.float32)
found = tf.constant(True, dtype=tf.bool)
def loop(q_, mask, mass_, found_):
q_list = tf.dynamic_partition(q_, mask, 2)
condition_indices = tf.dynamic_partition(tf.range(tf.shape(q_)[0]), mask, 2) # 0 element it False,
# 1 element if true
p = q_list[1] * (1.0 - mass_) / tf.reduce_sum(q_list[1])
p_new = tf.dynamic_stitch(condition_indices, [q_list[0], p])
# condition verification and mask modification
less_mask = tf.cast(tf.less(u, p_new), tf.int32) # 0 when u is bigger than p, 1 when u is less than p
condition_indices = tf.dynamic_partition(tf.range(tf.shape(p_new)[0]), less_mask,
2) # 0 when u is bigger than p, 1 when u is less than p
split_p_new = tf.dynamic_partition(p_new, less_mask, 2)
split_u = tf.dynamic_partition(u, less_mask, 2)
alpha = tf.dynamic_stitch(condition_indices, [split_p_new[0], split_u[1]])
mass_ += tf.reduce_sum(split_u[1])
mask = mask * (tf.ones_like(less_mask) - less_mask)
found_ = tf.cond(tf.equal(tf.reduce_sum(less_mask), 0),
lambda: False,
lambda: True)
alpha = tf.reshape(alpha, q_.shape)
return alpha, mask, mass_, found_
(csoft, mask_, _, _) = tf.while_loop(cond=lambda _0, _1, _2, f: f,
body=loop,
loop_vars=(q, active, mass, found))
return [csoft, mask_]
def csoftmax(tensor, inv_cumulative_att):
""" It is a implementation of the constrained softmax (csoftmax).
Based on the paper:
https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy-First Taggers"
Args:
tensor: A tensorflow tensor is score. This tensor have dimensionality [None, n_tokens]
inv_cumulative_att: A inverse cumulative attention tensor with dimensionality [None, n_tokens]
Returns:
cs: Tensor at the output with dimensionality [None, n_tokens]
"""
shape_ten = tensor.shape
shape_cum = inv_cumulative_att.shape
merge_tensor = [tensor, inv_cumulative_att]
cs, _ = tf.map_fn(csoftmax_for_slice, merge_tensor, dtype=[tf.float32, tf.float32]) # [bs, L]
return cs
def attention_gen_step(hidden_for_sketch, hidden_for_attn_alignment, sketch, key, cum_att):
""" It is a implementation one step of block of the Luong et al. attention mechanism with general score and the constrained softmax (csoftmax).
Based on the papers:
https://arxiv.org/abs/1508.04025 "Effective Approaches to Attention-based Neural Machine Translation"
https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy-First Taggers"
Args:
hidden_for_sketch: A tensorflow tensor for a sketch computing. This tensor have dimensionality [None, max_num_tokens, sketch_hidden_size]
hidden_for_attn_alignment: A tensorflow tensor is aligned for output during a performing. This tensor have dimensionality [None, max_num_tokens, hidden_size_for_attn_alignment]
sketch: A previous step sketch tensor for a sketch computing. This tensor have dimensionality [None, sketch_hidden_size]
key: A tensorflow tensor with dimensionality [None, None, key_size]
cum_att: A cumulative attention tensor with dimensionality [None, max_num_tokens]
Returns:
next_sketch: Tensor of the current step sketch with dimensionality [None, sketch_hidden_size]
att: Tensor of the current step attention with dimensionality [None, max_num_tokens]
aligned_hidden_sketch: Tensor of aligned hidden state of current step with dimensionality [None, hidden_size_for_attn_alignment]
"""
with tf.name_scope('attention_step'):
sketch_dims = hidden_for_sketch.get_shape().as_list()
batch_size = sketch_dims[0]
num_tokens = sketch_dims[1]
hidden_size = sketch_dims[2]
attn_alignment_dims = hidden_for_attn_alignment.get_shape().as_list()
attn_alignment_hidden_size = attn_alignment_dims[2]
repeated_sketch = tf.tile(tf.reshape(sketch, [-1, 1, hidden_size]), (1,num_tokens, 1))
concat_mem = tf.concat([hidden_for_sketch, repeated_sketch],-1)
concat_mem = tf.reshape(concat_mem, [-1, num_tokens, 2*hidden_size]) # dirty trick
reduce_mem = tf.layers.dense(concat_mem, hidden_size)
projected_key = tf.layers.dense(key, hidden_size)
t_key = tf.reshape(projected_key,[-1, hidden_size, 1])
score = tf.reshape(tf.matmul(reduce_mem, t_key), [-1, num_tokens])
inv_cum_att = tf.reshape(tf.ones_like(cum_att) - cum_att, [-1, num_tokens])
att = csoftmax(score, inv_cum_att)
t_reduce_mem = tf.transpose(reduce_mem, [0,2,1])
t_hidden_for_attn_alignment = tf.transpose(hidden_for_attn_alignment, [0,2,1])
r_att = tf.reshape(att, [-1, num_tokens, 1])
next_sketch = tf.squeeze(tf.matmul(t_reduce_mem,r_att),-1)
aligned_hidden_sketch = tf.squeeze(tf.matmul(t_hidden_for_attn_alignment,r_att),-1)
return next_sketch, att, aligned_hidden_sketch
def attention_gen_block(hidden_for_sketch, hidden_for_attn_alignment, key, attention_depth):
""" It is a implementation of the Luong et al. attention mechanism with general score and the constrained softmax (csoftmax).
Based on the papers:
https://arxiv.org/abs/1508.04025 "Effective Approaches to Attention-based Neural Machine Translation"
https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy-First Taggers"
Args:
hidden_for_sketch: A tensorflow tensor for a sketch computing. This tensor have dimensionality [None, max_num_tokens, sketch_hidden_size]
hidden_for_attn_alignment: A tensorflow tensor is aligned for output during a performing. This tensor have dimensionality [None, max_num_tokens, hidden_size_for_attn_alignment]
key: A tensorflow tensor with dimensionality [None, None, key_size]
attention_depth: Number of usage csoftmax
Returns:
final_aligned_hiddens: Tensor at the output with dimensionality [1, attention_depth, hidden_size_for_attn_alignment]
"""
with tf.name_scope('attention_block'):
sketch_dims = tf.shape(hidden_for_sketch)
batch_size = sketch_dims[0]
num_tokens = sketch_dims[1]
hidden_size = sketch_dims[2]
attn_alignment_dims = tf.shape(hidden_for_attn_alignment)
attn_alignment_hidden_size = attn_alignment_dims[2]
sketches = [tf.zeros(shape=[batch_size, hidden_size], dtype=tf.float32)]
aligned_hiddens = []
cum_att = tf.zeros(shape=[batch_size, num_tokens]) # cumulative attention
for i in range(attention_depth):
sketch, cum_att_, aligned_hidden = attention_gen_step(hidden_for_sketch, hidden_for_attn_alignment, sketches[-1], key, cum_att)
sketches.append(sketch) #sketch
aligned_hiddens.append(aligned_hidden) #sketch
cum_att += cum_att_
final_aligned_hiddens = tf.reshape(tf.transpose(tf.stack(aligned_hiddens), [1, 0, 2]),[1, attention_depth, attn_alignment_hidden_size])
return final_aligned_hiddens
def attention_bah_step(hidden_for_sketch, hidden_for_attn_alignment, sketch, cum_att):
""" It is a implementation one step of block of the Bahdanau et al. attention mechanism with concat score and the constrained softmax (csoftmax).
Based on the papers:
https://arxiv.org/abs/1409.0473 "Neural Machine Translation by Jointly Learning to Align and Translate"
https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy-First Taggers"
Args:
hidden_for_sketch: A tensorflow tensor for a sketch computing. This tensor have dimensionality [None, max_num_tokens, sketch_hidden_size]
hidden_for_attn_alignment: A tensorflow tensor is aligned for output during a performing. This tensor have dimensionality [None, max_num_tokens, hidden_size_for_attn_alignment]
sketch: A previous step sketch tensor for a sketch computing. This tensor have dimensionality [None, sketch_hidden_size]
key: A tensorflow tensor with dimensionality [None, None, key_size]
cum_att: A cumulative attention tensor with dimensionality [None, max_num_tokens]
Returns:
next_sketch: Tensor of the current step sketch with dimensionality [None, sketch_hidden_size]
att: Tensor of the current step attention with dimensionality [None, max_num_tokens]
aligned_hidden_sketch: Tensor of aligned hidden state of current step with dimensionality [None, hidden_size_for_attn_alignment]
"""
with tf.name_scope('attention_step'):
sketch_dims = hidden_for_sketch.get_shape().as_list()
batch_size = sketch_dims[0]
num_tokens = sketch_dims[1]
hidden_size = sketch_dims[2]
attn_alignment_dims = hidden_for_attn_alignment.get_shape().as_list()
attn_alignment_hidden_size = attn_alignment_dims[2]
repeated_sketch = tf.tile(tf.reshape(sketch, [-1, 1, hidden_size]), (1,num_tokens, 1))
concat_mem = tf.concat([hidden_for_sketch, repeated_sketch],-1)
concat_mem = tf.reshape(concat_mem, [-1, num_tokens, 2*hidden_size]) # dirty trick
reduce_mem = tf.layers.dense(concat_mem, hidden_size)
score = tf.squeeze(tf.layers.dense(reduce_mem, units = 1,
use_bias=False),-1)
inv_cum_att = tf.reshape(tf.ones_like(cum_att) - cum_att, [-1, num_tokens])
att = csoftmax(score, inv_cum_att)
t_reduce_mem = tf.transpose(reduce_mem, [0,2,1])
t_hidden_for_attn_alignment = tf.transpose(hidden_for_attn_alignment, [0,2,1])
r_att = tf.reshape(att, [-1, num_tokens, 1])
next_sketch = tf.squeeze(tf.matmul(t_reduce_mem,r_att),-1)
aligned_hidden_sketch = tf.squeeze(tf.matmul(t_hidden_for_attn_alignment,r_att),-1)
return next_sketch, att, aligned_hidden_sketch
def attention_bah_block(hidden_for_sketch, hidden_for_attn_alignment, attention_depth):
""" It is a implementation of the Bahdanau et al. attention mechanism with concat score and the constrained softmax (csoftmax).
Based on the papers:
https://arxiv.org/abs/1409.0473 "Neural Machine Translation by Jointly Learning to Align and Translate"
https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy-First Taggers"
Args:
hidden_for_sketch: A tensorflow tensor for a sketch computing. This tensor have dimensionality [None, max_num_tokens, sketch_hidden_size]
hidden_for_attn_alignment: A tensorflow tensor is aligned for output during a performing. This tensor have dimensionality [None, max_num_tokens, hidden_size_for_attn_alignment]
key: A tensorflow tensor with dimensionality [None, None, key_size]
attention_depth: Number of usage csoftmax
Returns:
final_aligned_hiddens: Tensor at the output with dimensionality [1, attention_depth, hidden_size_for_attn_alignment]
"""
with tf.name_scope('attention_block'):
sketch_dims = tf.shape(hidden_for_sketch)
batch_size = sketch_dims[0]
num_tokens = sketch_dims[1]
hidden_size = sketch_dims[2]
attn_alignment_dims = tf.shape(hidden_for_attn_alignment)
attn_alignment_hidden_size = attn_alignment_dims[2]
sketches = [tf.zeros(shape=[batch_size, hidden_size], dtype=tf.float32)]
aligned_hiddens = []
cum_att = tf.zeros(shape=[batch_size, num_tokens]) # cumulative attention
for i in range(attention_depth):
sketch, cum_att_, aligned_hidden = attention_bah_step(hidden_for_sketch, hidden_for_attn_alignment, sketches[-1], cum_att)
sketches.append(sketch) #sketch
aligned_hiddens.append(aligned_hidden) #sketch
cum_att += cum_att_
final_aligned_hiddens = tf.reshape(tf.transpose(tf.stack(aligned_hiddens), [1, 0, 2]),[1, attention_depth, attn_alignment_hidden_size])
return final_aligned_hiddens
| 53.724409 | 184 | 0.708413 |
import tensorflow as tf
def csoftmax_for_slice(input):
[ten, u] = input
shape_t = ten.shape
shape_u = u.shape
ten -= tf.reduce_mean(ten)
q = tf.exp(ten)
active = tf.ones_like(u, dtype=tf.int32)
mass = tf.constant(0, dtype=tf.float32)
found = tf.constant(True, dtype=tf.bool)
def loop(q_, mask, mass_, found_):
q_list = tf.dynamic_partition(q_, mask, 2)
condition_indices = tf.dynamic_partition(tf.range(tf.shape(q_)[0]), mask, 2)
p = q_list[1] * (1.0 - mass_) / tf.reduce_sum(q_list[1])
p_new = tf.dynamic_stitch(condition_indices, [q_list[0], p])
less_mask = tf.cast(tf.less(u, p_new), tf.int32)
condition_indices = tf.dynamic_partition(tf.range(tf.shape(p_new)[0]), less_mask,
2)
split_p_new = tf.dynamic_partition(p_new, less_mask, 2)
split_u = tf.dynamic_partition(u, less_mask, 2)
alpha = tf.dynamic_stitch(condition_indices, [split_p_new[0], split_u[1]])
mass_ += tf.reduce_sum(split_u[1])
mask = mask * (tf.ones_like(less_mask) - less_mask)
found_ = tf.cond(tf.equal(tf.reduce_sum(less_mask), 0),
lambda: False,
lambda: True)
alpha = tf.reshape(alpha, q_.shape)
return alpha, mask, mass_, found_
(csoft, mask_, _, _) = tf.while_loop(cond=lambda _0, _1, _2, f: f,
body=loop,
loop_vars=(q, active, mass, found))
return [csoft, mask_]
def csoftmax(tensor, inv_cumulative_att):
shape_ten = tensor.shape
shape_cum = inv_cumulative_att.shape
merge_tensor = [tensor, inv_cumulative_att]
cs, _ = tf.map_fn(csoftmax_for_slice, merge_tensor, dtype=[tf.float32, tf.float32])
return cs
def attention_gen_step(hidden_for_sketch, hidden_for_attn_alignment, sketch, key, cum_att):
with tf.name_scope('attention_step'):
sketch_dims = hidden_for_sketch.get_shape().as_list()
batch_size = sketch_dims[0]
num_tokens = sketch_dims[1]
hidden_size = sketch_dims[2]
attn_alignment_dims = hidden_for_attn_alignment.get_shape().as_list()
attn_alignment_hidden_size = attn_alignment_dims[2]
repeated_sketch = tf.tile(tf.reshape(sketch, [-1, 1, hidden_size]), (1,num_tokens, 1))
concat_mem = tf.concat([hidden_for_sketch, repeated_sketch],-1)
concat_mem = tf.reshape(concat_mem, [-1, num_tokens, 2*hidden_size])
reduce_mem = tf.layers.dense(concat_mem, hidden_size)
projected_key = tf.layers.dense(key, hidden_size)
t_key = tf.reshape(projected_key,[-1, hidden_size, 1])
score = tf.reshape(tf.matmul(reduce_mem, t_key), [-1, num_tokens])
inv_cum_att = tf.reshape(tf.ones_like(cum_att) - cum_att, [-1, num_tokens])
att = csoftmax(score, inv_cum_att)
t_reduce_mem = tf.transpose(reduce_mem, [0,2,1])
t_hidden_for_attn_alignment = tf.transpose(hidden_for_attn_alignment, [0,2,1])
r_att = tf.reshape(att, [-1, num_tokens, 1])
next_sketch = tf.squeeze(tf.matmul(t_reduce_mem,r_att),-1)
aligned_hidden_sketch = tf.squeeze(tf.matmul(t_hidden_for_attn_alignment,r_att),-1)
return next_sketch, att, aligned_hidden_sketch
def attention_gen_block(hidden_for_sketch, hidden_for_attn_alignment, key, attention_depth):
with tf.name_scope('attention_block'):
sketch_dims = tf.shape(hidden_for_sketch)
batch_size = sketch_dims[0]
num_tokens = sketch_dims[1]
hidden_size = sketch_dims[2]
attn_alignment_dims = tf.shape(hidden_for_attn_alignment)
attn_alignment_hidden_size = attn_alignment_dims[2]
sketches = [tf.zeros(shape=[batch_size, hidden_size], dtype=tf.float32)]
aligned_hiddens = []
cum_att = tf.zeros(shape=[batch_size, num_tokens])
for i in range(attention_depth):
sketch, cum_att_, aligned_hidden = attention_gen_step(hidden_for_sketch, hidden_for_attn_alignment, sketches[-1], key, cum_att)
sketches.append(sketch)
aligned_hiddens.append(aligned_hidden)
cum_att += cum_att_
final_aligned_hiddens = tf.reshape(tf.transpose(tf.stack(aligned_hiddens), [1, 0, 2]),[1, attention_depth, attn_alignment_hidden_size])
return final_aligned_hiddens
def attention_bah_step(hidden_for_sketch, hidden_for_attn_alignment, sketch, cum_att):
with tf.name_scope('attention_step'):
sketch_dims = hidden_for_sketch.get_shape().as_list()
batch_size = sketch_dims[0]
num_tokens = sketch_dims[1]
hidden_size = sketch_dims[2]
attn_alignment_dims = hidden_for_attn_alignment.get_shape().as_list()
attn_alignment_hidden_size = attn_alignment_dims[2]
repeated_sketch = tf.tile(tf.reshape(sketch, [-1, 1, hidden_size]), (1,num_tokens, 1))
concat_mem = tf.concat([hidden_for_sketch, repeated_sketch],-1)
concat_mem = tf.reshape(concat_mem, [-1, num_tokens, 2*hidden_size])
reduce_mem = tf.layers.dense(concat_mem, hidden_size)
score = tf.squeeze(tf.layers.dense(reduce_mem, units = 1,
use_bias=False),-1)
inv_cum_att = tf.reshape(tf.ones_like(cum_att) - cum_att, [-1, num_tokens])
att = csoftmax(score, inv_cum_att)
t_reduce_mem = tf.transpose(reduce_mem, [0,2,1])
t_hidden_for_attn_alignment = tf.transpose(hidden_for_attn_alignment, [0,2,1])
r_att = tf.reshape(att, [-1, num_tokens, 1])
next_sketch = tf.squeeze(tf.matmul(t_reduce_mem,r_att),-1)
aligned_hidden_sketch = tf.squeeze(tf.matmul(t_hidden_for_attn_alignment,r_att),-1)
return next_sketch, att, aligned_hidden_sketch
def attention_bah_block(hidden_for_sketch, hidden_for_attn_alignment, attention_depth):
with tf.name_scope('attention_block'):
sketch_dims = tf.shape(hidden_for_sketch)
batch_size = sketch_dims[0]
num_tokens = sketch_dims[1]
hidden_size = sketch_dims[2]
attn_alignment_dims = tf.shape(hidden_for_attn_alignment)
attn_alignment_hidden_size = attn_alignment_dims[2]
sketches = [tf.zeros(shape=[batch_size, hidden_size], dtype=tf.float32)]
aligned_hiddens = []
cum_att = tf.zeros(shape=[batch_size, num_tokens])
for i in range(attention_depth):
sketch, cum_att_, aligned_hidden = attention_bah_step(hidden_for_sketch, hidden_for_attn_alignment, sketches[-1], cum_att)
sketches.append(sketch)
aligned_hiddens.append(aligned_hidden)
cum_att += cum_att_
final_aligned_hiddens = tf.reshape(tf.transpose(tf.stack(aligned_hiddens), [1, 0, 2]),[1, attention_depth, attn_alignment_hidden_size])
return final_aligned_hiddens
| true | true |
f73bcc8c71ca0e10ea57d961a9ac78839381bf3c | 6,431 | py | Python | tests/test_numeric_switchedsystem.py | ralfgerlich/simupy | 7716c95ab51b63483278208230758dfdcd1a2b51 | [
"BSD-2-Clause"
] | 436 | 2017-08-30T06:55:26.000Z | 2022-03-18T04:08:00.000Z | tests/test_numeric_switchedsystem.py | ralfgerlich/simupy | 7716c95ab51b63483278208230758dfdcd1a2b51 | [
"BSD-2-Clause"
] | 25 | 2017-09-07T15:42:11.000Z | 2022-03-24T15:57:34.000Z | tests/test_numeric_switchedsystem.py | ralfgerlich/simupy | 7716c95ab51b63483278208230758dfdcd1a2b51 | [
"BSD-2-Clause"
] | 60 | 2017-09-07T14:17:07.000Z | 2022-02-10T05:44:27.000Z | import pytest
import numpy as np
import numpy.testing as npt
from simupy.systems import (SwitchedSystem, need_state_equation_function_msg,
need_output_equation_function_msg,
zero_dim_output_msg, full_state_output)
max_n_condition = 4
bounds_min = -1
bounds_max = 1
def state_equation_function(t, x, u):
return np.ones(x.shape)
def output_equation_function(t, u):
return np.ones(u.shape)
def event_variable_equation_function(t, x):
return x
@pytest.fixture(scope="module", params=np.arange(2, max_n_condition))
def switch_fixture(request):
yield (((bounds_max - bounds_min)*np.sort(np.random.rand(request.param-1))
+ bounds_min),
np.array([lambda t, x, u: cnd*np.ones(x.shape)
for cnd in range(request.param)]),
np.array([lambda t, u: cnd*np.ones(u.shape)
for cnd in range(request.param)])
)
def test_dim_output_0(switch_fixture):
with pytest.raises(ValueError, match=zero_dim_output_msg):
SwitchedSystem(
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
output_equations_functions=switch_fixture[2]
)
SwitchedSystem(
dim_output=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
output_equations_functions=switch_fixture[2],
)
def test_state_equations_functions_kwarg(switch_fixture):
with pytest.raises(ValueError, match=need_state_equation_function_msg):
SwitchedSystem(
dim_state=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
output_equations_functions=switch_fixture[2]
)
with pytest.raises(ValueError, match="broadcast"):
SwitchedSystem(
dim_state=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=np.array([
lambda t, x, u: cnd*np.ones(x.shape)
for cnd in range(switch_fixture[0].size+2)
]),
output_equations_functions=switch_fixture[2]
)
sys = SwitchedSystem(
dim_state=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=switch_fixture[1],
output_equations_functions=switch_fixture[2]
)
npt.assert_array_equal(sys.state_equations_functions, switch_fixture[1])
sys = SwitchedSystem(
dim_state=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=state_equation_function,
output_equations_functions=switch_fixture[2]
)
npt.assert_array_equal(
sys.state_equations_functions,
state_equation_function
)
def test_output_equations_functions_kwarg(switch_fixture):
with pytest.raises(ValueError, match=need_output_equation_function_msg):
SwitchedSystem(
dim_output=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
)
with pytest.raises(ValueError, match="broadcast"):
SwitchedSystem(
dim_output=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
output_equations_functions=np.array([
lambda t, u: cnd*np.ones(u.shape)
for cnd in range(switch_fixture[0].size+2)
]),
)
sys = SwitchedSystem(
dim_state=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=switch_fixture[1],
)
npt.assert_array_equal(
sys.output_equations_functions,
full_state_output
)
sys = SwitchedSystem(
dim_output=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
output_equations_functions=switch_fixture[2]
)
npt.assert_array_equal(sys.output_equations_functions, switch_fixture[2])
sys = SwitchedSystem(
dim_output=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
output_equations_functions=output_equation_function
)
npt.assert_array_equal(
sys.output_equations_functions,
output_equation_function
)
def test_event_equation_function(switch_fixture):
sys = SwitchedSystem(
dim_output=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=switch_fixture[1],
output_equations_functions=switch_fixture[2],
)
assert sys.state_update_equation_function == full_state_output
for x in np.linspace(bounds_min, bounds_max):
if not np.any(np.isclose(x, switch_fixture[0])):
assert ~np.any(np.isclose(
sys.event_equation_function(x, x),
0
))
for zero in switch_fixture[0]:
npt.assert_allclose(
sys.event_equation_function(len(switch_fixture[0]), zero),
0
)
def test_update_equation_function(switch_fixture):
sys = SwitchedSystem(
dim_output=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=switch_fixture[1],
output_equations_functions=switch_fixture[2],
)
assert not hasattr(sys, 'condition_idx')
sys.prepare_to_integrate()
assert sys.condition_idx is None
sys.update_equation_function(np.random.rand(1), bounds_min)
assert sys.condition_idx == 0
for cnd_idx, zero in enumerate(switch_fixture[0]):
sys.update_equation_function(np.random.rand(1), zero)
assert sys.condition_idx == cnd_idx+1
if len(switch_fixture[0]) > 1:
with pytest.warns(UserWarning):
sys.update_equation_function(np.random.rand(1), bounds_min)
| 34.390374 | 78 | 0.684497 | import pytest
import numpy as np
import numpy.testing as npt
from simupy.systems import (SwitchedSystem, need_state_equation_function_msg,
need_output_equation_function_msg,
zero_dim_output_msg, full_state_output)
max_n_condition = 4
bounds_min = -1
bounds_max = 1
def state_equation_function(t, x, u):
return np.ones(x.shape)
def output_equation_function(t, u):
return np.ones(u.shape)
def event_variable_equation_function(t, x):
return x
@pytest.fixture(scope="module", params=np.arange(2, max_n_condition))
def switch_fixture(request):
yield (((bounds_max - bounds_min)*np.sort(np.random.rand(request.param-1))
+ bounds_min),
np.array([lambda t, x, u: cnd*np.ones(x.shape)
for cnd in range(request.param)]),
np.array([lambda t, u: cnd*np.ones(u.shape)
for cnd in range(request.param)])
)
def test_dim_output_0(switch_fixture):
with pytest.raises(ValueError, match=zero_dim_output_msg):
SwitchedSystem(
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
output_equations_functions=switch_fixture[2]
)
SwitchedSystem(
dim_output=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
output_equations_functions=switch_fixture[2],
)
def test_state_equations_functions_kwarg(switch_fixture):
with pytest.raises(ValueError, match=need_state_equation_function_msg):
SwitchedSystem(
dim_state=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
output_equations_functions=switch_fixture[2]
)
with pytest.raises(ValueError, match="broadcast"):
SwitchedSystem(
dim_state=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=np.array([
lambda t, x, u: cnd*np.ones(x.shape)
for cnd in range(switch_fixture[0].size+2)
]),
output_equations_functions=switch_fixture[2]
)
sys = SwitchedSystem(
dim_state=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=switch_fixture[1],
output_equations_functions=switch_fixture[2]
)
npt.assert_array_equal(sys.state_equations_functions, switch_fixture[1])
sys = SwitchedSystem(
dim_state=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=state_equation_function,
output_equations_functions=switch_fixture[2]
)
npt.assert_array_equal(
sys.state_equations_functions,
state_equation_function
)
def test_output_equations_functions_kwarg(switch_fixture):
with pytest.raises(ValueError, match=need_output_equation_function_msg):
SwitchedSystem(
dim_output=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
)
with pytest.raises(ValueError, match="broadcast"):
SwitchedSystem(
dim_output=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
output_equations_functions=np.array([
lambda t, u: cnd*np.ones(u.shape)
for cnd in range(switch_fixture[0].size+2)
]),
)
sys = SwitchedSystem(
dim_state=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=switch_fixture[1],
)
npt.assert_array_equal(
sys.output_equations_functions,
full_state_output
)
sys = SwitchedSystem(
dim_output=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
output_equations_functions=switch_fixture[2]
)
npt.assert_array_equal(sys.output_equations_functions, switch_fixture[2])
sys = SwitchedSystem(
dim_output=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
output_equations_functions=output_equation_function
)
npt.assert_array_equal(
sys.output_equations_functions,
output_equation_function
)
def test_event_equation_function(switch_fixture):
sys = SwitchedSystem(
dim_output=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=switch_fixture[1],
output_equations_functions=switch_fixture[2],
)
assert sys.state_update_equation_function == full_state_output
for x in np.linspace(bounds_min, bounds_max):
if not np.any(np.isclose(x, switch_fixture[0])):
assert ~np.any(np.isclose(
sys.event_equation_function(x, x),
0
))
for zero in switch_fixture[0]:
npt.assert_allclose(
sys.event_equation_function(len(switch_fixture[0]), zero),
0
)
def test_update_equation_function(switch_fixture):
sys = SwitchedSystem(
dim_output=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=switch_fixture[1],
output_equations_functions=switch_fixture[2],
)
assert not hasattr(sys, 'condition_idx')
sys.prepare_to_integrate()
assert sys.condition_idx is None
sys.update_equation_function(np.random.rand(1), bounds_min)
assert sys.condition_idx == 0
for cnd_idx, zero in enumerate(switch_fixture[0]):
sys.update_equation_function(np.random.rand(1), zero)
assert sys.condition_idx == cnd_idx+1
if len(switch_fixture[0]) > 1:
with pytest.warns(UserWarning):
sys.update_equation_function(np.random.rand(1), bounds_min)
| true | true |
f73bcce97ee70082397ca731afbe74c12863cdc9 | 5,318 | py | Python | examples/niscope/fetch.py | vvacharya/grpc-device | 22326f69b83d774457c0f5409b71ce7fc66002f6 | [
"MIT"
] | null | null | null | examples/niscope/fetch.py | vvacharya/grpc-device | 22326f69b83d774457c0f5409b71ce7fc66002f6 | [
"MIT"
] | null | null | null | examples/niscope/fetch.py | vvacharya/grpc-device | 22326f69b83d774457c0f5409b71ce7fc66002f6 | [
"MIT"
] | null | null | null | r"""Initiate an acquisition and fetch a waveform for each specified channel.
The gRPC API is built from the C API. NI-SCOPE documentation is installed with the driver at:
C:\Program Files (x86)\IVI Foundation\IVI\Drivers\niScope\Documentation\English\Digitizers.chm
A version of this .chm is available online at:
https://zone.ni.com/reference/en-XX/help/370592AB-01/
Getting Started:
To run this example, install "NI-SCOPE Driver" on the server machine:
https://www.ni.com/en-us/support/downloads/drivers/download.ni-scope.html
For instructions on how to use protoc to generate gRPC client interfaces, see our "Creating a gRPC
Client" wiki page:
https://github.com/ni/grpc-device/wiki/Creating-a-gRPC-Client
Refer to the NI-SCOPE gRPC Wiki to determine the valid channel and resource names for your NI-SCOPE
module:
https://github.com/ni/grpc-device/wiki/NI-SCOPE-C-Function-Reference
Running from command line:
Server machine's IP address, port number, and resource name can be passed as separate command line
arguments.
> python fetch.py <server_address> <port_number> <resource_name>
If they are not passed in as command line arguments, then by default the server address will be
"localhost:31763", with "SimulatedScope" as the resource name.
"""
import sys
import grpc
import niscope_pb2 as niscope_types
import niscope_pb2_grpc as grpc_niscope
SERVER_ADDRESS = "localhost"
SERVER_PORT = "31763"
# Resource name and options for a simulated 5164 client. Change them according to the NI-SCOPE
# model.
RESOURCE = "SimulatedScope"
OPTIONS = "Simulate=1, DriverSetup=Model:5164; BoardType:PXIe"
CHANNELS = "0"
# Read in cmd args
if len(sys.argv) >= 2:
SERVER_ADDRESS = sys.argv[1]
if len(sys.argv) >= 3:
SERVER_PORT = sys.argv[2]
if len(sys.argv) >= 4:
RESOURCE = sys.argv[3]
OPTIONS = ""
# Create the communication channel for the remote host and create a connection to the NI-SCOPE
# service.
channel = grpc.insecure_channel(f"{SERVER_ADDRESS}:{SERVER_PORT}")
client = grpc_niscope.NiScopeStub(channel)
def check_for_error(vi, status):
"""Raise an exception if the status indicates an error."""
if status != 0:
error_message_response = client.ErrorMessage(
niscope_types.ErrorMessageRequest(vi=vi, error_code=status)
)
raise Exception(error_message_response.error_message)
def check_for_initialization_error(response):
"""Raise an exception if an error was returned from Initialize."""
if response.status < 0:
raise RuntimeError(f"Error: {response.error_message or response.status}")
if response.status > 0:
sys.stderr.write(f"Warning: {response.error_message or response.status}\n")
try:
# Open session to NI-SCOPE module with options.
init_with_options_response = client.InitWithOptions(
niscope_types.InitWithOptionsRequest(
resource_name=RESOURCE, id_query=False, option_string=OPTIONS
)
)
vi = init_with_options_response.vi
check_for_initialization_error(init_with_options_response)
# Configure vertical.
voltage = 10.0
check_for_error(
vi,
(
client.ConfigureVertical(
niscope_types.ConfigureVerticalRequest(
vi=vi,
channel_list=CHANNELS,
range=voltage,
offset=0.0,
coupling=niscope_types.VerticalCoupling.VERTICAL_COUPLING_NISCOPE_VAL_AC,
probe_attenuation=1.0,
enabled=True,
)
)
).status,
)
# Configure horizontal timing.
samples = 1000
check_for_error(
vi,
(
client.ConfigureHorizontalTiming(
niscope_types.ConfigureHorizontalTimingRequest(
vi=vi,
min_sample_rate=50000000,
min_num_pts=samples,
ref_position=50.0,
num_records=1,
enforce_realtime=True,
)
)
).status,
)
# Initiate acquisition.
check_for_error(
vi, (client.InitiateAcquisition(niscope_types.InitiateAcquisitionRequest(vi=vi))).status
)
# Fetch waveforms.
fetch_response = client.Fetch(
niscope_types.FetchRequest(vi=vi, channel_list=CHANNELS, timeout=10000, num_samples=samples)
)
check_for_error(vi, fetch_response.status)
waveforms = fetch_response.waveform
# Print waveform results.
for i in range(len(waveforms)):
print(f"Waveform {i} information:")
print(f"{waveforms[i]}\n")
# If NI-SCOPE API throws an exception, print the error message.
except grpc.RpcError as rpc_error:
error_message = rpc_error.details()
if rpc_error.code() == grpc.StatusCode.UNAVAILABLE:
error_message = f"Failed to connect to server on {SERVER_ADDRESS}:{SERVER_PORT}"
elif rpc_error.code() == grpc.StatusCode.UNIMPLEMENTED:
error_message = (
"The operation is not implemented or is not supported/enabled in this service"
)
print(f"{error_message}")
finally:
if "vi" in vars() and vi.id != 0:
# close the session.
check_for_error(vi, (client.Close(niscope_types.CloseRequest(vi=vi))).status)
| 33.658228 | 100 | 0.678827 |
import sys
import grpc
import niscope_pb2 as niscope_types
import niscope_pb2_grpc as grpc_niscope
SERVER_ADDRESS = "localhost"
SERVER_PORT = "31763"
RESOURCE = "SimulatedScope"
OPTIONS = "Simulate=1, DriverSetup=Model:5164; BoardType:PXIe"
CHANNELS = "0"
if len(sys.argv) >= 2:
SERVER_ADDRESS = sys.argv[1]
if len(sys.argv) >= 3:
SERVER_PORT = sys.argv[2]
if len(sys.argv) >= 4:
RESOURCE = sys.argv[3]
OPTIONS = ""
channel = grpc.insecure_channel(f"{SERVER_ADDRESS}:{SERVER_PORT}")
client = grpc_niscope.NiScopeStub(channel)
def check_for_error(vi, status):
if status != 0:
error_message_response = client.ErrorMessage(
niscope_types.ErrorMessageRequest(vi=vi, error_code=status)
)
raise Exception(error_message_response.error_message)
def check_for_initialization_error(response):
if response.status < 0:
raise RuntimeError(f"Error: {response.error_message or response.status}")
if response.status > 0:
sys.stderr.write(f"Warning: {response.error_message or response.status}\n")
try:
init_with_options_response = client.InitWithOptions(
niscope_types.InitWithOptionsRequest(
resource_name=RESOURCE, id_query=False, option_string=OPTIONS
)
)
vi = init_with_options_response.vi
check_for_initialization_error(init_with_options_response)
voltage = 10.0
check_for_error(
vi,
(
client.ConfigureVertical(
niscope_types.ConfigureVerticalRequest(
vi=vi,
channel_list=CHANNELS,
range=voltage,
offset=0.0,
coupling=niscope_types.VerticalCoupling.VERTICAL_COUPLING_NISCOPE_VAL_AC,
probe_attenuation=1.0,
enabled=True,
)
)
).status,
)
samples = 1000
check_for_error(
vi,
(
client.ConfigureHorizontalTiming(
niscope_types.ConfigureHorizontalTimingRequest(
vi=vi,
min_sample_rate=50000000,
min_num_pts=samples,
ref_position=50.0,
num_records=1,
enforce_realtime=True,
)
)
).status,
)
check_for_error(
vi, (client.InitiateAcquisition(niscope_types.InitiateAcquisitionRequest(vi=vi))).status
)
fetch_response = client.Fetch(
niscope_types.FetchRequest(vi=vi, channel_list=CHANNELS, timeout=10000, num_samples=samples)
)
check_for_error(vi, fetch_response.status)
waveforms = fetch_response.waveform
for i in range(len(waveforms)):
print(f"Waveform {i} information:")
print(f"{waveforms[i]}\n")
except grpc.RpcError as rpc_error:
error_message = rpc_error.details()
if rpc_error.code() == grpc.StatusCode.UNAVAILABLE:
error_message = f"Failed to connect to server on {SERVER_ADDRESS}:{SERVER_PORT}"
elif rpc_error.code() == grpc.StatusCode.UNIMPLEMENTED:
error_message = (
"The operation is not implemented or is not supported/enabled in this service"
)
print(f"{error_message}")
finally:
if "vi" in vars() and vi.id != 0:
check_for_error(vi, (client.Close(niscope_types.CloseRequest(vi=vi))).status)
| true | true |
f73bcd99a3c7c808b15a9439df00b8a3368de919 | 6,063 | py | Python | demoapp/settings/base.py | praekelt/molo-surveysdemo | fc6f3f9e64f3c16bd3a774186e4699f756e36147 | [
"BSD-2-Clause"
] | null | null | null | demoapp/settings/base.py | praekelt/molo-surveysdemo | fc6f3f9e64f3c16bd3a774186e4699f756e36147 | [
"BSD-2-Clause"
] | null | null | null | demoapp/settings/base.py | praekelt/molo-surveysdemo | fc6f3f9e64f3c16bd3a774186e4699f756e36147 | [
"BSD-2-Clause"
] | null | null | null | """
Django settings for base demoapp.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
from os.path import abspath, dirname, join
from django.conf import global_settings
from django.utils.translation import ugettext_lazy as _
import dj_database_url
import djcelery
from celery.schedules import crontab
djcelery.setup_loader()
# Absolute filesystem path to the Django project directory:
PROJECT_ROOT = dirname(dirname(dirname(abspath(__file__))))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "vonsm$$=sj6r06b7m$j--4ly6gtwl7vz_#+ip($b&j!v#@i++d"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*']
# Base URL to use when referring to full URLs within the Wagtail admin
# backend - e.g. in notification emails. Don't include '/admin' or
# a trailing slash
BASE_URL = 'http://example.com'
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django_extensions',
'taggit',
'modelcluster',
'wagtail.wagtailcore',
'wagtail.wagtailadmin',
'wagtail.wagtaildocs',
'wagtail.wagtailsnippets',
'wagtail.wagtailusers',
'wagtail.wagtailsites',
'wagtail.wagtailimages',
'wagtail.wagtailembeds',
'wagtail.wagtailsearch',
'wagtail.wagtailredirects',
'wagtail.wagtailforms',
'wagtail.contrib.settings',
'molo.core',
'demoapp',
'mptt',
'djcelery',
'raven.contrib.django.raven_compat',
'django_cas_ng',
'compressor',
'wagtailsurveys',
'molo.surveys'
)
SITE_ID = 1
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'wagtail.wagtailcore.middleware.SiteMiddleware',
'wagtail.wagtailredirects.middleware.RedirectMiddleware',
)
ROOT_URLCONF = 'demoapp.urls'
WSGI_APPLICATION = 'demoapp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
# SQLite (simplest install)
DATABASES = {'default': dj_database_url.config(
default='sqlite:///%s' % (join(PROJECT_ROOT, 'db.sqlite3'),))}
# PostgreSQL (Recommended, but requires the psycopg2 library and Postgresql
# development headers)
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.postgresql_psycopg2',
# 'NAME': 'base',
# 'USER': 'postgres',
# 'PASSWORD': '',
# 'HOST': '', # Set to empty string for localhost.
# 'PORT': '', # Set to empty string for default.
# # number of seconds database connections should persist for
# 'CONN_MAX_AGE': 600,
# }
# }
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_IMPORTS = ('molo.core.tasks')
BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERYBEAT_SCHEDULE = {
'rotate_content': {
'task': 'molo.core.tasks.rotate_content',
'schedule': crontab(minute=0),
},
}
LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'Africa/Johannesburg'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Native South African languages are currently not included in the default
# list of languges in django
# https://github.com/django/django/blob/master/django/conf/global_settings.py#L50
LANGUAGES = global_settings.LANGUAGES + (
('zu', _('Zulu')),
('xh', _('Xhosa')),
('st', _('Sotho')),
('ve', _('Venda')),
('tn', _('Tswana')),
('ts', _('Tsonga')),
('ss', _('Swati')),
('nr', _('Ndebele')),
)
LOCALE_PATHS = (
join(PROJECT_ROOT, "locale"),
)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_ROOT = join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
)
MEDIA_ROOT = join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'
# Django compressor settings
# http://django-compressor.readthedocs.org/en/latest/settings/
COMPRESS_PRECOMPILERS = (
('text/x-scss', 'django_libsass.SassCompiler'),
)
# Template configuration
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
'django.core.context_processors.request',
'molo.core.context_processors.locale',
'wagtail.contrib.settings.context_processors.settings',
)
# Wagtail settings
LOGIN_URL = 'wagtailadmin_login'
LOGIN_REDIRECT_URL = 'wagtailadmin_home'
WAGTAIL_SITE_NAME = "base"
# Use Elasticsearch as the search backend for extra performance and better
# search results:
# http://wagtail.readthedocs.org/en/latest/howto/performance.html#search
# http://wagtail.readthedocs.org/en/latest/core_components/
# search/backends.html#elasticsearch-backend
#
# WAGTAILSEARCH_BACKENDS = {
# 'default': {
# 'BACKEND': ('wagtail.wagtailsearch.backends.'
# 'elasticsearch.ElasticSearch'),
# 'INDEX': 'base',
# },
# }
# Whether to use face/feature detection to improve image
# cropping - requires OpenCV
WAGTAILIMAGES_FEATURE_DETECTION_ENABLED = False
ENABLE_SSO = False
| 27.066964 | 81 | 0.70856 |
from os.path import abspath, dirname, join
from django.conf import global_settings
from django.utils.translation import ugettext_lazy as _
import dj_database_url
import djcelery
from celery.schedules import crontab
djcelery.setup_loader()
PROJECT_ROOT = dirname(dirname(dirname(abspath(__file__))))
SECRET_KEY = "vonsm$$=sj6r06b7m$j--4ly6gtwl7vz_#+ip($b&j!v#@i++d"
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*']
# Base URL to use when referring to full URLs within the Wagtail admin
# backend - e.g. in notification emails. Don't include '/admin' or
BASE_URL = 'http://example.com'
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django_extensions',
'taggit',
'modelcluster',
'wagtail.wagtailcore',
'wagtail.wagtailadmin',
'wagtail.wagtaildocs',
'wagtail.wagtailsnippets',
'wagtail.wagtailusers',
'wagtail.wagtailsites',
'wagtail.wagtailimages',
'wagtail.wagtailembeds',
'wagtail.wagtailsearch',
'wagtail.wagtailredirects',
'wagtail.wagtailforms',
'wagtail.contrib.settings',
'molo.core',
'demoapp',
'mptt',
'djcelery',
'raven.contrib.django.raven_compat',
'django_cas_ng',
'compressor',
'wagtailsurveys',
'molo.surveys'
)
SITE_ID = 1
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'wagtail.wagtailcore.middleware.SiteMiddleware',
'wagtail.wagtailredirects.middleware.RedirectMiddleware',
)
ROOT_URLCONF = 'demoapp.urls'
WSGI_APPLICATION = 'demoapp.wsgi.application'
ES = {'default': dj_database_url.config(
default='sqlite:///%s' % (join(PROJECT_ROOT, 'db.sqlite3'),))}
olo.core.tasks')
BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERYBEAT_SCHEDULE = {
'rotate_content': {
'task': 'molo.core.tasks.rotate_content',
'schedule': crontab(minute=0),
},
}
LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'Africa/Johannesburg'
USE_I18N = True
USE_L10N = True
USE_TZ = True
GUAGES = global_settings.LANGUAGES + (
('zu', _('Zulu')),
('xh', _('Xhosa')),
('st', _('Sotho')),
('ve', _('Venda')),
('tn', _('Tswana')),
('ts', _('Tsonga')),
('ss', _('Swati')),
('nr', _('Ndebele')),
)
LOCALE_PATHS = (
join(PROJECT_ROOT, "locale"),
)
STATIC_ROOT = join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
)
MEDIA_ROOT = join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'
COMPRESS_PRECOMPILERS = (
('text/x-scss', 'django_libsass.SassCompiler'),
)
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
'django.core.context_processors.request',
'molo.core.context_processors.locale',
'wagtail.contrib.settings.context_processors.settings',
)
LOGIN_URL = 'wagtailadmin_login'
LOGIN_REDIRECT_URL = 'wagtailadmin_home'
WAGTAIL_SITE_NAME = "base"
FEATURE_DETECTION_ENABLED = False
ENABLE_SSO = False
| true | true |
f73bcebdd2a730d1c6d54902c36ea152cddb678f | 49,581 | py | Python | ta/trend.py | amalekji/trading-tech-analysis | b360062d6b2a31f0bf237e42a9a399d3b1f6c306 | [
"MIT"
] | 1 | 2020-07-18T09:05:57.000Z | 2020-07-18T09:05:57.000Z | ta/trend.py | amalekji/trading-tech-analysis | b360062d6b2a31f0bf237e42a9a399d3b1f6c306 | [
"MIT"
] | null | null | null | ta/trend.py | amalekji/trading-tech-analysis | b360062d6b2a31f0bf237e42a9a399d3b1f6c306 | [
"MIT"
] | 1 | 2020-08-25T18:16:11.000Z | 2020-08-25T18:16:11.000Z | """
.. module:: trend
:synopsis: Trend Indicators.
.. moduleauthor:: Dario Lopez Padial (Bukosabino)
"""
import numpy as np
import pandas as pd
from ta.utils import IndicatorMixin, ema, get_min_max, sma
class AroonIndicator(IndicatorMixin):
"""Aroon Indicator
Identify when trends are likely to change direction.
Aroon Up = ((N - Days Since N-day High) / N) x 100
Aroon Down = ((N - Days Since N-day Low) / N) x 100
Aroon Indicator = Aroon Up - Aroon Down
https://www.investopedia.com/terms/a/aroon.asp
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
"""
def __init__(self, close: pd.Series, n: int = 25, fillna: bool = False):
self._close = close
self._n = n
self._fillna = fillna
self._run()
def _run(self):
min_periods = 0 if self._fillna else self._n
rolling_close = self._close.rolling(self._n, min_periods=min_periods)
self._aroon_up = rolling_close.apply(
lambda x: float(np.argmax(x) + 1) / self._n * 100, raw=True)
self._aroon_down = rolling_close.apply(
lambda x: float(np.argmin(x) + 1) / self._n * 100, raw=True)
def aroon_up(self) -> pd.Series:
"""Aroon Up Channel
Returns:
pandas.Series: New feature generated.
"""
aroon_up = self._check_fillna(self._aroon_up, value=0)
return pd.Series(aroon_up, name=f'aroon_up_{self._n}')
def aroon_down(self) -> pd.Series:
"""Aroon Down Channel
Returns:
pandas.Series: New feature generated.
"""
aroon_down = self._check_fillna(self._aroon_down, value=0)
return pd.Series(aroon_down, name=f'aroon_down_{self._n}')
def aroon_indicator(self) -> pd.Series:
"""Aroon Indicator
Returns:
pandas.Series: New feature generated.
"""
aroon_diff = self._aroon_up - self._aroon_down
aroon_diff = self._check_fillna(aroon_diff, value=0)
return pd.Series(aroon_diff, name=f'aroon_ind_{self._n}')
class MACD(IndicatorMixin):
"""Moving Average Convergence Divergence (MACD)
Is a trend-following momentum indicator that shows the relationship between
two moving averages of prices.
https://school.stockcharts.com/doku.php?id=technical_indicators:moving_average_convergence_divergence_macd
Args:
close(pandas.Series): dataset 'Close' column.
n_fast(int): n period short-term.
n_slow(int): n period long-term.
n_sign(int): n period to signal.
fillna(bool): if True, fill nan values.
"""
def __init__(self,
close: pd.Series,
n_slow: int = 26,
n_fast: int = 12,
n_sign: int = 9,
fillna: bool = False):
self._close = close
self._n_slow = n_slow
self._n_fast = n_fast
self._n_sign = n_sign
self._fillna = fillna
self._run()
def _run(self):
self._emafast = ema(self._close, self._n_fast, self._fillna)
self._emaslow = ema(self._close, self._n_slow, self._fillna)
self._macd = self._emafast - self._emaslow
self._macd_signal = ema(self._macd, self._n_sign, self._fillna)
self._macd_diff = self._macd - self._macd_signal
def macd(self) -> pd.Series:
"""MACD Line
Returns:
pandas.Series: New feature generated.
"""
macd = self._check_fillna(self._macd, value=0)
return pd.Series(macd, name=f'MACD_{self._n_fast}_{self._n_slow}')
def macd_signal(self) -> pd.Series:
"""Signal Line
Returns:
pandas.Series: New feature generated.
"""
macd_signal = self._check_fillna(self._macd_signal, value=0)
return pd.Series(macd_signal, name=f'MACD_sign_{self._n_fast}_{self._n_slow}')
def macd_diff(self) -> pd.Series:
"""MACD Histogram
Returns:
pandas.Series: New feature generated.
"""
macd_diff = self._check_fillna(self._macd_diff, value=0)
return pd.Series(macd_diff, name=f'MACD_diff_{self._n_fast}_{self._n_slow}')
class EMAIndicator(IndicatorMixin):
"""EMA - Exponential Moving Average
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
"""
def __init__(self, close: pd.Series, n: int = 14, fillna: bool = False):
self._close = close
self._n = n
self._fillna = fillna
def ema_indicator(self) -> pd.Series:
"""Exponential Moving Average (EMA)
Returns:
pandas.Series: New feature generated.
"""
ema_ = ema(self._close, self._n, self._fillna)
return pd.Series(ema_, name=f'ema_{self._n}')
class SMAIndicator(IndicatorMixin):
"""SMA - Simple Moving Average
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
"""
def __init__(self, close: pd.Series, n: int, fillna: bool = False):
self._close = close
self._n = n
self._fillna = fillna
def sma_indicator(self) -> pd.Series:
"""Simple Moving Average (SMA)
Returns:
pandas.Series: New feature generated.
"""
sma_ = sma(self._close, self._n, self._fillna)
return pd.Series(sma_, name=f'sma_{self._n}')
class TRIXIndicator(IndicatorMixin):
"""Trix (TRIX)
Shows the percent rate of change of a triple exponentially smoothed moving
average.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:trix
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
"""
def __init__(self, close: pd.Series, n: int = 15, fillna: bool = False):
self._close = close
self._n = n
self._fillna = fillna
self._run()
def _run(self):
ema1 = ema(self._close, self._n, self._fillna)
ema2 = ema(ema1, self._n, self._fillna)
ema3 = ema(ema2, self._n, self._fillna)
self._trix = (ema3 - ema3.shift(1, fill_value=ema3.mean())) / ema3.shift(1, fill_value=ema3.mean())
self._trix *= 100
def trix(self) -> pd.Series:
"""Trix (TRIX)
Returns:
pandas.Series: New feature generated.
"""
trix = self._check_fillna(self._trix, value=0)
return pd.Series(trix, name=f'trix_{self._n}')
class MassIndex(IndicatorMixin):
"""Mass Index (MI)
It uses the high-low range to identify trend reversals based on range
expansions. It identifies range bulges that can foreshadow a reversal of
the current trend.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:mass_index
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
n(int): n low period.
n2(int): n high period.
fillna(bool): if True, fill nan values.
"""
def __init__(self, high: pd.Series, low: pd.Series, n: int = 9, n2: int = 25, fillna: bool = False):
self._high = high
self._low = low
self._n = n
self._n2 = n2
self._fillna = fillna
self._run()
def _run(self):
min_periods = 0 if self._fillna else self._n2
amplitude = self._high - self._low
ema1 = ema(amplitude, self._n, self._fillna)
ema2 = ema(ema1, self._n, self._fillna)
mass = ema1 / ema2
self._mass = mass.rolling(self._n2, min_periods=min_periods).sum()
def mass_index(self) -> pd.Series:
"""Mass Index (MI)
Returns:
pandas.Series: New feature generated.
"""
mass = self._check_fillna(self._mass, value=0)
return pd.Series(mass, name=f'mass_index_{self._n}_{self._n2}')
class IchimokuIndicator(IndicatorMixin):
"""Ichimoku Kinkō Hyō (Ichimoku)
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ichimoku_cloud
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
n1(int): n1 low period.
n2(int): n2 medium period.
n3(int): n3 high period.
visual(bool): if True, shift n2 values.
fillna(bool): if True, fill nan values.
"""
def __init__(self, high: pd.Series, low: pd.Series, n1: int = 9, n2: int = 26, n3: int = 52,
visual: bool = False, fillna: bool = False):
self._high = high
self._low = low
self._n1 = n1
self._n2 = n2
self._n3 = n3
self._visual = visual
self._fillna = fillna
self._run()
def _run(self):
min_periods_n1 = 0 if self._fillna else self._n1
min_periods_n2 = 0 if self._fillna else self._n2
self._conv = 0.5 * (
self._high.rolling(self._n1, min_periods=min_periods_n1).max() +
self._low.rolling(self._n1, min_periods=min_periods_n1).min())
self._base = 0.5 * (
self._high.rolling(self._n2, min_periods=min_periods_n2).max() +
self._low.rolling(self._n2, min_periods=min_periods_n2).min())
def ichimoku_conversion_line(self) -> pd.Series:
"""Tenkan-sen (Conversion Line)
Returns:
pandas.Series: New feature generated.
"""
conversion = self._check_fillna(self._conv, value=-1)
return pd.Series(conversion, name=f'ichimoku_conv_{self._n1}_{self._n2}')
def ichimoku_base_line(self) -> pd.Series:
"""Kijun-sen (Base Line)
Returns:
pandas.Series: New feature generated.
"""
base = self._check_fillna(self._base, value=-1)
return pd.Series(base, name=f'ichimoku_base_{self._n1}_{self._n2}')
def ichimoku_a(self) -> pd.Series:
"""Senkou Span A (Leading Span A)
Returns:
pandas.Series: New feature generated.
"""
spana = 0.5 * (self._conv + self._base)
spana = spana.shift(self._n2, fill_value=spana.mean()) if self._visual else spana
spana = self._check_fillna(spana, value=-1)
return pd.Series(spana, name=f'ichimoku_a_{self._n1}_{self._n2}')
def ichimoku_b(self) -> pd.Series:
"""Senkou Span B (Leading Span B)
Returns:
pandas.Series: New feature generated.
"""
spanb = 0.5 * (self._high.rolling(self._n3, min_periods=0).max()
+ self._low.rolling(self._n3, min_periods=0).min())
spanb = spanb.shift(self._n2, fill_value=spanb.mean()) if self._visual else spanb
spanb = self._check_fillna(spanb, value=-1)
return pd.Series(spanb, name=f'ichimoku_b_{self._n1}_{self._n2}')
class KSTIndicator(IndicatorMixin):
"""KST Oscillator (KST Signal)
It is useful to identify major stock market cycle junctures because its
formula is weighed to be more greatly influenced by the longer and more
dominant time spans, in order to better reflect the primary swings of stock
market cycle.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:know_sure_thing_kst
Args:
close(pandas.Series): dataset 'Close' column.
r1(int): r1 period.
r2(int): r2 period.
r3(int): r3 period.
r4(int): r4 period.
n1(int): n1 smoothed period.
n2(int): n2 smoothed period.
n3(int): n3 smoothed period.
n4(int): n4 smoothed period.
nsig(int): n period to signal.
fillna(bool): if True, fill nan values.
"""
def __init__(self, close: pd.Series, r1: int = 10, r2: int = 15, r3: int = 20, r4: int = 30,
n1: int = 10, n2: int = 10, n3: int = 10, n4: int = 15, nsig: int = 9,
fillna: bool = False):
self._close = close
self._r1 = r1
self._r2 = r2
self._r3 = r3
self._r4 = r4
self._n1 = n1
self._n2 = n2
self._n3 = n3
self._n4 = n4
self._nsig = nsig
self._fillna = fillna
self._run()
def _run(self):
min_periods_n1 = 0 if self._fillna else self._n1
min_periods_n2 = 0 if self._fillna else self._n2
min_periods_n3 = 0 if self._fillna else self._n3
min_periods_n4 = 0 if self._fillna else self._n4
rocma1 = (
(self._close - self._close.shift(self._r1, fill_value=self._close.mean()))
/ self._close.shift(self._r1, fill_value=self._close.mean())).rolling(
self._n1, min_periods=min_periods_n1).mean()
rocma2 = (
(self._close - self._close.shift(self._r2, fill_value=self._close.mean()))
/ self._close.shift(self._r2, fill_value=self._close.mean())).rolling(
self._n2, min_periods=min_periods_n2).mean()
rocma3 = (
(self._close - self._close.shift(self._r3, fill_value=self._close.mean()))
/ self._close.shift(self._r3, fill_value=self._close.mean())).rolling(
self._n3, min_periods=min_periods_n3).mean()
rocma4 = (
(self._close - self._close.shift(self._r4, fill_value=self._close.mean()))
/ self._close.shift(self._r4, fill_value=self._close.mean())).rolling(
self._n4, min_periods=min_periods_n4).mean()
self._kst = 100 * (rocma1 + 2 * rocma2 + 3 * rocma3 + 4 * rocma4)
self._kst_sig = self._kst.rolling(self._nsig, min_periods=0).mean()
def kst(self) -> pd.Series:
"""Know Sure Thing (KST)
Returns:
pandas.Series: New feature generated.
"""
kst = self._check_fillna(self._kst, value=0)
return pd.Series(kst, name='kst')
def kst_sig(self) -> pd.Series:
"""Signal Line Know Sure Thing (KST)
nsig-period SMA of KST
Returns:
pandas.Series: New feature generated.
"""
kst_sig = self._check_fillna(self._kst_sig, value=0)
return pd.Series(kst_sig, name='kst_sig')
def kst_diff(self) -> pd.Series:
"""Diff Know Sure Thing (KST)
KST - Signal_KST
Returns:
pandas.Series: New feature generated.
"""
kst_diff = self._kst - self._kst_sig
kst_diff = self._check_fillna(kst_diff, value=0)
return pd.Series(kst_diff, name='kst_diff')
class DPOIndicator(IndicatorMixin):
"""Detrended Price Oscillator (DPO)
Is an indicator designed to remove trend from price and make it easier to
identify cycles.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:detrended_price_osci
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
"""
def __init__(self, close: pd.Series, n: int = 20, fillna: bool = False):
self._close = close
self._n = n
self._fillna = fillna
self._run()
def _run(self):
min_periods = 0 if self._fillna else self._n
self._dpo = (self._close.shift(int((0.5 * self._n) + 1), fill_value=self._close.mean())
- self._close.rolling(self._n, min_periods=min_periods).mean())
def dpo(self) -> pd.Series:
"""Detrended Price Oscillator (DPO)
Returns:
pandas.Series: New feature generated.
"""
dpo = self._check_fillna(self._dpo, value=0)
return pd.Series(dpo, name='dpo_'+str(self._n))
class CCIIndicator(IndicatorMixin):
"""Commodity Channel Index (CCI)
CCI measures the difference between a security's price change and its
average price change. High positive readings indicate that prices are well
above their average, which is a show of strength. Low negative readings
indicate that prices are well below their average, which is a show of
weakness.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:commodity_channel_index_cci
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
c(int): constant.
fillna(bool): if True, fill nan values.
"""
def __init__(self,
high: pd.Series,
low: pd.Series,
close: pd.Series,
n: int = 20,
c: float = 0.015,
fillna: bool = False):
self._high = high
self._low = low
self._close = close
self._n = n
self._c = c
self._fillna = fillna
self._run()
def _run(self):
def _mad(x):
return np.mean(np.abs(x-np.mean(x)))
min_periods = 0 if self._fillna else self._n
pp = (self._high + self._low + self._close) / 3.0
self._cci = ((pp - pp.rolling(self._n, min_periods=min_periods).mean())
/ (self._c * pp.rolling(self._n, min_periods=min_periods).apply(_mad, True)))
def cci(self) -> pd.Series:
"""Commodity Channel Index (CCI)
Returns:
pandas.Series: New feature generated.
"""
cci = self._check_fillna(self._cci, value=0)
return pd.Series(cci, name='cci')
class ADXIndicator(IndicatorMixin):
"""Average Directional Movement Index (ADX)
The Plus Directional Indicator (+DI) and Minus Directional Indicator (-DI)
are derived from smoothed averages of these differences, and measure trend
direction over time. These two indicators are often referred to
collectively as the Directional Movement Indicator (DMI).
The Average Directional Index (ADX) is in turn derived from the smoothed
averages of the difference between +DI and -DI, and measures the strength
of the trend (regardless of direction) over time.
Using these three indicators together, chartists can determine both the
direction and strength of the trend.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_directional_index_adx
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
"""
def __init__(self, high: pd.Series, low: pd.Series, close: pd.Series, n: int = 14, fillna: bool = False):
self._high = high
self._low = low
self._close = close
self._n = n
self._fillna = fillna
self._run()
def _run(self):
assert self._n != 0, "N may not be 0 and is %r" % n
cs = self._close.shift(1)
pdm = get_min_max(self._high, cs, 'max')
pdn = get_min_max(self._low, cs, 'min')
tr = pdm - pdn
self._trs_initial = np.zeros(self._n-1)
self._trs = np.zeros(len(self._close) - (self._n - 1))
self._trs[0] = tr.dropna()[0:self._n].sum()
tr = tr.reset_index(drop=True)
for i in range(1, len(self._trs)-1):
self._trs[i] = self._trs[i-1] - (self._trs[i-1]/float(self._n)) + tr[self._n+i]
up = self._high - self._high.shift(1)
dn = self._low.shift(1) - self._low
pos = abs(((up > dn) & (up > 0)) * up)
neg = abs(((dn > up) & (dn > 0)) * dn)
self._dip = np.zeros(len(self._close) - (self._n - 1))
self._dip[0] = pos.dropna()[0:self._n].sum()
pos = pos.reset_index(drop=True)
for i in range(1, len(self._dip)-1):
self._dip[i] = self._dip[i-1] - (self._dip[i-1]/float(self._n)) + pos[self._n+i]
self._din = np.zeros(len(self._close) - (self._n - 1))
self._din[0] = neg.dropna()[0:self._n].sum()
neg = neg.reset_index(drop=True)
for i in range(1, len(self._din)-1):
self._din[i] = self._din[i-1] - (self._din[i-1]/float(self._n)) + neg[self._n+i]
def adx(self) -> pd.Series:
"""Average Directional Index (ADX)
Returns:
pandas.Series: New feature generated.
"""
dip = np.zeros(len(self._trs))
for i in range(len(self._trs)):
dip[i] = 100 * (self._dip[i]/self._trs[i])
din = np.zeros(len(self._trs))
for i in range(len(self._trs)):
din[i] = 100 * (self._din[i]/self._trs[i])
dx = 100 * np.abs((dip - din) / (dip + din))
adx = np.zeros(len(self._trs))
adx[self._n] = dx[0:self._n].mean()
for i in range(self._n+1, len(adx)):
adx[i] = ((adx[i-1] * (self._n - 1)) + dx[i-1]) / float(self._n)
adx = np.concatenate((self._trs_initial, adx), axis=0)
self._adx = pd.Series(data=adx, index=self._close.index)
adx = self._check_fillna(self._adx, value=20)
return pd.Series(adx, name='adx')
def adx_pos(self) -> pd.Series:
"""Plus Directional Indicator (+DI)
Returns:
pandas.Series: New feature generated.
"""
dip = np.zeros(len(self._close))
for i in range(1, len(self._trs)-1):
dip[i+self._n] = 100 * (self._dip[i]/self._trs[i])
adx_pos = self._check_fillna(pd.Series(dip, index=self._close.index), value=20)
return pd.Series(adx_pos, name='adx_pos')
def adx_neg(self) -> pd.Series:
"""Minus Directional Indicator (-DI)
Returns:
pandas.Series: New feature generated.
"""
din = np.zeros(len(self._close))
for i in range(1, len(self._trs)-1):
din[i+self._n] = 100 * (self._din[i]/self._trs[i])
adx_neg = self._check_fillna(pd.Series(din, index=self._close.index), value=20)
return pd.Series(adx_neg, name='adx_neg')
class VortexIndicator(IndicatorMixin):
"""Vortex Indicator (VI)
It consists of two oscillators that capture positive and negative trend
movement. A bullish signal triggers when the positive trend indicator
crosses above the negative trend indicator or a key level.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:vortex_indicator
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
"""
def __init__(self, high: pd.Series, low: pd.Series, close: pd.Series, n: int = 14, fillna: bool = False):
self._high = high
self._low = low
self._close = close
self._n = n
self._fillna = fillna
self._run()
def _run(self):
cs = self._close.shift(1, fill_value=self._close.mean())
tr = self._true_range(self._high, self._low, cs)
min_periods = 0 if self._fillna else self._n
trn = tr.rolling(self._n, min_periods=min_periods).sum()
vmp = np.abs(self._high - self._low.shift(1))
vmm = np.abs(self._low - self._high.shift(1))
self._vip = vmp.rolling(self._n, min_periods=min_periods).sum() / trn
self._vin = vmm.rolling(self._n, min_periods=min_periods).sum() / trn
def vortex_indicator_pos(self):
"""+VI
Returns:
pandas.Series: New feature generated.
"""
vip = self._check_fillna(self._vip, value=1)
return pd.Series(vip, name='vip')
def vortex_indicator_neg(self):
"""-VI
Returns:
pandas.Series: New feature generated.
"""
vin = self._check_fillna(self._vin, value=1)
return pd.Series(vin, name='vin')
def vortex_indicator_diff(self):
"""Diff VI
Returns:
pandas.Series: New feature generated.
"""
vid = self._vip - self._vin
vid = self._check_fillna(vid, value=0)
return pd.Series(vid, name='vid')
class PSARIndicator(IndicatorMixin):
"""Parabolic Stop and Reverse (Parabolic SAR)
The Parabolic Stop and Reverse, more commonly known as the
Parabolic SAR,is a trend-following indicator developed by
J. Welles Wilder. The Parabolic SAR is displayed as a single
parabolic line (or dots) underneath the price bars in an uptrend,
and above the price bars in a downtrend.
https://school.stockcharts.com/doku.php?id=technical_indicators:parabolic_sar
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
step(float): the Acceleration Factor used to compute the SAR.
max_step(float): the maximum value allowed for the Acceleration Factor.
fillna(bool): if True, fill nan values.
"""
def __init__(self, high: pd.Series, low: pd.Series, close: pd.Series,
step: float = 0.02, max_step: float = 0.20,
fillna: bool = False):
self._high = high
self._low = low
self._close = close
self._step = step
self._max_step = max_step
self._fillna = fillna
self._run()
def _run(self):
up_trend = True
af = self._step
up_trend_high = self._high.iloc[0]
down_trend_low = self._low.iloc[0]
self._psar = self._close.copy()
self._psar_up = pd.Series(index=self._psar.index)
self._psar_down = pd.Series(index=self._psar.index)
for i in range(2, len(self._close)):
reversal = False
max_high = self._high.iloc[i]
min_low = self._low.iloc[i]
if up_trend:
self._psar.iloc[i] = self._psar.iloc[i-1] + (
af * (up_trend_high - self._psar.iloc[i-1]))
if min_low < self._psar.iloc[i]:
reversal = True
self._psar.iloc[i] = up_trend_high
down_trend_low = min_low
af = self._step
else:
if max_high > up_trend_high:
up_trend_high = max_high
af = min(af + self._step, self._max_step)
l1 = self._low.iloc[i-1]
l2 = self._low.iloc[i-2]
if l2 < self._psar.iloc[i]:
self._psar.iloc[i] = l2
elif l1 < self._psar.iloc[i]:
self._psar.iloc[i] = l1
else:
self._psar.iloc[i] = self._psar.iloc[i-1] - (
af * (self._psar.iloc[i-1] - down_trend_low))
if max_high > self._psar.iloc[i]:
reversal = True
self._psar.iloc[i] = down_trend_low
up_trend_high = max_high
af = self._step
else:
if min_low < down_trend_low:
down_trend_low = min_low
af = min(af + self._step, self._max_step)
h1 = self._high.iloc[i-1]
h2 = self._high.iloc[i-2]
if h2 > self._psar.iloc[i]:
self._psar[i] = h2
elif h1 > self._psar.iloc[i]:
self._psar.iloc[i] = h1
up_trend = up_trend != reversal # XOR
if up_trend:
self._psar_up.iloc[i] = self._psar.iloc[i]
else:
self._psar_down.iloc[i] = self._psar.iloc[i]
def psar(self) -> pd.Series:
"""PSAR value
Returns:
pandas.Series: New feature generated.
"""
psar = self._check_fillna(self._psar, value=-1)
return pd.Series(psar, name='psar')
def psar_up(self) -> pd.Series:
"""PSAR up trend value
Returns:
pandas.Series: New feature generated.
"""
psar_up = self._check_fillna(self._psar_up, value=-1)
return pd.Series(psar_up, name='psarup')
def psar_down(self) -> pd.Series:
"""PSAR down trend value
Returns:
pandas.Series: New feature generated.
"""
psar_down = self._check_fillna(self._psar_down, value=-1)
return pd.Series(psar_down, name='psardown')
def psar_up_indicator(self) -> pd.Series:
"""PSAR up trend value
Returns:
pandas.Series: New feature generated.
"""
indicator = self._psar_up.where(self._psar_up.notnull()
& self._psar_up.shift(1).isnull(), 0)
indicator = indicator.where(indicator == 0, 1)
return pd.Series(indicator, index=self._close.index, name='psariup')
def psar_down_indicator(self) -> pd.Series:
"""PSAR down trend value
Returns:
pandas.Series: New feature generated.
"""
indicator = self._psar_up.where(self._psar_down.notnull()
& self._psar_down.shift(1).isnull(), 0)
indicator = indicator.where(indicator == 0, 1)
return pd.Series(indicator, index=self._close.index, name='psaridown')
def ema_indicator(close, n=12, fillna=False):
"""Exponential Moving Average (EMA)
Returns:
pandas.Series: New feature generated.
"""
return EMAIndicator(close=close, n=n, fillna=fillna).ema_indicator()
def sma_indicator(close, n=12, fillna=False):
"""Simple Moving Average (SMA)
Returns:
pandas.Series: New feature generated.
"""
return SMAIndicator(close=close, n=n, fillna=fillna).sma_indicator()
def macd(close, n_slow=26, n_fast=12, fillna=False):
"""Moving Average Convergence Divergence (MACD)
Is a trend-following momentum indicator that shows the relationship between
two moving averages of prices.
https://en.wikipedia.org/wiki/MACD
Args:
close(pandas.Series): dataset 'Close' column.
n_fast(int): n period short-term.
n_slow(int): n period long-term.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return MACD(close=close, n_slow=n_slow, n_fast=n_fast, n_sign=9, fillna=fillna).macd()
def macd_signal(close, n_slow=26, n_fast=12, n_sign=9, fillna=False):
"""Moving Average Convergence Divergence (MACD Signal)
Shows EMA of MACD.
https://en.wikipedia.org/wiki/MACD
Args:
close(pandas.Series): dataset 'Close' column.
n_fast(int): n period short-term.
n_slow(int): n period long-term.
n_sign(int): n period to signal.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return MACD(close=close, n_slow=n_slow, n_fast=n_fast, n_sign=n_sign, fillna=fillna).macd_signal()
def macd_diff(close, n_slow=26, n_fast=12, n_sign=9, fillna=False):
"""Moving Average Convergence Divergence (MACD Diff)
Shows the relationship between MACD and MACD Signal.
https://en.wikipedia.org/wiki/MACD
Args:
close(pandas.Series): dataset 'Close' column.
n_fast(int): n period short-term.
n_slow(int): n period long-term.
n_sign(int): n period to signal.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return MACD(close=close, n_slow=n_slow, n_fast=n_fast, n_sign=n_sign, fillna=fillna).macd_diff()
def adx(high, low, close, n=14, fillna=False):
"""Average Directional Movement Index (ADX)
The Plus Directional Indicator (+DI) and Minus Directional Indicator (-DI)
are derived from smoothed averages of these differences, and measure trend
direction over time. These two indicators are often referred to
collectively as the Directional Movement Indicator (DMI).
The Average Directional Index (ADX) is in turn derived from the smoothed
averages of the difference between +DI and -DI, and measures the strength
of the trend (regardless of direction) over time.
Using these three indicators together, chartists can determine both the
direction and strength of the trend.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_directional_index_adx
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return ADXIndicator(high=high, low=low, close=close, n=n, fillna=fillna).adx()
def adx_pos(high, low, close, n=14, fillna=False):
"""Average Directional Movement Index Positive (ADX)
The Plus Directional Indicator (+DI) and Minus Directional Indicator (-DI)
are derived from smoothed averages of these differences, and measure trend
direction over time. These two indicators are often referred to
collectively as the Directional Movement Indicator (DMI).
The Average Directional Index (ADX) is in turn derived from the smoothed
averages of the difference between +DI and -DI, and measures the strength
of the trend (regardless of direction) over time.
Using these three indicators together, chartists can determine both the
direction and strength of the trend.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_directional_index_adx
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return ADXIndicator(high=high, low=low, close=close, n=n, fillna=fillna).adx_pos()
def adx_neg(high, low, close, n=14, fillna=False):
"""Average Directional Movement Index Negative (ADX)
The Plus Directional Indicator (+DI) and Minus Directional Indicator (-DI)
are derived from smoothed averages of these differences, and measure trend
direction over time. These two indicators are often referred to
collectively as the Directional Movement Indicator (DMI).
The Average Directional Index (ADX) is in turn derived from the smoothed
averages of the difference between +DI and -DI, and measures the strength
of the trend (regardless of direction) over time.
Using these three indicators together, chartists can determine both the
direction and strength of the trend.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_directional_index_adx
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return ADXIndicator(high=high, low=low, close=close, n=n, fillna=fillna).adx_neg()
def vortex_indicator_pos(high, low, close, n=14, fillna=False):
"""Vortex Indicator (VI)
It consists of two oscillators that capture positive and negative trend
movement. A bullish signal triggers when the positive trend indicator
crosses above the negative trend indicator or a key level.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:vortex_indicator
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return VortexIndicator(high=high, low=low, close=close, n=n, fillna=fillna).vortex_indicator_pos()
def vortex_indicator_neg(high, low, close, n=14, fillna=False):
"""Vortex Indicator (VI)
It consists of two oscillators that capture positive and negative trend
movement. A bearish signal triggers when the negative trend indicator
crosses above the positive trend indicator or a key level.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:vortex_indicator
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return VortexIndicator(high=high, low=low, close=close, n=n, fillna=fillna).vortex_indicator_neg()
def trix(close, n=15, fillna=False):
"""Trix (TRIX)
Shows the percent rate of change of a triple exponentially smoothed moving
average.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:trix
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return TRIXIndicator(close=close, n=n, fillna=fillna).trix()
def mass_index(high, low, n=9, n2=25, fillna=False):
"""Mass Index (MI)
It uses the high-low range to identify trend reversals based on range
expansions. It identifies range bulges that can foreshadow a reversal of
the current trend.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:mass_index
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
n(int): n low period.
n2(int): n high period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return MassIndex(high=high, low=low, n=n, n2=n2, fillna=fillna).mass_index()
def cci(high, low, close, n=20, c=0.015, fillna=False):
"""Commodity Channel Index (CCI)
CCI measures the difference between a security's price change and its
average price change. High positive readings indicate that prices are well
above their average, which is a show of strength. Low negative readings
indicate that prices are well below their average, which is a show of
weakness.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:commodity_channel_index_cci
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
n(int): n periods.
c(int): constant.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return CCIIndicator(high=high, low=low, close=close, n=n, c=c, fillna=fillna).cci()
def dpo(close, n=20, fillna=False):
"""Detrended Price Oscillator (DPO)
Is an indicator designed to remove trend from price and make it easier to
identify cycles.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:detrended_price_osci
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return DPOIndicator(close=close, n=n, fillna=fillna).dpo()
def kst(close, r1=10, r2=15, r3=20, r4=30, n1=10, n2=10, n3=10, n4=15, fillna=False):
"""KST Oscillator (KST)
It is useful to identify major stock market cycle junctures because its
formula is weighed to be more greatly influenced by the longer and more
dominant time spans, in order to better reflect the primary swings of stock
market cycle.
https://en.wikipedia.org/wiki/KST_oscillator
Args:
close(pandas.Series): dataset 'Close' column.
r1(int): r1 period.
r2(int): r2 period.
r3(int): r3 period.
r4(int): r4 period.
n1(int): n1 smoothed period.
n2(int): n2 smoothed period.
n3(int): n3 smoothed period.
n4(int): n4 smoothed period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return KSTIndicator(
close=close, r1=r1, r2=r2, r3=r3, r4=r4, n1=n1, n2=n2, n3=n3, n4=n4, nsig=9, fillna=fillna).kst()
def kst_sig(close, r1=10, r2=15, r3=20, r4=30, n1=10, n2=10, n3=10, n4=15, nsig=9, fillna=False):
"""KST Oscillator (KST Signal)
It is useful to identify major stock market cycle junctures because its
formula is weighed to be more greatly influenced by the longer and more
dominant time spans, in order to better reflect the primary swings of stock
market cycle.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:know_sure_thing_kst
Args:
close(pandas.Series): dataset 'Close' column.
r1(int): r1 period.
r2(int): r2 period.
r3(int): r3 period.
r4(int): r4 period.
n1(int): n1 smoothed period.
n2(int): n2 smoothed period.
n3(int): n3 smoothed period.
n4(int): n4 smoothed period.
nsig(int): n period to signal.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return KSTIndicator(
close=close, r1=r1, r2=r2, r3=r3, r4=r4, n1=n1, n2=n2, n3=n3, n4=n4, nsig=nsig, fillna=fillna).kst_sig()
def ichimoku_conversion_line(high, low, n1=9, n2=26, visual=False, fillna=False) -> pd.Series:
"""Tenkan-sen (Conversion Line)
It identifies the trend and look for potential signals within that trend.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ichimoku_cloud
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
n1(int): n1 low period.
n2(int): n2 medium period.
visual(bool): if True, shift n2 values.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return IchimokuIndicator(
high=high, low=low, n1=n1, n2=n2, n3=52, visual=visual, fillna=fillna).ichimoku_conversion_line()
def ichimoku_base_line(high, low, n1=9, n2=26, visual=False, fillna=False) -> pd.Series:
"""Kijun-sen (Base Line)
It identifies the trend and look for potential signals within that trend.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ichimoku_cloud
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
n1(int): n1 low period.
n2(int): n2 medium period.
visual(bool): if True, shift n2 values.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return IchimokuIndicator(
high=high, low=low, n1=n1, n2=n2, n3=52, visual=visual, fillna=fillna).ichimoku_base_line()
def ichimoku_a(high, low, n1=9, n2=26, visual=False, fillna=False):
"""Ichimoku Kinkō Hyō (Ichimoku)
It identifies the trend and look for potential signals within that trend.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ichimoku_cloud
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
n1(int): n1 low period.
n2(int): n2 medium period.
visual(bool): if True, shift n2 values.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return IchimokuIndicator(high=high, low=low, n1=n1, n2=n2, n3=52, visual=visual, fillna=fillna).ichimoku_a()
def ichimoku_b(high, low, n2=26, n3=52, visual=False, fillna=False):
"""Ichimoku Kinkō Hyō (Ichimoku)
It identifies the trend and look for potential signals within that trend.
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ichimoku_cloud
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
n2(int): n2 medium period.
n3(int): n3 high period.
visual(bool): if True, shift n2 values.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return IchimokuIndicator(high=high, low=low, n1=9, n2=n2, n3=n3, visual=visual, fillna=fillna).ichimoku_b()
def aroon_up(close, n=25, fillna=False):
"""Aroon Indicator (AI)
Identify when trends are likely to change direction (uptrend).
Aroon Up - ((N - Days Since N-day High) / N) x 100
https://www.investopedia.com/terms/a/aroon.asp
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return AroonIndicator(close=close, n=n, fillna=fillna).aroon_up()
def aroon_down(close, n=25, fillna=False):
"""Aroon Indicator (AI)
Identify when trends are likely to change direction (downtrend).
Aroon Down - ((N - Days Since N-day Low) / N) x 100
https://www.investopedia.com/terms/a/aroon.asp
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
return AroonIndicator(close=close, n=n, fillna=fillna).aroon_down()
def psar_up(high, low, close, step=0.02, max_step=0.20, fillna=False):
"""Parabolic Stop and Reverse (Parabolic SAR)
Returns the PSAR series with non-N/A values for upward trends
https://school.stockcharts.com/doku.php?id=technical_indicators:parabolic_sar
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
step(float): the Acceleration Factor used to compute the SAR.
max_step(float): the maximum value allowed for the Acceleration Factor.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = PSARIndicator(high=high, low=low, close=close, step=step,
max_step=max_step, fillna=fillna)
return indicator.psar_up()
def psar_down(high, low, close, step=0.02, max_step=0.20, fillna=False):
"""Parabolic Stop and Reverse (Parabolic SAR)
Returns the PSAR series with non-N/A values for downward trends
https://school.stockcharts.com/doku.php?id=technical_indicators:parabolic_sar
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
step(float): the Acceleration Factor used to compute the SAR.
max_step(float): the maximum value allowed for the Acceleration Factor.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = PSARIndicator(high=high, low=low, close=close, step=step,
max_step=max_step, fillna=fillna)
return indicator.psar_down()
def psar_up_indicator(high, low, close, step=0.02, max_step=0.20, fillna=False):
"""Parabolic Stop and Reverse (Parabolic SAR) Upward Trend Indicator
Returns 1, if there is a reversal towards an upward trend. Else, returns 0.
https://school.stockcharts.com/doku.php?id=technical_indicators:parabolic_sar
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
step(float): the Acceleration Factor used to compute the SAR.
max_step(float): the maximum value allowed for the Acceleration Factor.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = PSARIndicator(high=high, low=low, close=close, step=step,
max_step=max_step, fillna=fillna)
return indicator.psar_up_indicator()
def psar_down_indicator(high, low, close, step=0.02, max_step=0.20, fillna=False):
"""Parabolic Stop and Reverse (Parabolic SAR) Downward Trend Indicator
Returns 1, if there is a reversal towards an downward trend. Else, returns 0.
https://school.stockcharts.com/doku.php?id=technical_indicators:parabolic_sar
Args:
high(pandas.Series): dataset 'High' column.
low(pandas.Series): dataset 'Low' column.
close(pandas.Series): dataset 'Close' column.
step(float): the Acceleration Factor used to compute the SAR.
max_step(float): the maximum value allowed for the Acceleration Factor.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New feature generated.
"""
indicator = PSARIndicator(high=high, low=low, close=close, step=step,
max_step=max_step, fillna=fillna)
return indicator.psar_down_indicator()
| 34.479138 | 112 | 0.624675 | import numpy as np
import pandas as pd
from ta.utils import IndicatorMixin, ema, get_min_max, sma
class AroonIndicator(IndicatorMixin):
def __init__(self, close: pd.Series, n: int = 25, fillna: bool = False):
self._close = close
self._n = n
self._fillna = fillna
self._run()
def _run(self):
min_periods = 0 if self._fillna else self._n
rolling_close = self._close.rolling(self._n, min_periods=min_periods)
self._aroon_up = rolling_close.apply(
lambda x: float(np.argmax(x) + 1) / self._n * 100, raw=True)
self._aroon_down = rolling_close.apply(
lambda x: float(np.argmin(x) + 1) / self._n * 100, raw=True)
def aroon_up(self) -> pd.Series:
aroon_up = self._check_fillna(self._aroon_up, value=0)
return pd.Series(aroon_up, name=f'aroon_up_{self._n}')
def aroon_down(self) -> pd.Series:
aroon_down = self._check_fillna(self._aroon_down, value=0)
return pd.Series(aroon_down, name=f'aroon_down_{self._n}')
def aroon_indicator(self) -> pd.Series:
aroon_diff = self._aroon_up - self._aroon_down
aroon_diff = self._check_fillna(aroon_diff, value=0)
return pd.Series(aroon_diff, name=f'aroon_ind_{self._n}')
class MACD(IndicatorMixin):
def __init__(self,
close: pd.Series,
n_slow: int = 26,
n_fast: int = 12,
n_sign: int = 9,
fillna: bool = False):
self._close = close
self._n_slow = n_slow
self._n_fast = n_fast
self._n_sign = n_sign
self._fillna = fillna
self._run()
def _run(self):
self._emafast = ema(self._close, self._n_fast, self._fillna)
self._emaslow = ema(self._close, self._n_slow, self._fillna)
self._macd = self._emafast - self._emaslow
self._macd_signal = ema(self._macd, self._n_sign, self._fillna)
self._macd_diff = self._macd - self._macd_signal
def macd(self) -> pd.Series:
macd = self._check_fillna(self._macd, value=0)
return pd.Series(macd, name=f'MACD_{self._n_fast}_{self._n_slow}')
def macd_signal(self) -> pd.Series:
macd_signal = self._check_fillna(self._macd_signal, value=0)
return pd.Series(macd_signal, name=f'MACD_sign_{self._n_fast}_{self._n_slow}')
def macd_diff(self) -> pd.Series:
macd_diff = self._check_fillna(self._macd_diff, value=0)
return pd.Series(macd_diff, name=f'MACD_diff_{self._n_fast}_{self._n_slow}')
class EMAIndicator(IndicatorMixin):
def __init__(self, close: pd.Series, n: int = 14, fillna: bool = False):
self._close = close
self._n = n
self._fillna = fillna
def ema_indicator(self) -> pd.Series:
ema_ = ema(self._close, self._n, self._fillna)
return pd.Series(ema_, name=f'ema_{self._n}')
class SMAIndicator(IndicatorMixin):
def __init__(self, close: pd.Series, n: int, fillna: bool = False):
self._close = close
self._n = n
self._fillna = fillna
def sma_indicator(self) -> pd.Series:
sma_ = sma(self._close, self._n, self._fillna)
return pd.Series(sma_, name=f'sma_{self._n}')
class TRIXIndicator(IndicatorMixin):
def __init__(self, close: pd.Series, n: int = 15, fillna: bool = False):
self._close = close
self._n = n
self._fillna = fillna
self._run()
def _run(self):
ema1 = ema(self._close, self._n, self._fillna)
ema2 = ema(ema1, self._n, self._fillna)
ema3 = ema(ema2, self._n, self._fillna)
self._trix = (ema3 - ema3.shift(1, fill_value=ema3.mean())) / ema3.shift(1, fill_value=ema3.mean())
self._trix *= 100
def trix(self) -> pd.Series:
trix = self._check_fillna(self._trix, value=0)
return pd.Series(trix, name=f'trix_{self._n}')
class MassIndex(IndicatorMixin):
def __init__(self, high: pd.Series, low: pd.Series, n: int = 9, n2: int = 25, fillna: bool = False):
self._high = high
self._low = low
self._n = n
self._n2 = n2
self._fillna = fillna
self._run()
def _run(self):
min_periods = 0 if self._fillna else self._n2
amplitude = self._high - self._low
ema1 = ema(amplitude, self._n, self._fillna)
ema2 = ema(ema1, self._n, self._fillna)
mass = ema1 / ema2
self._mass = mass.rolling(self._n2, min_periods=min_periods).sum()
def mass_index(self) -> pd.Series:
mass = self._check_fillna(self._mass, value=0)
return pd.Series(mass, name=f'mass_index_{self._n}_{self._n2}')
class IchimokuIndicator(IndicatorMixin):
def __init__(self, high: pd.Series, low: pd.Series, n1: int = 9, n2: int = 26, n3: int = 52,
visual: bool = False, fillna: bool = False):
self._high = high
self._low = low
self._n1 = n1
self._n2 = n2
self._n3 = n3
self._visual = visual
self._fillna = fillna
self._run()
def _run(self):
min_periods_n1 = 0 if self._fillna else self._n1
min_periods_n2 = 0 if self._fillna else self._n2
self._conv = 0.5 * (
self._high.rolling(self._n1, min_periods=min_periods_n1).max() +
self._low.rolling(self._n1, min_periods=min_periods_n1).min())
self._base = 0.5 * (
self._high.rolling(self._n2, min_periods=min_periods_n2).max() +
self._low.rolling(self._n2, min_periods=min_periods_n2).min())
def ichimoku_conversion_line(self) -> pd.Series:
conversion = self._check_fillna(self._conv, value=-1)
return pd.Series(conversion, name=f'ichimoku_conv_{self._n1}_{self._n2}')
def ichimoku_base_line(self) -> pd.Series:
base = self._check_fillna(self._base, value=-1)
return pd.Series(base, name=f'ichimoku_base_{self._n1}_{self._n2}')
def ichimoku_a(self) -> pd.Series:
spana = 0.5 * (self._conv + self._base)
spana = spana.shift(self._n2, fill_value=spana.mean()) if self._visual else spana
spana = self._check_fillna(spana, value=-1)
return pd.Series(spana, name=f'ichimoku_a_{self._n1}_{self._n2}')
def ichimoku_b(self) -> pd.Series:
spanb = 0.5 * (self._high.rolling(self._n3, min_periods=0).max()
+ self._low.rolling(self._n3, min_periods=0).min())
spanb = spanb.shift(self._n2, fill_value=spanb.mean()) if self._visual else spanb
spanb = self._check_fillna(spanb, value=-1)
return pd.Series(spanb, name=f'ichimoku_b_{self._n1}_{self._n2}')
class KSTIndicator(IndicatorMixin):
def __init__(self, close: pd.Series, r1: int = 10, r2: int = 15, r3: int = 20, r4: int = 30,
n1: int = 10, n2: int = 10, n3: int = 10, n4: int = 15, nsig: int = 9,
fillna: bool = False):
self._close = close
self._r1 = r1
self._r2 = r2
self._r3 = r3
self._r4 = r4
self._n1 = n1
self._n2 = n2
self._n3 = n3
self._n4 = n4
self._nsig = nsig
self._fillna = fillna
self._run()
def _run(self):
min_periods_n1 = 0 if self._fillna else self._n1
min_periods_n2 = 0 if self._fillna else self._n2
min_periods_n3 = 0 if self._fillna else self._n3
min_periods_n4 = 0 if self._fillna else self._n4
rocma1 = (
(self._close - self._close.shift(self._r1, fill_value=self._close.mean()))
/ self._close.shift(self._r1, fill_value=self._close.mean())).rolling(
self._n1, min_periods=min_periods_n1).mean()
rocma2 = (
(self._close - self._close.shift(self._r2, fill_value=self._close.mean()))
/ self._close.shift(self._r2, fill_value=self._close.mean())).rolling(
self._n2, min_periods=min_periods_n2).mean()
rocma3 = (
(self._close - self._close.shift(self._r3, fill_value=self._close.mean()))
/ self._close.shift(self._r3, fill_value=self._close.mean())).rolling(
self._n3, min_periods=min_periods_n3).mean()
rocma4 = (
(self._close - self._close.shift(self._r4, fill_value=self._close.mean()))
/ self._close.shift(self._r4, fill_value=self._close.mean())).rolling(
self._n4, min_periods=min_periods_n4).mean()
self._kst = 100 * (rocma1 + 2 * rocma2 + 3 * rocma3 + 4 * rocma4)
self._kst_sig = self._kst.rolling(self._nsig, min_periods=0).mean()
def kst(self) -> pd.Series:
kst = self._check_fillna(self._kst, value=0)
return pd.Series(kst, name='kst')
def kst_sig(self) -> pd.Series:
kst_sig = self._check_fillna(self._kst_sig, value=0)
return pd.Series(kst_sig, name='kst_sig')
def kst_diff(self) -> pd.Series:
kst_diff = self._kst - self._kst_sig
kst_diff = self._check_fillna(kst_diff, value=0)
return pd.Series(kst_diff, name='kst_diff')
class DPOIndicator(IndicatorMixin):
def __init__(self, close: pd.Series, n: int = 20, fillna: bool = False):
self._close = close
self._n = n
self._fillna = fillna
self._run()
def _run(self):
min_periods = 0 if self._fillna else self._n
self._dpo = (self._close.shift(int((0.5 * self._n) + 1), fill_value=self._close.mean())
- self._close.rolling(self._n, min_periods=min_periods).mean())
def dpo(self) -> pd.Series:
dpo = self._check_fillna(self._dpo, value=0)
return pd.Series(dpo, name='dpo_'+str(self._n))
class CCIIndicator(IndicatorMixin):
def __init__(self,
high: pd.Series,
low: pd.Series,
close: pd.Series,
n: int = 20,
c: float = 0.015,
fillna: bool = False):
self._high = high
self._low = low
self._close = close
self._n = n
self._c = c
self._fillna = fillna
self._run()
def _run(self):
def _mad(x):
return np.mean(np.abs(x-np.mean(x)))
min_periods = 0 if self._fillna else self._n
pp = (self._high + self._low + self._close) / 3.0
self._cci = ((pp - pp.rolling(self._n, min_periods=min_periods).mean())
/ (self._c * pp.rolling(self._n, min_periods=min_periods).apply(_mad, True)))
def cci(self) -> pd.Series:
cci = self._check_fillna(self._cci, value=0)
return pd.Series(cci, name='cci')
class ADXIndicator(IndicatorMixin):
def __init__(self, high: pd.Series, low: pd.Series, close: pd.Series, n: int = 14, fillna: bool = False):
self._high = high
self._low = low
self._close = close
self._n = n
self._fillna = fillna
self._run()
def _run(self):
assert self._n != 0, "N may not be 0 and is %r" % n
cs = self._close.shift(1)
pdm = get_min_max(self._high, cs, 'max')
pdn = get_min_max(self._low, cs, 'min')
tr = pdm - pdn
self._trs_initial = np.zeros(self._n-1)
self._trs = np.zeros(len(self._close) - (self._n - 1))
self._trs[0] = tr.dropna()[0:self._n].sum()
tr = tr.reset_index(drop=True)
for i in range(1, len(self._trs)-1):
self._trs[i] = self._trs[i-1] - (self._trs[i-1]/float(self._n)) + tr[self._n+i]
up = self._high - self._high.shift(1)
dn = self._low.shift(1) - self._low
pos = abs(((up > dn) & (up > 0)) * up)
neg = abs(((dn > up) & (dn > 0)) * dn)
self._dip = np.zeros(len(self._close) - (self._n - 1))
self._dip[0] = pos.dropna()[0:self._n].sum()
pos = pos.reset_index(drop=True)
for i in range(1, len(self._dip)-1):
self._dip[i] = self._dip[i-1] - (self._dip[i-1]/float(self._n)) + pos[self._n+i]
self._din = np.zeros(len(self._close) - (self._n - 1))
self._din[0] = neg.dropna()[0:self._n].sum()
neg = neg.reset_index(drop=True)
for i in range(1, len(self._din)-1):
self._din[i] = self._din[i-1] - (self._din[i-1]/float(self._n)) + neg[self._n+i]
def adx(self) -> pd.Series:
dip = np.zeros(len(self._trs))
for i in range(len(self._trs)):
dip[i] = 100 * (self._dip[i]/self._trs[i])
din = np.zeros(len(self._trs))
for i in range(len(self._trs)):
din[i] = 100 * (self._din[i]/self._trs[i])
dx = 100 * np.abs((dip - din) / (dip + din))
adx = np.zeros(len(self._trs))
adx[self._n] = dx[0:self._n].mean()
for i in range(self._n+1, len(adx)):
adx[i] = ((adx[i-1] * (self._n - 1)) + dx[i-1]) / float(self._n)
adx = np.concatenate((self._trs_initial, adx), axis=0)
self._adx = pd.Series(data=adx, index=self._close.index)
adx = self._check_fillna(self._adx, value=20)
return pd.Series(adx, name='adx')
def adx_pos(self) -> pd.Series:
dip = np.zeros(len(self._close))
for i in range(1, len(self._trs)-1):
dip[i+self._n] = 100 * (self._dip[i]/self._trs[i])
adx_pos = self._check_fillna(pd.Series(dip, index=self._close.index), value=20)
return pd.Series(adx_pos, name='adx_pos')
def adx_neg(self) -> pd.Series:
din = np.zeros(len(self._close))
for i in range(1, len(self._trs)-1):
din[i+self._n] = 100 * (self._din[i]/self._trs[i])
adx_neg = self._check_fillna(pd.Series(din, index=self._close.index), value=20)
return pd.Series(adx_neg, name='adx_neg')
class VortexIndicator(IndicatorMixin):
def __init__(self, high: pd.Series, low: pd.Series, close: pd.Series, n: int = 14, fillna: bool = False):
self._high = high
self._low = low
self._close = close
self._n = n
self._fillna = fillna
self._run()
def _run(self):
cs = self._close.shift(1, fill_value=self._close.mean())
tr = self._true_range(self._high, self._low, cs)
min_periods = 0 if self._fillna else self._n
trn = tr.rolling(self._n, min_periods=min_periods).sum()
vmp = np.abs(self._high - self._low.shift(1))
vmm = np.abs(self._low - self._high.shift(1))
self._vip = vmp.rolling(self._n, min_periods=min_periods).sum() / trn
self._vin = vmm.rolling(self._n, min_periods=min_periods).sum() / trn
def vortex_indicator_pos(self):
vip = self._check_fillna(self._vip, value=1)
return pd.Series(vip, name='vip')
def vortex_indicator_neg(self):
vin = self._check_fillna(self._vin, value=1)
return pd.Series(vin, name='vin')
def vortex_indicator_diff(self):
vid = self._vip - self._vin
vid = self._check_fillna(vid, value=0)
return pd.Series(vid, name='vid')
class PSARIndicator(IndicatorMixin):
def __init__(self, high: pd.Series, low: pd.Series, close: pd.Series,
step: float = 0.02, max_step: float = 0.20,
fillna: bool = False):
self._high = high
self._low = low
self._close = close
self._step = step
self._max_step = max_step
self._fillna = fillna
self._run()
def _run(self):
up_trend = True
af = self._step
up_trend_high = self._high.iloc[0]
down_trend_low = self._low.iloc[0]
self._psar = self._close.copy()
self._psar_up = pd.Series(index=self._psar.index)
self._psar_down = pd.Series(index=self._psar.index)
for i in range(2, len(self._close)):
reversal = False
max_high = self._high.iloc[i]
min_low = self._low.iloc[i]
if up_trend:
self._psar.iloc[i] = self._psar.iloc[i-1] + (
af * (up_trend_high - self._psar.iloc[i-1]))
if min_low < self._psar.iloc[i]:
reversal = True
self._psar.iloc[i] = up_trend_high
down_trend_low = min_low
af = self._step
else:
if max_high > up_trend_high:
up_trend_high = max_high
af = min(af + self._step, self._max_step)
l1 = self._low.iloc[i-1]
l2 = self._low.iloc[i-2]
if l2 < self._psar.iloc[i]:
self._psar.iloc[i] = l2
elif l1 < self._psar.iloc[i]:
self._psar.iloc[i] = l1
else:
self._psar.iloc[i] = self._psar.iloc[i-1] - (
af * (self._psar.iloc[i-1] - down_trend_low))
if max_high > self._psar.iloc[i]:
reversal = True
self._psar.iloc[i] = down_trend_low
up_trend_high = max_high
af = self._step
else:
if min_low < down_trend_low:
down_trend_low = min_low
af = min(af + self._step, self._max_step)
h1 = self._high.iloc[i-1]
h2 = self._high.iloc[i-2]
if h2 > self._psar.iloc[i]:
self._psar[i] = h2
elif h1 > self._psar.iloc[i]:
self._psar.iloc[i] = h1
up_trend = up_trend != reversal
if up_trend:
self._psar_up.iloc[i] = self._psar.iloc[i]
else:
self._psar_down.iloc[i] = self._psar.iloc[i]
def psar(self) -> pd.Series:
psar = self._check_fillna(self._psar, value=-1)
return pd.Series(psar, name='psar')
def psar_up(self) -> pd.Series:
psar_up = self._check_fillna(self._psar_up, value=-1)
return pd.Series(psar_up, name='psarup')
def psar_down(self) -> pd.Series:
psar_down = self._check_fillna(self._psar_down, value=-1)
return pd.Series(psar_down, name='psardown')
def psar_up_indicator(self) -> pd.Series:
indicator = self._psar_up.where(self._psar_up.notnull()
& self._psar_up.shift(1).isnull(), 0)
indicator = indicator.where(indicator == 0, 1)
return pd.Series(indicator, index=self._close.index, name='psariup')
def psar_down_indicator(self) -> pd.Series:
indicator = self._psar_up.where(self._psar_down.notnull()
& self._psar_down.shift(1).isnull(), 0)
indicator = indicator.where(indicator == 0, 1)
return pd.Series(indicator, index=self._close.index, name='psaridown')
def ema_indicator(close, n=12, fillna=False):
return EMAIndicator(close=close, n=n, fillna=fillna).ema_indicator()
def sma_indicator(close, n=12, fillna=False):
return SMAIndicator(close=close, n=n, fillna=fillna).sma_indicator()
def macd(close, n_slow=26, n_fast=12, fillna=False):
return MACD(close=close, n_slow=n_slow, n_fast=n_fast, n_sign=9, fillna=fillna).macd()
def macd_signal(close, n_slow=26, n_fast=12, n_sign=9, fillna=False):
return MACD(close=close, n_slow=n_slow, n_fast=n_fast, n_sign=n_sign, fillna=fillna).macd_signal()
def macd_diff(close, n_slow=26, n_fast=12, n_sign=9, fillna=False):
return MACD(close=close, n_slow=n_slow, n_fast=n_fast, n_sign=n_sign, fillna=fillna).macd_diff()
def adx(high, low, close, n=14, fillna=False):
return ADXIndicator(high=high, low=low, close=close, n=n, fillna=fillna).adx()
def adx_pos(high, low, close, n=14, fillna=False):
return ADXIndicator(high=high, low=low, close=close, n=n, fillna=fillna).adx_pos()
def adx_neg(high, low, close, n=14, fillna=False):
return ADXIndicator(high=high, low=low, close=close, n=n, fillna=fillna).adx_neg()
def vortex_indicator_pos(high, low, close, n=14, fillna=False):
return VortexIndicator(high=high, low=low, close=close, n=n, fillna=fillna).vortex_indicator_pos()
def vortex_indicator_neg(high, low, close, n=14, fillna=False):
return VortexIndicator(high=high, low=low, close=close, n=n, fillna=fillna).vortex_indicator_neg()
def trix(close, n=15, fillna=False):
return TRIXIndicator(close=close, n=n, fillna=fillna).trix()
def mass_index(high, low, n=9, n2=25, fillna=False):
return MassIndex(high=high, low=low, n=n, n2=n2, fillna=fillna).mass_index()
def cci(high, low, close, n=20, c=0.015, fillna=False):
return CCIIndicator(high=high, low=low, close=close, n=n, c=c, fillna=fillna).cci()
def dpo(close, n=20, fillna=False):
return DPOIndicator(close=close, n=n, fillna=fillna).dpo()
def kst(close, r1=10, r2=15, r3=20, r4=30, n1=10, n2=10, n3=10, n4=15, fillna=False):
return KSTIndicator(
close=close, r1=r1, r2=r2, r3=r3, r4=r4, n1=n1, n2=n2, n3=n3, n4=n4, nsig=9, fillna=fillna).kst()
def kst_sig(close, r1=10, r2=15, r3=20, r4=30, n1=10, n2=10, n3=10, n4=15, nsig=9, fillna=False):
return KSTIndicator(
close=close, r1=r1, r2=r2, r3=r3, r4=r4, n1=n1, n2=n2, n3=n3, n4=n4, nsig=nsig, fillna=fillna).kst_sig()
def ichimoku_conversion_line(high, low, n1=9, n2=26, visual=False, fillna=False) -> pd.Series:
return IchimokuIndicator(
high=high, low=low, n1=n1, n2=n2, n3=52, visual=visual, fillna=fillna).ichimoku_conversion_line()
def ichimoku_base_line(high, low, n1=9, n2=26, visual=False, fillna=False) -> pd.Series:
return IchimokuIndicator(
high=high, low=low, n1=n1, n2=n2, n3=52, visual=visual, fillna=fillna).ichimoku_base_line()
def ichimoku_a(high, low, n1=9, n2=26, visual=False, fillna=False):
return IchimokuIndicator(high=high, low=low, n1=n1, n2=n2, n3=52, visual=visual, fillna=fillna).ichimoku_a()
def ichimoku_b(high, low, n2=26, n3=52, visual=False, fillna=False):
return IchimokuIndicator(high=high, low=low, n1=9, n2=n2, n3=n3, visual=visual, fillna=fillna).ichimoku_b()
def aroon_up(close, n=25, fillna=False):
return AroonIndicator(close=close, n=n, fillna=fillna).aroon_up()
def aroon_down(close, n=25, fillna=False):
return AroonIndicator(close=close, n=n, fillna=fillna).aroon_down()
def psar_up(high, low, close, step=0.02, max_step=0.20, fillna=False):
indicator = PSARIndicator(high=high, low=low, close=close, step=step,
max_step=max_step, fillna=fillna)
return indicator.psar_up()
def psar_down(high, low, close, step=0.02, max_step=0.20, fillna=False):
indicator = PSARIndicator(high=high, low=low, close=close, step=step,
max_step=max_step, fillna=fillna)
return indicator.psar_down()
def psar_up_indicator(high, low, close, step=0.02, max_step=0.20, fillna=False):
indicator = PSARIndicator(high=high, low=low, close=close, step=step,
max_step=max_step, fillna=fillna)
return indicator.psar_up_indicator()
def psar_down_indicator(high, low, close, step=0.02, max_step=0.20, fillna=False):
indicator = PSARIndicator(high=high, low=low, close=close, step=step,
max_step=max_step, fillna=fillna)
return indicator.psar_down_indicator()
| true | true |
f73bcf9c573fc1a2d38793abf9f74c5ab13b74b0 | 414 | py | Python | migrations/versions/008_Add_deleted_flag_to_batch.py | LCBRU/batch_demographics | e516e958091fd74dad00b1705431ac030e3c4503 | [
"MIT"
] | null | null | null | migrations/versions/008_Add_deleted_flag_to_batch.py | LCBRU/batch_demographics | e516e958091fd74dad00b1705431ac030e3c4503 | [
"MIT"
] | null | null | null | migrations/versions/008_Add_deleted_flag_to_batch.py | LCBRU/batch_demographics | e516e958091fd74dad00b1705431ac030e3c4503 | [
"MIT"
] | null | null | null | from sqlalchemy import MetaData, Table, Column, Boolean
meta = MetaData()
def upgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
batch = Table("batch", meta, autoload=True)
deleted = Column("deleted", Boolean())
deleted.create(batch)
def downgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
batch = Table("batch", meta, autoload=True)
batch.c.deleted.drop() | 23 | 55 | 0.705314 | from sqlalchemy import MetaData, Table, Column, Boolean
meta = MetaData()
def upgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
batch = Table("batch", meta, autoload=True)
deleted = Column("deleted", Boolean())
deleted.create(batch)
def downgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
batch = Table("batch", meta, autoload=True)
batch.c.deleted.drop() | true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.