hexsha stringlengths 40 40 | size int64 5 2.06M | ext stringclasses 10 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 248 | max_stars_repo_name stringlengths 5 125 | max_stars_repo_head_hexsha stringlengths 40 78 | 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 3 248 | max_issues_repo_name stringlengths 5 125 | max_issues_repo_head_hexsha stringlengths 40 78 | 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 3 248 | max_forks_repo_name stringlengths 5 125 | max_forks_repo_head_hexsha stringlengths 40 78 | 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 5 2.06M | avg_line_length float64 1 1.02M | max_line_length int64 3 1.03M | alphanum_fraction float64 0 1 | count_classes int64 0 1.6M | score_classes float64 0 1 | count_generators int64 0 651k | score_generators float64 0 1 | count_decorators int64 0 990k | score_decorators float64 0 1 | count_async_functions int64 0 235k | score_async_functions float64 0 1 | count_documentation int64 0 1.04M | score_documentation float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b39c43d0021d178a258b637ee9621caf69f2c4a1 | 230 | py | Python | nsot/util/__init__.py | BunkersCo/nsot | fd45bdf63794aa3015a87855f4d7b03663fd5396 | [
"Apache-2.0"
] | null | null | null | nsot/util/__init__.py | BunkersCo/nsot | fd45bdf63794aa3015a87855f4d7b03663fd5396 | [
"Apache-2.0"
] | null | null | null | nsot/util/__init__.py | BunkersCo/nsot | fd45bdf63794aa3015a87855f4d7b03663fd5396 | [
"Apache-2.0"
] | null | null | null | """
Utilities used across the project.
"""
# Core
from . import core
from .core import * # noqa
# Stats
from . import stats
from .stats import * # noqa
__all__ = []
__all__.extend(core.__all__)
__all__.extend(stats.__all__)
| 13.529412 | 34 | 0.695652 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 67 | 0.291304 |
b39c9e2bf74b1b8f308baab389017a73fc014199 | 1,829 | py | Python | task3/test_openbrewerydb.py | rokimaru/rest_api_autotests | d4009b813b064681250671ec515646dc3554bc5d | [
"Apache-2.0"
] | null | null | null | task3/test_openbrewerydb.py | rokimaru/rest_api_autotests | d4009b813b064681250671ec515646dc3554bc5d | [
"Apache-2.0"
] | null | null | null | task3/test_openbrewerydb.py | rokimaru/rest_api_autotests | d4009b813b064681250671ec515646dc3554bc5d | [
"Apache-2.0"
] | null | null | null | """ Тесты api сайта https://www.openbrewerydb.org/ """
import pytest
import requests
from task3.methods import BrewerySiteMethods
class TestJsonPlaceholderSite:
""" Тесты api сайта https://www.openbrewerydb.org/ """
def test_openbrewerydb_1(self):
""" Проверка, что общее количество пивоварен на 1 странице = 20 """
response = requests.get('https://api.openbrewerydb.org/breweries').json()
assert len(response) == 20
def test_openbrewerydb_2(self, brewery_type):
""" Проверка фильтрации по brewery_type"""
response = requests.get('https://api.openbrewerydb.org/breweries?by_type=' + brewery_type)
assert response.status_code == 200
assert response.json()[0]["brewery_type"] == brewery_type
def test_openbrewerydb_3(self, brewery_name):
""" Проверка, фильтрации пивоварен по name """
response = requests.get("https://api.openbrewerydb.org/breweries?by_name=" + brewery_name)
assert response.status_code == 200
assert brewery_name in response.json()[0]["name"]
def test_openbrewerydb_4(self, brewery_id):
""" Проверяем, что можно получить инфо о любой пивоварне по id.
Тест через фикстуру."""
response = BrewerySiteMethods.request_brewery_information(brewery_id)
assert response.status_code == 200
assert response.json()["id"] == brewery_id
@pytest.mark.parametrize('ids_param', BrewerySiteMethods.get_all_breweries_id())
def test_openbrewerydb_5(self, ids_param):
""" Проверяем, что можно получить инфо о любой пивоварне по id.
Тест через маркер pytest"""
response = requests.get('https://api.openbrewerydb.org/breweries/' + str(ids_param))
assert response.status_code == 200
assert response.json()["id"] == ids_param
| 43.547619 | 98 | 0.686714 | 1,923 | 0.930334 | 0 | 0 | 486 | 0.235123 | 0 | 0 | 925 | 0.447508 |
b39cb5201c7a38f1f515f5662f4f1cce6e5fd7c3 | 1,347 | py | Python | TVQAplus/eval/utils.py | slewyh/vqa | b34d86d8db2f371e2d4cf55439ebaa83ae1918aa | [
"MIT"
] | 80 | 2019-05-27T14:05:31.000Z | 2021-12-13T12:16:11.000Z | TVQAplus/eval/utils.py | slewyh/vqa | b34d86d8db2f371e2d4cf55439ebaa83ae1918aa | [
"MIT"
] | 21 | 2019-05-27T14:08:23.000Z | 2022-01-03T04:02:25.000Z | eval/utils.py | Lee-Ft/RHA | 8a832a9afebc9204148bbd340c31e26c83138024 | [
"MIT"
] | 24 | 2019-09-05T03:27:14.000Z | 2021-06-30T12:15:40.000Z | import json
try:
import cPickle as pickle
except:
import pickle
def save_json(data, file_path):
with open(file_path, "w") as f:
json.dump(data, f)
def save_json_pretty(data, file_path):
"""save formatted json, use this one for some json config files"""
with open(file_path, "w") as f:
f.write(json.dumps(data, indent=4, sort_keys=True))
def load_json(file_path):
with open(file_path, "r") as f:
return json.load(f)
def save_pickle(data, data_path, highest=False):
protocol = 2 if highest else 0
with open(data_path, "w") as f:
pickle.dump(data, f, protocol=protocol)
def load_pickle(pickle_file):
try:
with open(pickle_file, 'rb') as f:
pickle_data = pickle.load(f)
except UnicodeDecodeError as e:
with open(pickle_file, 'rb') as f:
pickle_data = pickle.load(f, encoding='latin1')
except Exception as e:
print('Unable to load data ', pickle_file, ':', e)
raise
return pickle_data
def flat_list_of_lists(l):
"""flatten a list of lists [[1,2], [3,4]] to [1,2,3,4]"""
return [item for sublist in l for item in sublist]
def merge_dicts(list_dicts):
merged_dict = list_dicts[0].copy()
for i in range(1, len(list_dicts)):
merged_dict.update(list_dicts[i])
return merged_dict
| 25.415094 | 70 | 0.643653 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 176 | 0.130661 |
b39d2f478b8d05032480b473417744f719f3f2ee | 1,966 | py | Python | apps/finance_request/models.py | MegaSoftVision/finance_credit | a4350f525cd45b1e40d0a8be0ca1f3d77fdbe039 | [
"MIT"
] | null | null | null | apps/finance_request/models.py | MegaSoftVision/finance_credit | a4350f525cd45b1e40d0a8be0ca1f3d77fdbe039 | [
"MIT"
] | null | null | null | apps/finance_request/models.py | MegaSoftVision/finance_credit | a4350f525cd45b1e40d0a8be0ca1f3d77fdbe039 | [
"MIT"
] | null | null | null | from django.db import models
from apps.users.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
class Client(models.Model):
GOOD = 'gd'
REGULAR = 'rg'
BAD = 'bd'
NULL = 'nl'
DEBT_SCORE_CHOICES = [
(GOOD, 'Bueno'),
(REGULAR, 'Regular'),
(BAD, 'Malo'),
(NULL, 'Nulo'),
]
id = models.AutoField(primary_key=True, unique=True)
first_name = models.CharField('Nombre Completo', max_length=30)
last_name = models.CharField('Apellidos', max_length=30)
email = models.EmailField('Correo Electronico', unique=True)
debt_mount = models.IntegerField(
'Monto de la deuda',
default=0,
validators=[MinValueValidator(0)]
)
debt_score = models.CharField(
'Puntuación de la deuda',
max_length=2,
choices=DEBT_SCORE_CHOICES,
default=NULL
)
artificial_indicator = models.IntegerField(
'Indicador Artificial',
default=1,
validators=[MaxValueValidator(10), MinValueValidator(1)]
)
class Meta:
verbose_name = 'Cliente'
verbose_name_plural = 'Clientes'
REQUIRED_FIELDS = ['__all__']
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class RequestCredit(models.Model):
id = models.AutoField(primary_key=True)
client = models.ForeignKey(Client, related_name='requests_credits', on_delete=models.CASCADE)
request_mount = models.IntegerField(
'Monto de la solicitud',
default=1,
validators=[MaxValueValidator(50000), MinValueValidator(1)]
)
is_approved = models.BooleanField('Aprobado?', default=False)
class Meta:
verbose_name = 'Solicitud'
verbose_name_plural = 'Solicitudes'
REQUIRED_FIELDS = ['__all__']
def __str__(self):
return f'Cliente: {self.client.first_name} {self.client.last_name} - Solicitud de: {self.request_mount}'
| 29.343284 | 112 | 0.65412 | 1,824 | 0.9273 | 0 | 0 | 0 | 0 | 0 | 0 | 375 | 0.190646 |
b39fb66c9264ab0daee2f5939dd75f3e42854c9f | 938 | py | Python | Code/mreset.py | andrewwhipple/MeowgicMatt | 189c2c90a75eeb9c53d3be03c40f6b5792ceb548 | [
"MIT"
] | null | null | null | Code/mreset.py | andrewwhipple/MeowgicMatt | 189c2c90a75eeb9c53d3be03c40f6b5792ceb548 | [
"MIT"
] | null | null | null | Code/mreset.py | andrewwhipple/MeowgicMatt | 189c2c90a75eeb9c53d3be03c40f6b5792ceb548 | [
"MIT"
] | null | null | null | #Meowgic Matt reset module
import os
import json
#Debug function to call out that the module successfully loaded.
def meow():
print("mreset loaded")
#Resets Meowgic Matt to factory conditions, DELETING EVERYTHING CURRENTLY IN SUBFOLDERS.
def reset():
os.system("rm -rf ../Edited/")
os.system("rm -rf ../Published/")
os.system("rm -rf ../Queue/")
os.system("rm -rf ../Raw/")
os.system("rm -rf ../RSS/")
os.system("rm -rf ../Data/")
with open("dataStore.json", "r") as dataReadFile:
data = json.load(dataReadFile)
podcasts = data["podcasts"]
for cast in podcasts:
os.system("rm -rf " + cast + "/")
dataReadFile.close()
with open("dataStore.json", "w") as dataWriteFile:
resetDataString = '{"Setup Required":"true","podcasts":[]}'
dataWriteFile.write(resetDataString)
dataWriteFile.close()
print "\nMeowgic Matt Reset!\n" | 33.5 | 91 | 0.621535 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 430 | 0.458422 |
b3a08e780fd80323f4995b454d6b15261e415287 | 1,898 | py | Python | minecraftQuest.py | prathimacode-hub/Toonslate-Gags | fc7868c64d8b2694f2110fe8c941a0f311127e72 | [
"MIT"
] | 2 | 2021-07-12T10:36:42.000Z | 2021-07-17T04:39:20.000Z | minecraftQuest.py | prathimacode-hub/Toonslate-Gags | fc7868c64d8b2694f2110fe8c941a0f311127e72 | [
"MIT"
] | null | null | null | minecraftQuest.py | prathimacode-hub/Toonslate-Gags | fc7868c64d8b2694f2110fe8c941a0f311127e72 | [
"MIT"
] | 2 | 2021-07-11T12:56:07.000Z | 2021-07-14T17:40:54.000Z | # Setup
opt = ["yes", "no"]
directions = ["left", "right", "forward", "backward"]
# Introduction
name = input("What is your name, HaCKaToOnEr ?\n")
print("Welcome to Toonslate island , " + name + " Let us go on a Minecraft quest!")
print("You find yourself in front of a abandoned mineshaft.")
print("Can you find your way to explore the shaft and find the treasure chest ?\n")
# Start of game
response = ""
while response not in opt:
response = input("Would you like to go inside the Mineshaft?\nyes/no\n")
if response == "yes":
print("You head into the Mineshaft. You hear grumbling sound of zombies,hissing sound of spidersand rattling of skeletons.\n")
elif response == "no":
print("You are not ready for this quest. Goodbye, " + name + ".")
quit()
else:
print("I didn't understand that.\n")
# Next part of game
response = ""
while response not in directions:
print("To your left, you see a skeleton with a golden armor and a bow .")
print("To your right, there is a way to go more inside the shaft.")
print("There is a cobble stone wall directly in front of you.")
print("Behind you is the mineshaft exit.\n")
response = input("What direction would you like to move?\nleft/right/forward/backward\n")
if response == "left":
print(name+" was shot by an arrow. Farewell :( ")
quit()
elif response == "right":
print("You head deeper into the mineshaft and find the treasure chest ,Kudos!!!.\n")
elif response == "forward":
print("You broke the stone walls and find out it was a spider spawner, spiders slain you to deeath\n")
response = ""
elif response == "backward":
print("You leave the mineshaft un explored . Goodbye, " + name + ".")
quit()
else:
print("I didn't understand that.\n")
| 43.136364 | 135 | 0.632771 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,214 | 0.639621 |
b3a4f4d01102f6664e5c9be202321811c9c3c51b | 2,385 | py | Python | soundbay/utils/checkpoint_utils.py | deep-voice/soundbay | eb19b9932fab0c909c8e9c0627d29dfcd752c18c | [
"Apache-2.0"
] | 7 | 2021-07-29T09:44:20.000Z | 2022-02-01T20:01:05.000Z | soundbay/utils/checkpoint_utils.py | mosheman5/soundbay | eb19b9932fab0c909c8e9c0627d29dfcd752c18c | [
"Apache-2.0"
] | 13 | 2021-04-19T05:56:30.000Z | 2022-02-09T09:37:36.000Z | soundbay/utils/checkpoint_utils.py | deep-voice/soundbay | eb19b9932fab0c909c8e9c0627d29dfcd752c18c | [
"Apache-2.0"
] | 2 | 2021-04-06T06:32:24.000Z | 2022-01-22T16:37:29.000Z | from typing import Union
import boto3
from omegaconf import OmegaConf
from pathlib import Path
from tqdm import tqdm
def walk(input_path):
"""
helper function to yield folder's file content
Input:
input_path: the path of the folder
Output:
generator of files in directory tree
"""
for p in Path(input_path).iterdir():
if p.is_dir():
yield from walk(p)
continue
yield p.resolve()
def upload_experiment_to_s3(experiment_id: str,
dir_path: Union[Path, str],
bucket_name: str,
include_parent: bool = True):
"""
Uploads the experiment folder to s3 bucket
Input:
experiment_id: id of the experiment, taken usually from wandb logger
dir_path: path to the experiment directory
bucket_name: name of the desired bucket path
include_parent: flag to include the parent of the experiment folder while saving to s3
"""
dir_path = Path(dir_path)
assert dir_path.is_dir(), 'should upload experiments as directories to s3!'
object_global = f'{experiment_id}/{dir_path.parent.name}/{dir_path.name}' if include_parent \
else f'{experiment_id}/{dir_path.name}'
current_global = str(dir_path.resolve())
upload_files = list(walk(dir_path))
s3_client = boto3.client('s3')
for upload_file in tqdm(upload_files):
upload_file = str(upload_file)
s3_client.upload_file(upload_file, bucket_name, upload_file.replace(current_global, object_global))
def merge_with_checkpoint(run_args, checkpoint_args):
"""
Merge into current args the needed arguments from checkpoint
Right now we select the specific modules needed, can make it more generic if we'll see the need for it
Input:
run_args: dict_config of run args
checkpoint_args: dict_config of checkpoint args
Output:
run_args: updated dict_config of run args
"""
OmegaConf.set_struct(run_args, False)
run_args.model = OmegaConf.to_container(checkpoint_args.model, resolve=True)
run_args.data.test_dataset.preprocessors = OmegaConf.to_container(checkpoint_args.data.train_dataset.preprocessors, resolve=True)
run_args.data.sample_rate = checkpoint_args.data.sample_rate
OmegaConf.set_struct(run_args, True)
return run_args | 37.857143 | 133 | 0.692243 | 0 | 0 | 341 | 0.142977 | 0 | 0 | 0 | 0 | 1,016 | 0.425996 |
b3a5e848fef8a886c8da89c6bdd2489931204aef | 446 | py | Python | rubicon_ml/viz/__init__.py | fdosani/rubicon-ml | b6dbd3ea44afb297a224baec387712fdf65b5b4f | [
"Apache-2.0"
] | null | null | null | rubicon_ml/viz/__init__.py | fdosani/rubicon-ml | b6dbd3ea44afb297a224baec387712fdf65b5b4f | [
"Apache-2.0"
] | null | null | null | rubicon_ml/viz/__init__.py | fdosani/rubicon-ml | b6dbd3ea44afb297a224baec387712fdf65b5b4f | [
"Apache-2.0"
] | null | null | null | from rubicon_ml.viz.dashboard import Dashboard
from rubicon_ml.viz.dataframe_plot import DataframePlot
from rubicon_ml.viz.experiments_table import ExperimentsTable
from rubicon_ml.viz.metric_correlation_plot import MetricCorrelationPlot
from rubicon_ml.viz.metric_lists_comparison import MetricListsComparison
__all__ = [
"Dashboard",
"DataframePlot",
"ExperimentsTable",
"MetricListsComparison",
"MetricCorrelationPlot",
]
| 31.857143 | 72 | 0.825112 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 90 | 0.201794 |
b3a7d113a7a33eaf4860294977fa40757e49a7a5 | 1,609 | py | Python | run.py | CjwRiver/apiAutoTest | 35f1c2475e76dd34089e2cee33b351a1ca97c168 | [
"MIT"
] | null | null | null | run.py | CjwRiver/apiAutoTest | 35f1c2475e76dd34089e2cee33b351a1ca97c168 | [
"MIT"
] | null | null | null | run.py | CjwRiver/apiAutoTest | 35f1c2475e76dd34089e2cee33b351a1ca97c168 | [
"MIT"
] | null | null | null | from test.conftest import pytest
from tools import logger
from tools.read_file import ReadFile
from tools.send_email import EmailServe
import os
import shutil
report = ReadFile.read_config('$.file_path.report')
logfile = ReadFile.read_config('$.file_path.log')
file_path = ReadFile.read_config('$.file_path')
email = ReadFile.read_config('$.email')
def run():
if os.path.exists('report/'):
shutil.rmtree(path='report/')
logger.add(logfile, enqueue=True, encoding='utf-8')
# logger.add(file_path['log'], enqueue=True, encoding='utf-8')
logger.info("""
_ _
| | (_)
_ _ _ _ _ __ ___| |__ ___ ___ _ _ __
| | | | | | | '_ \/ __| '_ \| \ \/ / | | | '_ \
| |_| | |_| | | | \__ \ | | | |> <| |_| | | | |
\__, |\__,_|_| |_|___/_| |_|_/_/\_\\__,_|_| |_|
__/ |
|___/
""")
pytest.main(args=['test/test_api.py', f'--alluredir={report}/data'])
pytest.main(args=['test/test_api.py', f'--alluredir={file_path["report"]}/data'])
# 自动以服务形式打开报告
# os.system(f'allure serve {report}/data')
# 本地生成报告
os.system(f'allure generate {report}/data -o {report}/html --clean')
os.system(f'allure generate {file_path["report"]}/data -o {file_path["report"]}/html --clean')
logger.success('报告已生成')
# 发送邮件带附件报告
# EmailServe.send_email(email, file_path['report'])
# if __name__ == '__main__':
# run()
# # 删除本地附件
# os.remove(email['enclosures'])
if __name__ == '__main__':
run() | 32.836735 | 98 | 0.551274 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,086 | 0.645276 |
b3a818e615b2f988b30047093f25d5ce862b5e70 | 7,658 | py | Python | database/models/util.py | henryzzz093/data_pipeline2 | 5ac5ea2d48f495e0346d8e5198f44baf31af7d9a | [
"MIT"
] | null | null | null | database/models/util.py | henryzzz093/data_pipeline2 | 5ac5ea2d48f495e0346d8e5198f44baf31af7d9a | [
"MIT"
] | null | null | null | database/models/util.py | henryzzz093/data_pipeline2 | 5ac5ea2d48f495e0346d8e5198f44baf31af7d9a | [
"MIT"
] | 1 | 2021-08-16T00:40:01.000Z | 2021-08-16T00:40:01.000Z | import sqlalchemy as sa
import numpy as np
import datetime as dt
from faker import Faker
from jinja2 import Environment, PackageLoader
from database.models.core import (
Base,
Products,
Customers,
TransactionDetails,
Transactions,
)
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
PRODUCT_LIST = [
{"name": "hat", "price": 10.99},
{"name": "cap", "price": 6.99},
{"name": "shirt", "price": 50.99},
{"name": "sweater", "price": 69.99},
{"name": "shorts", "price": 49.99},
{"name": "jeans", "price": 39.99},
{"name": "neakers", "price": 32.99},
{"name": "boots", "price": 199.99},
{"name": "coats", "price": 249.99},
{"name": "accessories", "price": 149.99},
]
class DBConn:
def __init__(self, **kwargs):
"""
initialize the attributes of a class.
"""
self.host = kwargs.get("host", "host.docker.internal")
self.username = kwargs.get("username", "henry")
self.password = kwargs.get("password", "henry")
self.database = kwargs.get("database", "henry")
self.schema = kwargs.get("schema", "henry")
self.log = logger
def _get_conn_str(self, database_type):
"""
return the connection string based on database types
"""
if database_type == "postgres":
dbapi = "postgresql"
port = 5438
elif database_type == "mysql":
dbapi = "mysql+pymysql"
port = 3307
return f"{dbapi}://{self.username}:{self.password}@{self.host}:{port}" # noqa: E501
def get_conn(self, database_type):
"""
setup the connection to database
"""
conn_str = self._get_conn_str(database_type)
connection = sa.create_engine(conn_str, echo=True)
return connection
@property
def _database_types(self):
return ["mysql", "postgres"]
def get_session(self, database_type):
conn = self.get_conn(database_type)
Session = sa.orm.sessionmaker(bind=conn)
return Session()
class DataGenerator:
def __init__(self):
self.fake = Faker()
def _get_dates(self):
start_date = dt.date(2021, 1, 1) # set the start date
end_date = dt.datetime.now().date() # set the end date
diff = (end_date - start_date).days # calculate the delta
for i in range(0, diff):
date = start_date + dt.timedelta(days=i) # get each of the data
date = date.strftime("%Y-%m-%d") # convert it into datetime string
yield date
@property
def _name(self):
return self.fake.name()
@property
def _address(self):
return self.fake.address()
@property
def _phone(self):
return self.fake.phone_number()
def _get_email(self, name):
first_name = name.split()[0]
last_name = name.split()[-1]
index = np.random.randint(0, 3)
domains = ["gmail", "yahoo", "outlook"]
email = f"{first_name}.{last_name}@{domains[index]}.com"
return email.lower()
@property
def _product_id(self):
product_ids = list(
range(1, len(PRODUCT_LIST) + 1)
) # a list of [0, ... len(Product_list)+1]
index = np.random.randint(0, len(product_ids))
return product_ids[
index
] # return a random number from 0 to length of string
@property
def _quantity(self):
return np.random.randint(1, 10)
def get_data(self):
for date in self._get_dates():
for _ in range(np.random.randint(1, 15)):
name = self._name
data = {
"customers": {
"name": name,
"address": self._address,
"phone": self._phone,
"email": self._get_email(name),
},
"transactions": {
"transaction_date": date,
},
"transaction_details": {
"product_id": self._product_id,
"quantity": np.random.randint(1, 10),
},
}
yield data
class DBSetup(DBConn):
def _create_tables(self):
for database_type in self._database_types:
conn = self.get_conn(database_type)
if database_type == "postgres":
if not conn.dialect.has_schema(conn, self.schema):
conn.execute(sa.schema.CreateSchema(self.schema))
if database_type == "mysql":
conn.execute(f"CREATE DATABASE IF NOT EXISTS {self.schema}")
Base.metadata.create_all(conn)
def reset(self):
for database_type in self._database_types:
conn = self.get_conn(database_type)
Base.metadata.drop_all(conn)
sql = f"DROP SCHEMA IF EXISTS {self.schema}"
if database_type == "postgres":
conn.execute(f"{sql} CASCADE")
else:
conn.execute(sql)
def load_transaction(self, data, session):
customers = data.get("customers")
transactions = data.get("transactions")
transaction_details = data.get("transaction_details")
row = Customers( # maintain the relationship between each tables
**customers,
transactions=[
Transactions(
**transactions,
transaction_details=[
TransactionDetails(**transaction_details)
],
)
],
)
session.add(row)
session.commit()
def _seed_transactions(self):
my_fake_data = DataGenerator()
session = self.get_session("mysql")
for line in my_fake_data.get_data():
self.load_transaction(line, session)
@property
def _product_list(self):
return PRODUCT_LIST
def _seed_products(self):
for database_type in self._database_types: #
session = self.get_session(database_type)
for row in self._product_list:
product = Products(**row) # pass in as a kwargs
session.add(product) # insert data into both databases
session.commit()
def run(self):
self.reset()
self._create_tables()
self._seed_products()
self._seed_transactions()
class ApplicationDataBase(DBConn):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.jinja_env = Environment(
loader=PackageLoader("database", "templates")
)
db_type = "mysql"
def _get_template(self, filename, **kwargs):
temp = self.jinja_env.get_template(filename)
return temp.render(**kwargs)
def get_data(self, date, table_name):
kwargs = {"date": date}
sql = self._get_template(f"{table_name}.sql", **kwargs)
return self.run_query(sql)
def run_query(self, sql):
conn = self.get_conn("mysql")
result = conn.execute(sql)
return [dict(row) for row in result.fetchall()]
if __name__ == "__main__":
kwargs = {"host": "localhost"}
app = ApplicationDataBase(**kwargs)
data1 = app.get_data("2021-08-03", "customers")
data2 = app.get_data("2021-05-01", "transactions")
data3 = app.get_data("2021-07-21", "transaction_details")
print(data1)
print("******")
print(data2)
print("******")
print(data3)
| 29.117871 | 92 | 0.560068 | 6,501 | 0.848916 | 1,195 | 0.156046 | 742 | 0.096892 | 0 | 0 | 1,498 | 0.195612 |
b3ab6c36b1a0d4d101bc155cc11546266d771646 | 623 | py | Python | test_platform/api_app/user_view.py | juxiaona/test_dev05 | 7a47ff51cc4afd33353323ebe10469a1a3e40e4a | [
"Apache-2.0"
] | 1 | 2021-07-11T09:16:24.000Z | 2021-07-11T09:16:24.000Z | test_platform/api_app/user_view.py | juxiaona/test_dev05 | 7a47ff51cc4afd33353323ebe10469a1a3e40e4a | [
"Apache-2.0"
] | 1 | 2021-07-11T09:16:52.000Z | 2021-07-11T09:16:52.000Z | test_platform/api_app/user_view.py | juxiaona/test_dev05 | 7a47ff51cc4afd33353323ebe10469a1a3e40e4a | [
"Apache-2.0"
] | 3 | 2021-10-17T12:23:01.000Z | 2022-02-03T02:29:05.000Z | from rest_framework import routers, serializers, viewsets
from django.contrib.auth.models import User
from api_app.serializer import UserSerializer
# 视图类
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
# users = User.objects.all()
# users_list = []
# for user in users:
# user_dict = {
# "url": "http://127.0.0.1/users/"+ user.id + "/",
# "username": user.username,
# "email": user.email,
# }
# users_list.append(user_dict)
#
# return JsonResponse({"userlist":users_list})
| 27.086957 | 62 | 0.626003 | 465 | 0.739269 | 0 | 0 | 0 | 0 | 0 | 0 | 307 | 0.488076 |
b3adfd72fc9055ebcd5449010c4b1ce43ee3fc03 | 3,325 | py | Python | river/metrics/cluster/ssb.py | WLDCH/river | 8ab3431dc3e08c81d03f1220a523ee70c4facd8e | [
"BSD-3-Clause"
] | 1 | 2020-11-07T23:01:16.000Z | 2020-11-07T23:01:16.000Z | river/metrics/cluster/ssb.py | WLDCH/river | 8ab3431dc3e08c81d03f1220a523ee70c4facd8e | [
"BSD-3-Clause"
] | null | null | null | river/metrics/cluster/ssb.py | WLDCH/river | 8ab3431dc3e08c81d03f1220a523ee70c4facd8e | [
"BSD-3-Clause"
] | null | null | null | from river import stats, utils
from . import base
class SSB(base.ClusteringMetric):
"""Sum-of-Squares Between Clusters (SSB).
The Sum-of-Squares Between Clusters is the weighted mean of the squares of distances
between cluster centers to the mean value of the whole dataset.
Examples
--------
>>> from river import cluster
>>> from river import stream
>>> from river import metrics
>>> X = [
... [1, 2],
... [1, 4],
... [1, 0],
... [4, 2],
... [4, 4],
... [4, 0],
... [-2, 2],
... [-2, 4],
... [-2, 0]
... ]
>>> k_means = cluster.KMeans(n_clusters=3, halflife=0.4, sigma=3, seed=0)
>>> metric = metrics.cluster.SSB()
>>> for x, _ in stream.iter_array(X):
... k_means = k_means.learn_one(x)
... y_pred = k_means.predict_one(x)
... metric = metric.update(x, y_pred, k_means.centers)
>>> metric
SSB: 8.109389
References
----------
[^1]: Q. Zhao, M. Xu, and P. Franti, "Sum-of-squares based cluster validity index
and significance analysis," in Adaptive and Natural Computing Algorithms,
M. Kolehmainen, P. Toivanen, and B. Beliczynski, Eds.
Berlin, Germany: Springer, 2009, pp. 313–322.
"""
def __init__(self):
super().__init__()
self._center_all_points = {}
self._n_points = 0
self._n_points_by_clusters = {}
self._squared_distances = {}
self._initialized = False
def update(self, x, y_pred, centers, sample_weight=1.0):
if not self._initialized:
self._center_all_points = {i: stats.Mean() for i in x}
self._initialized = True
for i in self._center_all_points:
self._center_all_points[i].update(x[i], w=sample_weight)
center_all_points = {
i: self._center_all_points[i].get() for i in self._center_all_points
}
self._n_points += 1
try:
self._n_points_by_clusters[y_pred] += 1
except KeyError:
self._n_points_by_clusters[y_pred] = 1
for i in centers:
self._squared_distances[i] = utils.math.minkowski_distance(
centers[i], center_all_points, 2
)
return self
def revert(self, x, y_pred, centers, sample_weight=1.0):
for i in self._center_all_points:
self._center_all_points[i].update(x[i], w=-sample_weight)
center_all_points = {
i: self._center_all_points[i].get() for i in self._center_all_points
}
self._n_points -= 1
self._n_points_by_clusters[y_pred] -= 1
for i in centers:
self._squared_distances[i] = utils.math.minkowski_distance(
centers[i], center_all_points, 2
)
return self
def get(self):
ssb = 0
for i in self._n_points_by_clusters:
try:
ssb += (
1
/ self._n_points
* self._n_points_by_clusters[i]
* self._squared_distances[i]
)
except ZeroDivisionError:
ssb += 0
return ssb
@property
def bigger_is_better(self):
return True
| 27.254098 | 88 | 0.550376 | 3,273 | 0.983769 | 0 | 0 | 61 | 0.018335 | 0 | 0 | 1,212 | 0.364292 |
b3ae79059719c022e0deda9fca2855194972e39f | 70,728 | py | Python | DatabaseStocks.py | VaseSimion/Finance | 63d04a3bb03177e0f959c0c79fa922aecb50ae11 | [
"MIT"
] | 1 | 2021-01-26T11:59:59.000Z | 2021-01-26T11:59:59.000Z | DatabaseStocks.py | VaseSimion/Finance | 63d04a3bb03177e0f959c0c79fa922aecb50ae11 | [
"MIT"
] | null | null | null | DatabaseStocks.py | VaseSimion/Finance | 63d04a3bb03177e0f959c0c79fa922aecb50ae11 | [
"MIT"
] | 1 | 2021-01-26T15:53:58.000Z | 2021-01-26T15:53:58.000Z | import random
list_of_technology = ["AAPL", "ACIW", "ACN", "ADBE", "ADI", "ADP", "ADSK", "AKAM", "AMD", "AMAT",
"ANET", "ANSS", "ARW", "ATVI", "AVGO", "AVT", "AZPN", "BA", "BB", "BLL",
"BLKB", "BR", "CDK", "CDNS", "CERN", "CHKP", "CIEN", "COMM", "COUP",
"CREE", "CRM", "CRUS", "CRWD", "CSCO", "CVLT",
"CY", "CYBR", "DBX", "DDD", "DDOG", "DLB", "DOCU", "DOX", "DXC", "EA", "EFX", "EQT",
"FCEL", "FDS", "FEYE", "FIT", "FTNT", "FVRR", "G", "GE", "GLW", "GPRO",
"GRMN", "GRPN", "HIMX", "HPE", "HPQ", "IAC", "IBM",
"INFO", "INTC", "IPGP", "IT", "JBL", "JCOM", "KEX", "LOGI",
"MCHP", "MSFT", "MCO", "MDB", "MDRX", "MOMO", "MSCI", "MSI", "MU", "NCR",
"NLOK", "NLSN", "NOW", "NUAN",
"NVDA", "NTAP", "NTGR", "NXPI", "OKTA", "ON", "PANW", "PAYX", "PBI",
"PCG", "PFPT", "PING", "PTC", "PINS", "QCOM", "ORCL", "QRVO", "OTEX", "SABR",
"SHOP", "SNAP", "SPCE", "SPGI", "SPLK", "SQ", "SSNC",
"STM", "STX", "SYY", "SWKS", "TEAM", "TER", "TEVA", "TLND",
"TSM", "TTWO", "TWLO", "VEEV", "VLO", "VMW", "VRSK", "VSAT",
"WDC", "WIX", "WORK", "ZM", "XRX", "ZBRA", "ZEN", "ZNGA", "ZS"]
list_of_materials = ["AA", "ATI", "BLL", "CCJ", "CENX", "CCK", "UFS", "EXP", "EGO", "FCX", "GPK",
"IP", "KGC", "LPX", "MLM", "NEM", "NUE", "OC", "OI", "PKG", "PAAS", "RS", "RGLD", "SON", "SCCO",
"TRQ", "X", "VALE", "VMC", "WPM", "AUY", "MMM", "AIV", "ALB", "APD", "ASH", "AVY", "CE", "CX",
"CF", "CTVA", "DOW", "DD", "EXP", "EMN", "ECL", "IFF", "FMC", "HUN", "ICL", "LYB", "MEOH", "MOS",
"NEU", "POL", "PPG", "RPM", "SHW", "SLGN", "SQM", "GRA", "WLK"]
list_of_communication_services = ["ACIA", "GOOG", "AMCX", "T", "BIDU", "CTL", "CHTR", "CHL", "CHU", "CHT",
"CMCSA", "DISCA", "DISH", "DIS", "EXPE", "FFIV", "FB", "FOXA", "FTR", "GDDY",
"GRUB", "IPG", "LBTYA", "LN", "LYFT", "MTCH", "NFLX", "OMC",
"PINS", "RCI", "ROKU", "SBAC", "SNAP", "SPOT", "S", "TMUS", "TU", "TTD", "TRIP",
"TWTR", "UBER", "VEON", "VZ", "VIAC", "WB", "YNDX", "Z"]
list_of_utilities_and_real_estate = ["AES", "AEE", "AEP", "AWK", "WTR", "ATO", "CMS", "ED", "DUK", "EIX", "EVRG",
"EXC", "FE", "MDU", "NFG", "NEE", "NI", "NRG", "OGE", "PPL", "PEG", "SRE", "SO",
"UGI", "XEL", "AGNC", "ARE", "AMH", "AVB", "BXP", "CPT", "CBL", "CBRE", "CB",
"CLNY", "CXP", "ESS", "FRT", "GLPI", "JLL", "PB", "SVC", "SITC"]
list_of_energy = ["LNT", "AR", "APA", "BKR", "COG", "CNP", "CHK", "CVX", "SNP", "CNX", "CXO", "COP",
"CLB", "DCP", "DVN", "DO", "D", "DRQ", "DTE", "ENS", "EPD", "EOG", "EQT", "XOM", "FSLR", "GPOR",
"HAL", "HP", "HES", "HFC", "KMI", "LPI", "MMP", "MRO", "MPC", "MUR", "NBR", "NOV",
"NS", "OAS", "OXY", "OII", "OKE", "PBR", "PSX", "PXD", "QEP", "RRC", "RES", "SSL", "SLB", "SM",
"SWN", "SPWR", "TRGP", "FTI", "VAL", "VLO", "VSLR", "WLL", "WMB", "WEC", "INT"]
list_of_industrials = ["AOS", "AYI", "AEIS", "ACM", "AER", "AGCO", "ALLE", "ALSN", "AME", "APH", "AXE", "BA", "CAT",
"CLH", "CGNX", "CFX", "CR", "CSX", "CMI", "DE", "DCI", "DOV", "ETN", "EMR", "FAST", "FDX",
"FLEX", "FLS", "FLR", "GD", "GE", "GWR", "GLNG", "GGG", "HXL", "HON", "HII", "IEX", "ITW",
"IR", "ITRI", "JEC", "JCI", "KSU", "KBR", "KMT", "KEYS", "KEX", "KNX", "LII", "LECO", "LFUS",
"LMT", "MIC", "MIDD", "MSM", "NDSN", "NOC", "NSC", "ODFL", "PH", "PNR", "PWR", "RTN", "RBC",
"RSG", "ROK", "ROP", "R", "SPR", "SPXC", "TDY", "TEX", "TXT", "TTC", "TDG", "TRMB", "TRN", "UAL",
"URI", "UTX", "UNP", "UPS", "VMI", "WAB", "WM", "WCC", "XPO", "XYL"]
list_of_consumer_discretionary = ["ANF", "ADNT", "ALK", "BABA", "AMZN", "AAL", "AEO", "APTV", "ASNA", "AN", "AZO",
"CAR",
"BBBY", "BBY", "BJ", "BLMN", "BWA", "BV", "EAT", "BC", "BURL", "CAL", "GOOS", "CPRI",
"KMX", "CRI", "CVNA", "CHWY", "CMG", "CHRW", "CNK", "CTAS", "COLM", "CPA", "CPRT",
"DHI", "DAN", "DLPN", "DAL", "DKS", "DDS", "DOL", "DNKN", "EBAY", "ELF", "ETSY",
"RACE", "FCAU", "FL", "F", "FBHS", "FOSL", "GME", "GPS", "GTX", "GPC", "GIL", "GM",
"GNC", "GT", "HRB", "HBI", "HOG", "HAS", "HD", "H", "IGT", "IRBT", "ITT",
"JPC", "SJM", "JD", "JBLU", "JMIA", "KAR", "KSS", "KTB", "LB", "LVS", "LEA", "LEG",
"LEN", "LEVI", "LYV", "LKQ", "LOW", "LULU", "M", "MANU", "MAN", "MAR", "MAS", "MAT",
"MCD", "MLCO", "MELI", "MGM", "MHK", "NWL", "NKE", "NIO", "JWN", "NVEE", "OSK",
"PTON", "PDD", "PII", "POOL", "PHM", "PVH", "RL", "RVLV", "RHI", "RCL", "SBH",
"SGMS", "SMG", "SEE", "SIX", "SNA", "LUV", "SAVE", "SWK", "SBUX", "TPR",
"TEN", "TSLA", "MSG", "REAL", "TJX", "THO", "TIF", "TOL", "TSCO", "TUP",
"ULTA", "UAA",
"URBN", "VFC", "VC", "W", "WEN", "WHR", "WSM", "WW", "WYND", "WYNN"]
list_of_consumer_staples = ["MO", "ADM", "BYND", "BRFS", "BG", "CPB", "CHD", "CLX", "KO", "CL", "CAG", "STZ", "COTY",
"DG", "ENR", "EL", "FLO", "GIS", "HLF", "HLT", "HRL", "INGR", "K", "KDP", "KMB", "KHC",
"KR", "MKC", "TAP", "MDLZ", "PEP", "PM", "RAD", "SPB", "SFM", "SYY", "TGT",
"HAIN", "TSN", "UNFI", "VFF", "WBA", "WMT", "YUM"]
list_of_healthcare = ["ABT", "ABBV", "ACAD", "ALC", "ALXN", "ALGN", "ALKS", "AGN", "ALNY", "ABC", "AMGN", "ANTM",
"ARNA", "AVTR", "BHC", "BAX", "BDX", "BIO", "BIIB", "BMRN", "BSX", "BMY", "BKD", "BRKR", "CARA",
"CAH", "CNC", "CI", "COO", "CRBP", "CRSP", "CVS", "DHR", "DVA", "EW", "LLY", "EHC", "ENDP",
"EXAS", "GILD", "GWPH", "HCA", "HUM", "IDXX", "ILMN", "INCY", "INVA", "ISRG", "NVTA", "IQV",
"JAZZ", "JNJ", "LH", "LVGO", "MCK", "MD", "MDT", "MRK", "MTD", "MYL", "NGM", "OPK", "PKI",
"PFE", "QGEN", "REGN", "SGEN", "SYK", "TDOC", "TFX", "THC", "TEVA", "TMO", "TLRY", "UNH",
"UHS", "VAR", "VRTX", "WAT", "ZBH", "ZTS"]
list_of_financials = ["AFC", "AIG", "ACC", "AXP", "AMT", "AMP", "NLY", "AON", "ACGL", "ARCC", "AJG", "AIZ", "AGO",
"AXS", "BAC", "BK", "BKU", "BLK", "BOKF", "BRO", "COF", "CBOE", "CBRE", "SCHW",
"CIM", "CINF", "CIT", "C", "CME", "CNO", "CMA", "CBSH", "CXW", "BAP", "CCI", "CWK", "DLR", "DFS",
"DEI", "DRE", "ETFC", "EWBC", "EQIX", "EQR", "RE", "EXR", "FII", "FIS", "FNF", "FITB", "FHN",
"FRC", "BEN", "CFR", "GNW", "GPN", "GS", "HBAN", "PEAK", "HIG", "HST", "HHC", "IEP", "ICE",
"IBN", "IVZ", "IRM", "ITUB", "JKHY", "JHG", "JEF", "JPM", "KEY", "KRC", "KIM", "KKR", "LAZ",
"LM", "LC", "TREE", "LNC", "L", "LPLA", "MTB", "MKL", "MMC", "MA", "MET", "MTG", "MS", "NDAQ",
"NTRS", "NYCB", "ORI", "PYPL", "PBCT", "PNC", "BPOP", "PFG", "PSEC", "PRU", "RDN", "RJF",
"RLGY", "REG", "RF", "RGA", "RNR", "SEIC", "SBNY", "SLM", "SQ", "STT", "SF", "STI", "SIVB",
"SNV", "TROW", "AMTD", "ALL", "BX", "PGR", "TD", "TRV", "TFC", "TWO", "USB", "UBS",
"UMPQ", "UNM", "V", "WRB", "WBS", "WFC", "WELL", "WU", "WEX", "WLTW", "WETF", "ZION"]
european_stocks = ["ADS.DE", "ALO.PA", "BAYN.DE", "BMW.DE", "IFX.DE", "LHA.DE", "MAERSK-B.CO", "NOVO-B.CO",
"NZYM-B.CO", "SU.PA", "VWS.CO"]
def get_lists():
print(len(list_of_industrials + list_of_technology + list_of_communication_services + list_of_energy +
list_of_utilities_and_real_estate + list_of_materials + list_of_consumer_discretionary +
list_of_consumer_staples + list_of_healthcare + list_of_financials))
list_CFD = list_of_industrials + list_of_technology + list_of_communication_services + list_of_energy + \
list_of_utilities_and_real_estate + list_of_materials + list_of_consumer_discretionary + \
list_of_consumer_staples + list_of_healthcare + list_of_financials
random.shuffle(list_CFD)
return list_CFD
# investing side of Trading212
investing_list_of_energy = ["ADES", "AES", "ARPL", "AMRC", "AMSC", "APA", "ARCH", "AROC", "BKR", "BLDP", "BSM", "BCEI",
"COG", "CRC", "CPE", "CNQ", "CSIQ", "CQP", "CVX", "XEC", "CMS", "CRK", "CXO", "COP", "CEIX",
"CLR", "CZZ", "CVI", "DCP", "DVN", "DO", "FANG", "DRQ", "DTE", "ENB", "ET", "ENLC", "ENPH",
"ETR", "EPD", "EVA", "EOG", "EQT", "EQNR", "ES", "EXC", "EXTN",
"XOM", "FSLR", "FCEL", "GEOS", "HAL", "HP", "HES", "HEP", "JKS", "KMI", "KOS", "MMP", "MRO",
"MPC", "MPLX", "MUR",
"MUSA", "NC", "NOV", "NGS", "NEE", "DNOW", "OMP", "OXY", "OKE", "PBF", "BTU", "PBA",
"PBR", "PSX", "PSXP", "PXD", "PAA", "PLUG", "RRC",
"SLB", "SHLX", "SEDG", "SO", "SWN", "SPI", "SPWR", "RUN", "TRGP", "TRNX", "TRP", "FTI",
"TOT", "RIG", "VAL", "VLO", "VET", "VNOM", "VSLR", "VOC", "WES", "WMB", "WPX"]
investing_list_of_materials = ["MMM", "ASIX", "AEM", "AIV", "ADP", "ALB", "AA", "AMCR", "AU", "AVY", "BCPC", "BLL",
"GOLD", "BBL", "BHP", "BCC", "BREE.L", "CCJ", "CSL", "CRS", "CE", "CF", "CLF", "CDXS",
"BVN", "DOW", "DRD",
"DD", "EMN", "ESI", "UUUU", "EQX", "AG", "FMC", "FNV", "FCX", "GCP", "ICL", "IP", "IFF",
"LIN", "LAC", "LTHM", "LYB", "MLM", "MATW", "MDU", "NEM", "NXE", "NTIC", "NUE", "NTR",
"OI", "PAAS", "PPG", "RIO", "RGLD", "SAND", "SSL", "SCHN", "SEE", "SHW", "SBSW", "SMTS",
"SCOO", "STLD", "MOS", "TREX", "URG", "UEC", "VVV", "VRS", "VMC", "WRK", "WPM", "AUY"]
investing_list_of_industrials = ["AOS", "AIR", "ATU", "ADSW", "AEIS", "ACM", "AVAV", "ALG", "ALRM", "ALK", "ALGT",
"ALLE", "AMOT", "AME", "APH", "AGX", "ATRO", "AAXN", "BMI", "BDC", "BHE", "BEST",
"BLNK", "BE", "BA", "BGG", "CHRW", "WHD", "CAI", "CAMT", "CNI", "CARR", "CAT", "CFX",
"CTG", "CPA", "CVA", "CYRX", "CSX", "CMI", "CW", "CYBE", "DE",
"DAL", "DOV", "DYNT", "ETN", "ESLT", "EME", "EMR", "WATT", "ERII", "AQUA", "EXPD",
"EXPO", "FAST", "FDX", "FLS", "FLR", "FORR", "FTV", "FRG", "FELE", "FTDR", "GLOG",
"GLOP", "GD", "GE", "GFL", "EAF", "GHM", "HEES", "HDS", "HCCI",
"HON", "HWM", "HUBB", "ICHR", "ITW", "IR", "IVAC", "ITRI", "JBHT", "J", "JBLU", "JBT",
"JCI", "KAI", "KSU", "KEYS",
"KE", "LHX", "LSTR", "LTM", "LECO", "LFUS", "LMT", "MAGS", "MNTX", "MRCY", "MIDD",
"MTSC", "NSSC", "NATI", "LASR", "NAT", "NSC", "NOC", "NOVT", "ODFL", "OSIS", "OTIS",
"PCAR", "PH", "PNR", "POWL", "PWR", "RBC", "RSG", "RGP",
"RXN", "ROK", "ROP", "R", "SAIA", "SHIP", "SITE", "SNA", "LUV", "SAVE", "SPXC", "FLOW",
"SXI", "SRCL", "TEL", "TNC", "TTEK", "TXT", "GBX", "HCKT", "SHYF", "TKR", "TOPS",
"BLD", "TRNS", "TDG", "TRMB", "TWIN", "UNP", "UPS", "URI", "VSEC", "GWW", "WCN", "WM",
"WTS", "WLDN", "WWD", "WKHS", "WRTC", "XYL", "ZTO"]
investing_list_of_consumer_discretionary = ["FLWS", "TWOU", "AAN", "ANF", "ACTG", "ACCO", "AEY", "ADNT", "ATGE", "AAP",
"BABA", "AMZN", "AMC", "AAL", "APEI", "AMWD", "CRMT", "APTV", "ARC", "FUV",
"ARCO", "ASGN", "AN",
"AZO", "CAR", "AZEK", "BBSI", "BECN", "BBBY", "BBY", "BGSF", "BGFV", "BJRI",
"BLMN", "APRN", "BOOT", "BWA",
"BYD", "BRC", "BV", "BC", "BKE", "BLDR", "BURL", "CZR", "CAL", "CWH",
"GOOS", "CPRI", "KMX", "CCL",
"CVNA", "CSPR", "CATO", "FUN", "CHWY", "CMG", "CHH", "CHUY", "CNK", "CTAS",
"CPRT", "CTVA", "CRVL", "CROX", "DHI", "DRI", "PLAY", "TACO",
"DENN", "DKS", "DPZ", "DKNG", "EBAY", "ECL", "LOCO", "EEX", "ETSY",
"FTCH", "RACE", "FCAU", "FCFS", "FVRR", "FL", "F", "FRSX", "FOR", "FOSL",
"FOXF", "FRPT", "FNKO",
"GME", "GPS", "GTX", "GM", "GNTX", "GPC", "GDEN", "GT", "GHG", "GFF",
"GRWG", "GES", "HRB", "HBI", "HOG", "HAS",
"HSII", "MLHR", "HIBB", "HLT", "HMSY", "HD", "HUD", "NSP", "TILE", "IRBT",
"JD", "JMIA", "KELYA", "KEQU", "KFRC", "KBAL", "KSS", "KTB",
"KFY", "KRUS", "LB", "LAKE", "LAUR", "LEG", "LEN", "LEVI", "LQDT", "LAD",
"LYV", "LOW", "LULU", "M", "MANU",
"MAN", "HZO", "MAR", "MAS", "MAT", "MCD", "MELI", "MTH", "METX", "MGM",
"MOGU", "MCRI", "MNRO", "NRC", "EDU", "NWL", "NKE",
"NIO", "JWN", "NCLH", "ORLY", "OSW", "OSTK", "PTON", "PENN", "PETQ", "PETS",
"PDD", "PLNT", "PLYA", "PII", "RL", "PHM", "NEW", "PVH", "QRTEA", "RDIB",
"RCII", "QSR", "RVLV", "RHI", "ROST", "RCL", "RUHN", "RUTH", "SBH", "SGMS",
"SEAS", "SHAK", "SCVL", "SSTI", "SIG", "SIX", "SKY",
"SKYW", "SNBR", "SLM", "SPWH", "SWK", "SBUX", "SHOO", "SFIX", "STRA",
"TAL", "TPR", "TH", "TMHC", "TSLA", "TXRH", "CAKE", "PLCE", "MIK", "REAL",
"WEN", "THO",
"TIF", "TJX", "TOL", "TM", "TSCO", "TNET", "TBI", "ULTA", "UAA", "UNF",
"UAL", "URBN", "VFC", "MTN", "VVI", "VIPS", "SPCE", "VSTO", "VRM", "WTRH",
"WSG", "W", "WSTG", "WHR", "WING", "WINA", "WW", "WYND", "WYNN", "XSPA",
"YUMC", "YUM", "YJ", "ZUMZ"]
investing_list_of_consumer_staples = ["MO", "BUD", "ADM", "BGS", "BYND", "BIG", "BJ", "BTI", "BF-A", "BG", "CALM",
"CVGW", "CPB", "CELH", "CHD", "CLX", "KO", "CCEP", "CL", "CAG",
"STZ", "COST", "COTY", "CRON", "DAR", "DEO", "DG", "DLTR", "ELF", "EL", "GIS",
"GO", "HELE", "HLF",
"HRL", "IMKTA", "IPAR", "SJM", "K", "KDP", "KMB", "KHC", "KR", "MKC", "MGPI",
"TAP", "MDLZ", "MNST", "FIZZ", "OLLI", "PEP", "PAHC",
"PM", "PPG", "PG", "RAD", "SAFM", "SPTN", "SYY", "TGT", "SAM", "CHEF", "HSY",
"TSN", "UN", "UVV", "VFF", "WBA", "WMT", "WMK"]
investing_list_of_healthcare = ["TXG", "ABT", "ABBV", "ABMD", "ACIU", "ACHC", "ACAD", "AXDX", "XLRN", "ACOR", "AHCO",
"ADPT", "ADUS", "ADVM", "AERI", "AGEN", "AGRX", "A", "AGIO", "AIMT", "AKCA", "AKBA",
"AKRO", "AKUS", "ALBO",
"ALC", "ALEC", "ALXN", "ALGN", "ALKS", "ALLK", "AHPI", "ALLO", "ALNY", "AMRN", "AMED",
"AMS", "ABC", "AMGN", "FOLD", "AMN", "AMRX", "AMPH", "ANAB", "ANGO", "ANIP", "ANIK",
"ANPC", "ATRS", "ANTM", "APLS", "APHA", "AMEH", "APLT", "APRE", "APTO", "ARCT", "ARQT",
"ARDX",
"ARNA", "ARWR", "ARVN", "ASDN", "ASMB", "AZN", "ATRA", "ATNX", "ATHX", "BCEL", "ATRC",
"ATRI", "ACB", "AVDL", "AVNS", "AVTR", "AVGR", "AVRO", "AXNX", "AXGT", "AXSM",
"BXRX", "BHC", "BAX", "BEAM", "BDX", "BGNE", "BLCM", "BYSI", "TECH", "BASI", "BIOC",
"BCRX", "BDSI", "BIIB", "BLFS", "BMRN", "PHGE", "BNTX", "BSTC", "BEAT", "BTAI",
"BLUE", "BPMC", "BSX", "BBIO", "BMY", "BRKR", "BNR", "CABA", "CGC", "CARA",
"CRDF", "CAH", "CSII", "CDNA", "CSTL", "CPRX", "CNC", "CNTG", "CERS", "GIB", "CCXI",
"CBPO", "CPHI", "CI", "CLIN.L", "CLVS", "CODX", "COCP", "CHRS", "COLL", "CGEN", "CNST",
"CRBP", "CORT", "CRTX", "CVET", "CRNX", "CRSP",
"CCRN", "CUE", "CUTR", "CVS", "CBAY", "CYTK", "CTMX", "DHR", "DVA", "DCPH", "DNLI",
"XRAY", "DMTK", "DXCM", "DRNA", "DFFN", "DVAX", "EGRX", "EDIT", "EW", "LLY", "ENTA",
"ENDP", "EPZM", "ESPR", "ESTA", "EXAS", "EXEL", "FATE", "FGEN", "FMTX",
"FREQ", "FUSN", "GTHX", "GBIO", "GNPX", "GERN", "GILD", "GSK", "GBT", "GOSS", "GH",
"GHSI", "GWPH", "HALO", "HBIO", "HCA", "HQY", "HTBX", "HSIC", "HEPA", "HRTX", "HSKA",
"HEXO", "HOLX", "FIXX", "HZNP", "HUM", "IMAB", "IBIO", "ICLR", "ICUI", "IDXX", "IGMS",
"ILMN", "IMGN", "IMMU", "IMRN", "NARI", "INCY", "IFRX", "INMD", "INVA", "INGN", "INO",
"INSM", "PODD", "NTEC", "LOGM", "NTLA", "ICPT", "ISRG", "NVTA", "IONS", "IOVA", "IQV",
"IRTC", "IRWD", "JAZZ", "JNJ", "KALA", "KRTX", "KPTI", "KNSA", "KTOV", "KOD", "KRYS",
"KURA", "LH", "LTRN", "LNTH", "LMAT", "LHCG", "LGND", "LIVN", "LVGO", "LMNX", "MGNX",
"MDGL", "MGLN", "MNK", "MNKD", "MASI",
"MCK", "MEDP", "MDT", "MEIP", "MGTX", "MRK", "VIVO", "MMSI", "MRSN", "MRUS", "MTP",
"MRTX", "MIRM", "MRNA", "MTEM", "MNTA", "MORF", "MYL", "MYOK", "MYGN", "NSTG", "NH",
"NK", "NTRA", "NTUS", "NKTR", "NEOG", "NEO", "NBIX", "NXTC", "NGM", "NVS", "NVAX",
"NVO", "NVCR", "NUVA", "OCGN", "ODT", "OMER", "OTRK", "OPK", "OPCH", "OGEN", "OSUR",
"ORTX", "OGI", "OFIX", "KIDS", "OYST", "PACB", "PCRX", "PRTK", "PASG", "PDCO", "PAVM",
"PDLI", "PKI", "PRGO", "PFE", "PHAT", "PLRX", "PYPD", "PPD", "PRAH", "PGEN", "PRPO",
"DTIL", "PINC", "PRVL", "PRNB", "PROG", "PGNY", "PRTA", "PRVB", "PTCT", "PULM", "PLSE",
"PBYI", "QLGN", "QTRX", "DGX", "QDEL", "QTNT", "RDUS", "RDNT", "RAPT", "RETA", "RDHL",
"REGN", "RGNX", "RLMD", "RPTX", "RGEN", "REPL", "KRMD", "RTRX", "RVNC", "RVMD", "RYTM",
"RCKT", "RMTI", "RPRX", "RUBY", "SAGE", "SNY", "SRPT", "SRRK", "SGEN", "SNCA", "SWAV",
"SIBN", "SIGA", "SILK", "SINT", "SDC", "SOLY", "SRNE", "SWTX", "STAA", "STOK", "SYK",
"SNSS", "SUPN", "SGRY", "SRDX", "SNDX", "SYNH", "SNV", "SYRS", "TCMD", "TNDM", "TARO",
"TDOC", "TFX", "THC", "TEVA", "TGTX", "COO", "ENSG", "PRSC", "TXMD", "TBPH", "TMO",
"TLRY", "TMDI", "TTNP", "TVTY", "TBIO", "TMDX",
"TCDA", "TRIL", "TRIB", "GTS", "TPTX", "TWST", "RARE", "QURE", "UNH", "UTHR", "UHS",
"URGN", "VNDA", "VREX", "VAR", "VXRT", "VBIV", "VCYT", "VRTX", "VIE", "VMD", "VKTX",
"VIR", "VYGR", "WAT", "WST", "WMGI", "XBIT", "XNCR", "XENE", "YMAB", "ZLAB", "ZNTL",
"ZBH", "ZIOP", "ZTS", "ZGNX", "ZYXI"]
investing_list_of_financials = ["SRCE", "QFIN", "JFU", "AER", "AMG", "AFL", "AGMH", "AGNC", "AIG", "AL", "ALEX", "ADS",
"AB", "ALL", "ALLY", "AMBC", "AXP", "AMP", "ABCB", "AMSF", "NLY",
"AON", "ARI", "APO", "ACGL", "ARCC", "ARES", "AROW", "AJG", "APAM", "ASB", "AC", "AIZ",
"AGO", "AUB", "AXS", "BANF", "BSMX", "BAC", "BOH", "BMO", "BK", "BNS", "OZK", "BKU",
"BANR", "BBDC", "BCBP", "BRK-B",
"BLK", "BCOR", "BOKF", "BDGE", "BHF", "BRLIU", "BYFC", "BAM", "BPYU", "BRO", "CADE",
"CM", "COF", "CPTA", "CFFN", "CATM", "CATY", "CBTX", "SCHW", "CIM", "CB", "CCXX",
"CINF", "C", "CHCO", "CME", "CCH", "COLB", "CMA", "CBU",
"CODI", "COWN", "BAP", "CACC", "CRT", "CVBF", "DLR", "DFS", "DX", "ETFC", "EGBN",
"EHTH", "EFC", "ECPG", "ESGR", "EPR", "ERIE", "ESNT", "EVR", "FANH", "FIS", "FITB",
"BUSE", "FCNCA", "FFIN", "FHB", "FHN",
"FISV", "FLT", "FEAC", "WPF", "FMCI", "BEN", "FRHC", "FSK", "FULT", "FUSE", "FUTU",
"GATX", "GFN", "GNW", "GBCI", "GOOD", "GAIN", "GPN", "GL", "GS", "GSHD", "AJX", "GSKY",
"GDYN", "HLNE", "HASI", "HIG", "HDB", "HTLF", "HOPE", "HRZN", "HLI", "HSBC", "HBAN",
"IBKR", "ICE", "IVZ", "IVR", "ISBC", "ITUB",
"JKHY", "JRVR", "JHG", "JEF", "JFIN", "JPM", "KMPR", "KW", "KCAC", "KEY", "KNSL", "KKR",
"LADR", "LKFN", "LCA", "LAZ", "LGC", "LM", "TREE", "LX", "LNC", "L", "MTB", "MAIN",
"MFC", "MKL", "MMC",
"MA", "MCY", "MET", "MFA", "MC", "MGI", "MS", "COOP", "NDAQ", "NAVI", "NNI", "NRZ",
"NYMT", "NREF", "NKLA", "NMIH", "NTRS", "NWBI", "OCFC", "ONB", "ORI", "OXLC", "PPBI",
"PACW", "PLMR", "PKBK", "PAYC", "PYPL", "PAYS", "PBCT", "PNFP", "PNC",
"BPOP", "PFC", "PRA", "PGR", "PSEC", "PRU", "QIWI", "QD", "RDN", "RWT", "RF", "RNST",
"RPAY", "RY", "SAFT", "SASR", "SLCT", "SIGI", "SLQT", "FOUR", "SUNS", "SBSI", "SPAQ",
"SQ", "STWD", "STFC", "STT", "SCM", "STNE", "SLF", "SIVB", "SYF", "TROW",
"AMTD", "TCBI", "TFSL", "BX", "THG", "TRV", "TPRE", "TSBK", "TD", "SHLL", "TOWN.L",
"TSC",
"TFC", "TRUP", "TWO", "USB", "UMBF", "UMPQ", "UBSI", "UIHC", "UVE", "UNM", "VLY", "VEL",
"VCTR", "VBFC", "VIRT", "V", "WAFD", "WSBF", "WSBC", "WFC", "WAL", "WNEB", "WU", "WHG",
"WLTW", "WTFC", "XP", "ZION"]
investing_list_of_technology = ["ONEM", "DDD", "ATEN", "ACN", "ACIW", "ATVI", "ADBE", "ADTN", "AMD", "AGYS", "API",
"AIRG", "AKAM", "KERN", "AKTS", "MDRX", "AOSL", "AYX",
"AMBA", "AMSWA", "AMKR", "ASYS", "ADI", "PLAN", "ANSS", "ATEX", "APPF", "APPN", "AAPL",
"APDN", "AMAT", "AAOI", "ANET", "ARLO", "ASML",
"AZPN", "ASUR", "TEAM", "ATOM", "AUDC", "AEYE", "ADSK", "ADP", "AVNW", "AVID", "AVT",
"AWRE", "ACLS", "AXTI", "BAND", "BZUN",
"BNFT", "BILI", "BILL", "BLKB", "BB", "BL", "BAH", "BRQS", "EPAY", "BOX", "BCOV",
"AVGO", "BRKS", "CCMP", "CACI", "CDNS",
"CAMP", "CASA", "CDW", "CRNT", "CRNC", "CERN", "CEVA", "CHNG", "ECOM", "CHKP", "IMOS",
"CRUS", "CSCO", "CTXS", "CLFD", "CLDR", "NET", "CTSH",
"COHR", "COMM", "CPSI", "CNDT", "CLGX", "CSOD", "GLW", "CSGP", "COUP", "CREE", "CRWD",
"CSGS",
"CTS", "CUB", "CYBR", "DJCO", "DAKT", "DDOG", "DELL", "DSGX", "DGII", "DMRC", "APPS",
"DIOD", "DOCU", "DOMO", "DOYU", "DBX", "DSPG", "DXC", "EBON", "EBIX", "EGAN", "ESTC",
"EA",
"EMKR", "EMIS.L", "DAVA", "EIGI", "ENV", "EPAM", "PLUS", "EFX", "ERIC", "EVBG", "MRAM",
"EVH", "EXTR", "FFIV", "FDS", "FICO",
"FSLY", "FEYE", "FIT", "FIVN", "FLEX", "FLIR", "FORM", "FTNT", "FEIM", "GRMN", "IT",
"GNUS", "GILT", "GSB", "GLOB",
"GLUU", "GPRO", "GRVY", "GSIT", "GSX", "GTYH", "GWRE", "HLIT", "HPE", "HPQ", "HIMX",
"HUBS", "HUYA", "IBM", "IDEA.L", "IDEX", "INVE", "IDOX.L", "INFO", "IIVI", "IMMR",
"INFN",
"INOV", "IPHI", "INPX", "INSG", "NSIT", "INSE", "INTC", "IDCC", "INTU", "IPGP", "IQE.L",
"JCOM", "JBL", "JNPR", "KLAC",
"KOPN", "KLIC", "LRCX", "LTRX", "LSCC", "LDOS", "LLNW", "LPSN", "RAMP", "LIZI", "LOGI",
"LOGM", "LITE", "LUNA", "MTSI", "MGIC", "MANH", "MANT", "MKTX",
"MRVL", "MTLS", "MAXR", "MXIM", "MXL", "MCHP", "MU", "MSFT", "MSTR", "MIME", "MITK",
"MIXT", "MOBL",
"MODN", "MDB", "MPWR", "MCO", "MSI", "NPTN", "NTAP", "NTES", "NTGR", "NTCT",
"NEWR", "EGOV", "NICE", "NLSN", "NOK", "NLOK", "NVMI", "NUAN", "NTNX", "NVEC", "NVDA",
"NXPI", "OKTA", "OMCL",
"ON", "OCFT", "OSPN", "ORCL", "PD", "PANW", "PCYG", "PKE", "PAYX", "PCTY", "PCTI",
"PDFS", "PEGA", "PRFT", "PERI", "PFSW",
"PLAB", "PING", "PBI", "PXLW", "PLXS", "POWI", "PRGS", "PFPT", "PRO", "PTC", "QADA",
"QADB", "QRVO", "QCOM", "QLYS", "QMCO", "QTT", "RDCM", "RMBS", "RPD", "RTX", "RNWK",
"RP", "RDVT", "RESN", "RBBN", "RMNI", "RNG", "RIOT", "RST", "SBGI",
"SABR", "CRM", "SANM", "SAP", "SPNS", "SCSC", "SDGR", "SCPL", "SE", "SEAC", "STX",
"SCWX", "SMTC", "NOW", "SREV", "SWIR", "SILC", "SLAB", "SIMO", "SLP", "SITM", "SWKS",
"WORK", "SGH", "SMAR", "SMSI", "SMTX", "SONO", "SNE", "SPLK", "SPOT", "SPT", "SPSC",
"SSNC", "SRT", "SSYS",
"SMCI", "SVMK", "SYKE", "SYNC", "SYNA", "SNCR", "SNX", "SNPS", "TRHC", "TSM", "TTWO",
"TLND", "TM17.L", "TENB", "TDC",
"TER", "TXN", "TSEM", "TRU", "TTEC", "TTMI", "TWLO", "TYL", "UI", "UCTT", "UIS",
"UMC", "OLED", "UPLD", "UTSI",
"VRNS", "VECO", "VEEV", "VRNT", "VRSK", "VERI", "VSAT", "VIAV", "VICR", "VRTU", "VISL",
"VMW", "VCRA", "VOXX", "VUZI", "WAND.L", "WDC", "WIT", "WNS",
"WDAY", "WK", "XRX", "XLNX", "XPER", "XNET", "YEXT", "ZBRA", "ZEN", "ZUO", "ZNGA", "ZS"]
investing_list_of_communication_services = ["VNET", "EGHT", "ACIA", "ALLT", "GOOGL", "GOOG", "ANGI", "T", "ATNI",
"ATHM", "BIDU", "BCE", "WIFI", "BKNG", "BOMN", "CABO", "CDLX", "CARG",
"LUMN",
"CHTR", "CHL", "CHU", "CHT", "CIDM", "CCOI", "CMCSA", "CVLT", "CMTL",
"CNSL", "CRTO", "DADA", "DESP", "DISCA", "DISCK", "DISH", "SSP", "SATS",
"EB",
"EXPE", "FB", "FOXA", "FTR", "GCI", "GDDY", "GOGO", "GRPN", "GRUB", "HSTM",
"IHRT", "IAC", "INAP", "IPG", "IQ",
"IRDM", "KVHI", "LBRDA", "LBTYA", "LILA", "LTRPA", "LGF-B", "LORL",
"LYFT", "MMYT", "MCHX", "MTCH", "MDP", "MOMO", "NCMI", "NFLX", "NWS", "OMC",
"OPRA", "PTNR", "PT", "PINS", "QNST", "QRTEA", "MARK", "RCI", "ROKU", "SJR",
"SHOP", "SSTK", "SINA", "SBGI", "SIRI", "SKM", "SNAP", "SOGO", "SOHU",
"STMP", "TMUS", "TTGT", "TGNA", "TEF", "TU", "TME", "TTD",
"TZOO", "TPCO", "TCOM", "TRIP", "TRVG", "TRUE", "TCX", "TWTR", "UBER",
"UCL", "USM", "UONE", "UXIN", "VEON", "VRSN", "VZ", "VIAC",
"VOD", "VG", "DIS", "WMG", "WB", "WIX", "WWE", "YNDX", "Z", "ZIXI", "ZM"]
investing_list_of_utilities_and_real_estate = ["AQN", "ALE", "LNT", "AEE", "AEP", "AWR", "AWK", "ATO", "AGR", "AVA",
"AZRE", "BKH", "BIP", "BEP", "CIG", "CNP", "EBR", "ED", "CWCO", "D",
"DUK", "EIX", "ENIA", "ENIC", "EVRG", "FE", "FTS", "GWRS", "HNP", "ITCI",
"KEP", "MGEE", "NEP", "NI", "NRG", "OGS", "ORA", "PCG", "PNW", "POR",
"PPL", "PEG", "RGCO", "SRE", "SWX", "SR", "SPH", "UGI", "UTL", "VST",
"WEC", "XEL", "ADC", "ALEX", "ALX", "ARE", "ACC", "AFIN", "AMT", "COLD",
"AHT", "AVB", "BXP", "BRX",
"BPY", "CTRE", "CBL", "CBRE", "CDR", "CLDT", "CIO", "CLNY", "CXW", "COR",
"CUZ", "CRESY", "CCI", "CUBE", "CONE", "DLR", "DEI", "DEA", "EGP",
"ESRT", "EQIX", "ELS", "EQR", "ESS", "EXPI", "EXR", "FPI-PB",
"FRT", "FPH", "FCPT", "GOOD", "LAND", "GNL", "HASI", "HTA", "PEAK", "HT",
"HST", "HPP", "IIPR", "INVH", "IRM", "MAYS", "KIM", "LMRK", "LTC", "MAC",
"CLI", "MGRC", "MPW", "MAA", "MNR", "NNN", "NMRK", "OHI", "PK", "DOC",
"PLYM", "APTS", "PLD", "PSB", "PSA", "RYN", "O", "RVI", "REXR", "RLJ",
"RMR", "SBRA", "SAFE", "BFS",
"SBAC", "SPG", "SLG", "SRC", "STAG", "STOR", "SUI", "SHO", "SKT", "TRNO",
"GEO", "UMH", "VTR", "VER", "VICI", "VNO", "WPC",
"WELL", "WY", "WSR"]
investing_list_of_oct_nov = ["TCEHY", "NSRGY", "RHHBY", "LVMUY", "PNGAY", "LRLCY", "MPNGY", "PROSY", "CIHKY", "SFTBY",
"AAGIY", "DCMYY", "SIEGY", "HESAY", "CSLLY", "ENLAY", "CMWAY", "IDEXY", "CHDRY", "NTTYY",
"PPRUY", "NPSNY", "IBDRY", "ALIZY", "DTEGY", "FRCOY", "AIQUY", "SBGSY", "NTDOY", "RCRUY",
"CHGCY", "RBGLY", "ADDYY", "DNNGY", "KDDIY", "EADSY", "NJDCY", "DMLRY", "HKXCY", "ESLOY",
"SHECY", "DPSGY", "SOBKY", "BASFY", "ADYEY", "HEINY", "DSNKY", "DKILY", "ATLKY", "ATLCY",
"BYDDY", "OLCLY", "ZURVY", "VCISY", "VWAGY", "BAYRY", "BNPQY", "SMMNY", "MRAAY", "SAFRY",
"LZAGY", "DASTY", "NABZY", "PDRDY", "MTHRY", "BMWYY", "KNYJY", "HENKY", "HENOY", "WMMVY",
"NTOIY", "HOCPY", "TOELY", "AXAHY", "FANUY", "VLVLY", "DANOY", "IFNNY", "NILSY", "ANZBY",
"DBSDY", "AHCHY", "GVDNY", "LNSTY", "CFRUY", "ITOCY", "JAPAY", "WXXWY", "WFAFY", "VONOY",
"DSDVY", "DNZOY", "SUHJY", "ECIFY", "SMCAY", "FSUGY", "SXYAY", "VIVHY", "EXPGY", "MQBKY",
"KAOOY", "MURGY", "HTHIY", "JMHLY", "VWAPY", "TKOMY", "LGFRY", "VWDRY", "NRDBY", "YAHOY",
"ENGIY", "SMICY", "CLLNY", "NGLOY", "ADRNY", "GXYYY", "JPPHY", "AMKBY", "OPYGY", "CLPBY",
"ANPDY", "DBOEY", "WEGZY", "BDRFY", "RDSMY", "ELEZY", "EONGY", "MITSY", "HSNGY", "UNICY",
"SVNDY", "HNNMY", "OVCHY", "TRUMY", "MIELY", "HCMLY", "HXGBY", "TSCDY", "SCMWY", "SHZHY",
"CJPRY", "FJTSY", "FUJIY", "RWEOY", "OCPNY", "ALPMY", "PDYPY", "CMPGY", "SSDOY", "ASAZY",
"LBRDB", "TTNDY", "ZLNDY", "CRARY", "KHNGY", "UOVEY", "BRDCY", "JSHLY", "SDVKY", "AMADY",
"HKHHY", "CKHUY", "CLPHY", "ESALY", "NEXOY", "CTTAY", "KMTUY", "SSREY", "FERGY", "TELNY",
"KRYAY", "DNHBY", "NCLTY", "SAXPY", "AONNY", "KYOCY", "KUBTY", "FSNUY", "WTKWY", "ARZGY",
"KBCSY", "OCDDY", "OEZVY", "CODYY", "GBERY", "OTSKY", "SZKMY", "PCRFY", "LGRDY", "MITEY",
"TYIDY", "UCBJY", "EJPRY", "EDPFY", "AFTPY", "ANGPY", "CABGY", "MGDDY", "SOMLY", "MKKGY",
"GCTAY", "GASNY", "CGEMY", "SSMXY", "CRHKY", "SGSOY", "KNRRY", "BAESY", "SWDBY", "AKZOY",
"DWAHY", "EPOKY", "SSEZY", "DTCWY", "HVRRY", "SOTGY", "SYIEY", "UNCRY", "NRILY", "GIKLY",
"TLPFY", "FOJCY", "NCMGY", "ASBFY", "FRRVY", "NVZMY", "SMNNY", "GZPFY", "POAHY", "SAUHY",
"PUGOY", "TKAYY", "KNBWY", "NTDTY", "SVNLY", "ASHTY", "MTSFY", "AVIFY", "BDORY", "MSADY",
"KGSPY", "SCBFY", "SONVY", "NCBDY", "UPMMY", "IMBBY", "ERRFY", "OPHLY", "OMRNY", "THLLY",
"TTDKY", "FUJHY", "SGIOY", "SSUMY", "WRDLY", "PUMSY", "RKUNY", "RNECY", "GBLBY", "VDMCY",
"TEZNY", "EVVTY", "TSGTY", "ATASY", "CGXYY", "SMPNY", "DQJCY", "CHYHY", "CRRFY", "RTOKY",
"IKTSY", "XNGSY", "TGOPY", "JPXGY", "LNNGY", "GBOOY", "SCVPY", "DFKCY", "SCGLY", "AHKSY",
"WOPEY", "SWMAY", "MKTAY", "DNKEY", "NNGRY", "MONOY", "ILIAY", "CZMWY", "SKHHY", "HALMY",
"HDELY", "TOSYY", "HPGLY", "EDNMY", "SEOAY", "SGBLY", "SZLMY", "UBSFY", "SKHSY", "SZSAY",
"SWGAY", "NDEKY", "VEOEY", "FNMA", "STBFY", "FYRTY", "ASXFY", "HGKGY", "NXGPY", "BZLFY",
"RMYHY", "REPYY", "GNNDY", "AJINY", "BXBLY", "COIHY", "AUCOY", "JDSPY", "PSMMY", "JRONY",
"ALSMY", "YASKY", "CHEOY", "AMIGY", "KKOYY", "GJNSY", "JBAXY", "SNYFY", "SDXAY", "ATEYY",
"SUTNY", "RANJY", "NPSCY", "RDEIY", "YATRY", "MTUAY", "TKGSY", "HRGLY", "BNTGY", "UMICY",
"KIGRY", "MONDY", "KIROY", "JBSAY", "UHID", "MARUY", "COVTY", "YARIY", "SBSNY", "DSCSY",
"ORKLY", "SKFRY", "GNHAY", "KIKOY", "AYALY", "SMFKY", "SOLVY", "INGIY", "CCHGY", "TMVWY",
"SMMYY", "ASEKY", "SGPYY", "PUBGY", "QBIEY", "REMYY", "YAMCY", "EBKDY", "OTGLY", "SMTOY",
"IFJPY", "MTLHY", "AHEXY", "ALFVY", "DNTUY", "WJRYY", "MHGVY", "SKBSY", "KAEPY", "CUYTY",
"CNPAY", "ITTOY", "KSRYY", "LSRCY", "AGESY", "TLTZY", "ROHCY", "OMVKY", "KGFHY", "GLIBB",
"AAVMY", "LZRFY", "YKLTY", "RNLSY", "TMSNY", "SKSUY", "SNMCY", "PANDY", "SVCBY", "WILYY",
"HEGIY", "BDNNY", "CYGIY", "AEXAY", "TMICY", "SRTTY", "IMPUY", "GMVHY", "EFGSY", "HKMPY",
"UUGRY", "ARKAY", "STRNY", "ALNPY", "MNBEY", "TOTDY", "BKHYY", "ACSAY", "VLEEY", "SQNNY",
"KOTMY", "PRYMY", "ACOPY", "NNCHY", "CCOEY", "BURBY", "GLPEY", "IPSEY", "RTMVY", "SNPHY",
"ATDRY", "SMGZY", "TOKUY", "TISCY", "ISUZY", "ELUXY", "ACCYY", "SPXCY", "BTDPY", "BLHEY",
"ASGLY", "MCARY", "MAGOY", "VOPKY", "MDIBY", "TDHOY", "AMBBY", "BKGFY", "CRZBY", "AACAY",
"MAEOY", "FUPBY", "HLTOY", "GEHDY", "JSGRY", "DIFTY", "JAPSY", "PSZKY", "AMSSY", "EGIEY",
"SHCAY", "DNPLY", "BGAOY", "RGLXY", "CCLAY", "BMRRY", "HTCMY", "GEAGY", "LLESY", "IDKOY",
"ORINY", "RYKKY", "OUKPY", "TMRAY", "HSQVY", "CLZNY", "CKHGY", "NHYDY", "ENGGY", "WTBDY",
"JSAIY", "FMCC", "ASOMY", "HLUYY", "KAJMY", "RSNAY", "IESFY", "AGLXY", "JMPLY", "SALRY",
"SKLTY", "KNMCY", "LNEGY", "LRENY", "PEGRY", "DLAKY", "HLLGY", "CIBEY", "SHMUY", "PGENY",
"GTMEY", "YZCAY", "OSAGY", "MITUY", "WEGRY", "NPPNY", "CAKFY", "JCYGY", "LDSCY", "TSUKY",
"DCYHY", "YAMHY", "GNGBY", "HWDJY", "DMZPY", "JSCPY", "HKUOY", "TAIPY", "BNCDY", "AGRPY",
"PHPPY", "WRTBY", "SRGHY", "SCRYY", "AZIHY", "VLPNY", "RICOY", "RAIFY", "TYOYY", "SLOIY",
"CMSQY", "RYHTY", "BLSFY", "AVHNY", "TOPPY", "FELTY", "FCNCB", "NPSKY", "TSRYY", "TLGHY",
"EKTAY", "OCLDY", "TKAGY", "CDEVY", "EVTCY", "ASMVY", "CWLDY", "SUOPY", "BZZUY", "MAHLY",
"HINOY", "NKRKY", "NIPMY", "CHBAY", "VEMLY", "TEPCY", "ABCZY", "YOKEY", "FLGZY", "SHZUY",
"ROSYY", "MAURY", "FOVSY", "KYSEY", "BRTHY", "SEKEY", "TPRKY", "CLBEY", "GULRY", "CSXXY",
"CSIOY", "IMIAY", "TATYY", "JTTRY", "AUOTY", "FPRUY", "FMOCY", "THUPY", "WYGPY", "CLCGY",
"RBSFY", "IGGHY", "MCHOY", "ANSLY", "NGKSY", "MTGGY", "TKGBY", "RXEEY", "MZDAY", "THKLY",
"RNMBY", "ADRZY", "TPDKY", "KZMYY", "NCHEY", "EBRPY", "MNHFY", "AKABY", "KURRY", "SIETY",
"THYCY", "SGAMY", "ITJTY", "NDBKY", "HYPMY", "MALRY", "FINN", "KWPCY", "SKLKY", "SBFFY",
"NPNYY", "TKAMY", "AKBTY", "VNRFY", "DUFRY", "WBRBY", "TINLY", "GOFPY", "APELY", "CCOJY",
"ESYJY", "FINMY", "PBSFY", "EVNVY", "TGOSY", "BDVSY", "APNHY", "ELPVY", "STWRY", "CSNVY",
"AWCMY", "GLAPY", "NIFCY", "AIAGY", "GWPRF", "NHNKY", "EOCCY", "CGUSY", "MSLOY", "PUODY",
"JTEKY", "SOHVY", "BTVCY", "ZNKKY", "TKCBY", "SHWDY", "EBCOY", "DURYY", "ASCCY", "ISSDY",
"YORUY", "SREDY", "NTNTY", "BSEFY", "SFRGY", "CHRYY", "BCNAY", "KNCRY", "TBLMY", "TCCPY",
"MAKSY", "NINOY", "JGCCY", "PKCOY", "ETCMY", "MRPLY", "ANIOY", "MAUSY", "NPSHY", "BCUCY",
"FJTNY", "CBGPY", "BICEY", "SUBCY", "INCPY", "WETG", "ENGH", "FHNIY", "KWHIY", "IIJIY",
"JUMSY", "EFGXY", "IHICY", "FJTCY", "AOZOY", "TROLB", "KRNTY", "UBEOY", "BOSSY", "VIAAY",
"BPOSY", "BVNRY", "TRHFD", "BKUH", "OIBRQ", "FUWAY", "KUKAY", "ILKAY", "VTKLY", "TREAY",
"NPKYY", "THDDY", "CSVI", "TKYMY", "COGNY", "HAWPY", "SBLUY", "MMSMY", "RSTAY", "TGSGY",
"KPLUY", "FLIDY", "ASOZY", "HHULY", "SMSMY", "YITYY", "JPSWY", "WACLY", "TYOBY", "RKAGY",
"ISMAY", "MOHCY", "DNIYY", "KAIKY", "WACMY", "SYANY", "TCLRY", "SZGPY", "BOZTY", "BFLBY",
"WTBFA", "WTBFB", "CYBQY", "TDPAY", "PLFRY", "LTMAQ", "NVGI", "BIOGY", "FMBL", "ERMAY",
"TOGL", "CCGGY", "MDXG", "HWAL", "ADPXY", "VSBC", "HXOH", "FBAK", "HBIA", "FMCB", "USAT",
"TMOAY", "GANS", "NPACY", "NASB", "SBOEY", "BERK", "EMIS", "SPHRY", "RWWI", "LICT", "RTTO",
"SMLR", "SBNC", "KLDI", "MCHB", "KCLI", "CNND", "OTCM", "VADP", "ARTNB", "BHRB", "BWMYD",
"RCAR", "DGRLY", "CRCW", "SEMUF", "THVB", "FNGR", "AIXN", "FRMO", "EVSBY", "SCPJ", "MCCK",
"GFASY", "MGOM", "MCEM", "EOSS", "ATROB", "CUSI", "PKIN", "ORXOY", "AYAG", "FIZN", "EXSR",
"VLOWY", "TTSH", "MRTI", "CSHX", "SMTI", "ATCN", "FKWL", "LNNNY", "BVHBB", "WNDW", "NODB",
"HONT", "FNBT", "AMBZ", "CZFS", "JMSB", "GFKSY", "CFNB", "RCBC", "TGRF", "VNJA", "MLGF",
"VULC", "WMPN", "BKUT", "FCUV", "HLAN", "RZLTD", "WFTLF", "WNRP", "RVRF", "TRCY", "NECB",
"FFMH", "GDRZF", "ISBA", "EVOA", "CNBW", "CYFL", "WINSF", "TRUX", "NLST", "PURE", "TPRP",
"NWIN", "TYFG", "POWW", "PTGEF", "AKOM", "CWGL", "HMLN", "FKYS", "MDWT", "SCZC", "FNRN",
"GMGI", "BNCC", "LGIQ", "ENBP", "TYCB", "KSHB", "BVFL", "SBKK", "CHBH", "XTEG", "LQMT",
"LSYN", "QNBC", "PDER", "MHGU", "AERO", "KTYB", "RVRA", "BKUTK", "ICTSF", "EMYB", "MCBK",
"EACO", "CPKF", "MCBI", "JUVF", "CSBB", "CPTP", "PSIX", "CTGO", "NVOS", "BBBK", "OCBI",
"BAYK", "NUVR", "UTGN", "PSBQ", "LYBC", "NOBH", "EFSI", "CCFN", "KEWL", "BKGM", "JDVB",
"FGFH", "SCBH", "RRTS", "DMKBA", "MSBC", "DIMC", "ROFO", "HNFSA", "HNFSB", "APTL", "CVLBD",
"INTEQ", "HARL", "PFLC", "HSBI", "FABP", "NEFB", "SFDL", "LIXT", "FBTT", "EMPK", "WBBW",
"ELAMF", "PLTYF", "HWIN", "BMBN", "AMNF", "CMTV", "FFDF", "AMSIY", "SCTY", "CZBC", "ARHN",
"TYBT", "SOBS", "QEPC", "LWLG", "BHWB", "CNRD", "JFBC", "MODD", "BCAL", "CNBB", "KEGX",
"AMBK", "SABK", "PBAM", "MMMB", "ADOCY", "GWOX", "CURR", "ZMTP", "SOMC", "PRED", "CWBK",
"SILXY", "AVBH", "LBTI", "VABK", "WEBC", "REDW", "FETM", "CFCX", "NWYF", "BIOQ", "KTHN",
"GRRB", "FMBM", "PFOH", "UBNC", "SOTK", "INLB", "TRVR", "CLWY", "ELLH", "CCEL", "VLLX",
"SQCF", "MYBF", "CULL", "REEMF", "JCPNQ", "WAYN", "CZBT", "ELTP", "FACO", "TWCF", "CRSS",
"VKSC", "BURCA", "COSM", "WCRS", "ARBV", "CRAWA", "LINK", "IFHI", "SEBC", "LFGP", "KRPI",
"FISB", "CFST", "PKKW", "NACB", "DYNE", "MHPC", "TRNLY", "RVCB", "AVHOQ", "PFBX", "CNIG",
"KANP", "CHUC", "CBKM", "MCRAA", "MCRAB", "RSKIA", "SHWZ", "DWNX", "INVU", "HBSI", "PYYX",
"WLFDY", "SBBI", "UNIB", "UBAB", "CVSI", "CZNL", "WFCF", "PGTK", "FMFP", "TUESQ", "MFON",
"SCSG", "CNAF", "PMHG", "SMAL", "CIBY", "PKDC", "HLFN", "YDVL", "YRKB", "EPGNY", "FTMR",
"FFWC", "NIDB", "BTTR", "SHRG", "WLMS", "TETAA", "TETAB", "CFIN", "BELP", "NWPP", "MRMD",
"SBKO", "NUBC", "ECRP", "FMFG", "BOREF", "ACMTA", "ACMT", "BSHI", "IEHC", "UWHR", "FBVA",
"BSFC", "SRYB", "NJMC", "WEIN", "SLNG", "BEBE", "CTAM", "CUII", "SMID", "SUME", "EMGCQ",
"CEFC", "SRRE", "PPHI", "TLCC", "TTLO", "PGCG", "SBBG", "STBI", "ORBN", "WDFN", "FLFG",
"HFBA", "BUKS", "FOTB", "PCLB", "BCTF", "VKIN", "TPCS", "EQFN", "IOFB", "MUEL", "ATGN",
"NTRB", "FDVA", "PTBS", "OTTW", "PRSI", "VTDRF", "IVST", "SIMA", "CNCG", "GNRV", "CTUY",
"TORW", "STMH", "MDVT", "LSFG", "BORT", "KSBI", "PBSV", "TLRS", "MPAD", "BSPA", "ONVC",
"RYFL", "LEAT", "HRST", "PPBN", "BSCA", "OSBK", "FCOB", "PMTS", "HCBC", "FSRL", "TGEN",
"FBPA", "AFAP", "FBPI", "MEEC", "BEOB", "BKOR", "CCUR", "PGNN", "LOGN", "PWBO", "SLRK",
"HFBK", "ALMC", "CRMZ", "BMMJ", "GLGI", "EFBI", "OXBC", "BLHK", "UGRO", "SOFO", "OMQS",
"NANX", "PEGX", "SYCRF", "GVYB", "SFBK", "CIWV", "CFOK", "MACE", "MRGO", "BRBW", "PRKA",
"CNBZ", "SCTC", "PNBI", "CBCZ", "HLIX", "TMAK", "CNBX", "GOVB", "CHHE", "SCND", "SDRLF",
"HCBN", "DVCR", "JCDAF", "MAAL", "QNTO", "RSRV", "TRNF", "RWCB", "CZBS", "PBNK", "INIS",
"UNTN", "GTPS", "SCAY", "DTST", "AYSI", "SLGD", "STLY", "MVLY", "MNBO", "OTIVF", "GTMAY",
"EMMS", "FALC", "FBSI", "SCYT", "FRFC", "APLO", "SCXLB", "CBFC", "HCGI", "PEBC", "PHCG",
"CIBH", "PBCO", "IBWC", "NWBB", "CYTR", "SVBL", "GLXZ", "SPGZ", "WAKE", "OPXS", "ORBT",
"ADOM", "MKTY", "RYES", "WCFB", "TDCB", "CUEN", "PAYD", "CRSB", "HLSPY", "CCBC", "FRSB",
"FIDS", "OPST", "HRGG", "ELMA", "PIAC", "AGOL", "LXRP", "AMEN", "SSBP", "CTYP", "RAFI",
"PEYE", "JKRO", "TLSS", "GVFF", "DYNR", "FTLF", "CLOK", "DYSL", "EGDW", "MOBQ", "CCFC",
"TBBA", "SVIN", "CAWW", "PVBK", "HVLM", "DAFL", "FNFI", "FHLB", "SADL", "SNNF", "INBP",
"ERKH", "TRTC", "SECI", "IDWM", "TBTC", "SPND", "ABCP", "IVFH", "PPSF", "CNBA", "HWEN",
"NNUP", "HRTH", "GRMM", "PFHO", "AMFC", "RGBD", "CRZY", "NUKK", "FTDL", "AWSMD", "BXLC",
"DTRL", "TIKK", "ALTN", "ACAN", "KBPH", "ESOA", "OHPB", "NSYC", "GIGA", "ENZN", "TSSI",
"LPBC", "SUWN", "VFRM", "TRKX", "HWIS", "SURG", "BRRE", "FAME", "HCMC", "BMNM", "MAJJ",
"FCCT", "ZXAIY", "HOOB", "JSDA", "SPCO", "SMDM", "SYTE", "SNNY", "EFSH", "SENR", "NROM",
"CCOM", "VERF", "TOOD", "TOFB", "AMCT", "MXMTY", "OART", "IAIC", "SPRS", "ADMT", "AQSP",
"CIBN", "NAUH", "ANFC", "BKFG", "EUSP", "INRD", "HEWA", "QMCI", "CSTI", "ITEX", "JANL",
"LUVU", "DTRK", "IBAL", "VIDE", "CBKC", "MCVT", "ABLT", "ALPP", "SORT", "SUGR", "ALBY",
"AMMX", "MICR", "TCNB", "FSCR", "WELX", "VVUSQ", "RHDGF", "NEBLQ", "YEWB", "GNCIQ", "MGTI",
"FMBN", "PGNT", "XOGAQ", "CRVW", "YRIV", "EDHD", "ECIA", "SCIA", "IONI", "PALT", "SKTP",
"LCTC", "SRNA", "CLWD", "DWOG", "SRNN", "UNIR", "ABBB", "AAON", "ABB", "ACNB", "ABM",
"AGCO", "ACMR", "AHC", "ALJJ", "AMAG", "AMCX", "HKIB", "AMRK", "APG", "AACG", "ABIO",
"LIFE", "ASX", "AZZ", "ABEO", "AXAS", "ACAM", "ACEL", "ARAY", "ACER", "ACRX", "ACRS",
"ACU", "ATV", "AYI", "GOLF", "ADMS", "AE", "ADAP", "ADXN", "ADIL", "ACET", "ADRO", "AEHR",
"ADXS", "AEGN", "AMTX", "ACY", "AGLE", "AJRD", "WMS", "AEMD", "AIH", "ARPO", "AGFS",
"ALRN", "AIM", "AIRI", "AIRT", "ATSG", "ANTE", "AKTX", "AKER", "ALSK", "AIN", "ALDX",
"ALRS", "ALCO", "ALIM", "WTER", "Y", "ATI", "ABTX", "ALNA", "AESE", "ALSN", "ATEC", "ALPN",
"ALTG", "ALTA", "ALTR", "ALT", "ATHE", "ATUS", "AIMC", "ALTM", "ACH", "AMAL", "ABEV",
"AMBO", "DIT", "AMTB", "AMTBB", "UHAL", "AMRH", "AMX", "AMOV", "AXL", "AEO", "AEL", "AFG",
"ANAT", "AMNB", "AOUT", "ARL", "ARA", "AREC", "AMRB", "AVD", "AVCT", "ASRV", "ATLO",
"AMPE", "AMHC", "AMPY", "AXR", "AMYT", "AMRS", "AVXL", "ANCN", "ANDE", "ANIX", "ANVS",
"AR", "APEX", "APOG", "AINV", "APEN", "AIT", "AGTC", "AMTI", "ATR", "APVO", "APTX", "APYX",
"AQMS", "ARMK", "ARAV", "RKDA", "ARCB", "ACA", "ARNC", "RCUS", "ARGX", "ARDS", "ARKR",
"ARMP", "AFI", "AWI", "ARW", "ARTL", "ARTNA", "ARTW", "ABG", "AINC", "ASH", "ASLN", "ASPN",
"ASPU", "AWH", "ASRT", "AMK", "ASFI", "ASTE", "ALOT", "ASTC", "ATKR", "AAME", "ACBI",
"ATLC", "AAWW", "ATCX", "ATOS", "AUBN", "JG", "ALV", "AUTL", "AUTO", "AWX", "AVYA", "AVEO",
"ATXI", "CDMO", "AVNT", "RCEL", "AXLA", "AX", "AYLA", "AYTU", "AZYO", "BBX", "AZUL",
"AZRX", "BGCP", "BBQ", "RILY", "BKTI", "BRP", "BMCH", "BWXT", "BW", "BCSF", "BTN", "BBAR",
"BBD", "BBDO", "BBVA", "BCH", "BMA", "SAN", "BSAC", "BSBR", "CIB", "TBBK", "BXS", "BANC",
"BFC", "BMRC", "BOCH", "BPRN", "BKSC", "BFIN", "BSVN", "BWFG", "BHB", "BCS", "BNED", "B",
"BRN", "BSET", "BATL", "BCML", "BBGI", "BZH", "BELFA", "BELFB", "BLPH", "BRBR", "BNTC",
"WRB", "BRK-A", "BHLB", "BERY", "BRY", "XAIR", "BCYC", "BRPA", "BH", "BH-A", "BIO-B",
"BIO", "BPTH", "BCDA", "BMRA", "BLRX", "BSGM", "BVXV", "BHTG", "BIVI", "BFRA", "BITA",
"BKI", "BKCC", "TCPC", "BCAT", "BLBD", "BRBS", "BLCT", "BXC", "BXG", "BSBK", "BIMI",
"BPFH", "BWL-A", "BCLI", "BWAY", "BRFS", "BAK", "LND", "BBI", "BLIN", "BWB", "BRID",
"MNRL", "BFAM", "BEDU", "BSIG", "BCO", "VTOL", "BWEN", "BKD", "BRKL", "BMTC", "BSQR",
"BBW", "BFST", "BY", "CFFI", "CBFV", "CBZ", "YCBD", "CBMB", "CBOE", "CDK", "CECE", "CFBK",
"CHFS", "CIT", "CHPM", "CKX", "CVU", "CNA", "CCNE", "CEO", "CRAI", "CPSH", "CNO", "CRH",
"CSPI", "CSWI", "CTIC", "CNX", "CVV", "CBT", "CDZI", "CLBS", "CALB", "CWT", "CALA", "ELY",
"CALT", "CLXT", "CEI", "CATC", "CAC", "CANF", "CGIX", "CANG", "CNNE", "CAJ", "CMD", "CPHC",
"CCBG", "CBNK", "CSU", "CSWC", "CPST", "CAPR", "CSTR", "CG", "CUK", "CSV", "PRTS", "TAST",
"CARS", "CARE", "CWST", "CASY", "CASI", "CASS", "SAVA", "CSLT", "CATB", "CTLT", "CBIO",
"CVCO", "CVM", "CELC", "APOP", "CLDX", "CLRB", "CLLS", "CLSN", "CBMG", "CYAD", "CPAC",
"CX", "CETX", "CDEV", "EBR", "CENT", "CENTA", "CPF", "CEPU", "CVCY", "CENX", "CNBKA",
"LEU", "CNTY", "CCS", "CERC", "CDAY", "CSBR", "CHX", "CHRA", "CHAQ", "CTHR", "CRL", "GTLS",
"CCF", "CKPT", "CMCM", "CEMI", "CHE", "CC", "CHMG", "LNG", "CPK", "CHMA", "CVR", "CSSE",
"CHS", "CREG", "CMRX", "CAAS", "JRJC", "CEA", "LFC", "ZNH", "SNP", "CHA", "CGA", "DL",
"CXDC", "HGSH", "CJJD", "CNET", "COE", "CIH", "COFS", "CDXC", "CHDN", "CDTX", "CBB",
"CNNB", "CIR", "CZNC", "CTRN", "CTXR", "CFG", "CIZN", "CIA", "CZWI", "CIVB", "CLAR", "CLH",
"CLSK", "CCO", "CLSD", "CLIR", "CLRO", "CLPT", "CLW", "CWEN-A", "CWEN", "CBLI", "CNSP",
"CNF", "CCB", "COKE", "KOF", "CODA", "CCNC", "CVLY", "CDE", "JVA", "CGNX", "CNS", "CWBR",
"COHN", "CLCT", "CGRO", "CLGN", "CBAN", "CLBK", "COLM", "CMCO", "CBSH", "CMC", "CVGI",
"ESXB", "CYH", "TCFC", "CFBI", "JCS", "CTBI", "CWBC", "CIG-C", "CBD", "SID", "SBS", "ELP",
"CCU", "CMP", "CIX", "SCOR", "CHCI", "LODE", "CNCE", "CCM", "BBCP", "CNFR", "CNMD", "CNOB",
"CONN", "STZ-B", "ROAD", "CPSS", "TCS", "MCF", "CFRX", "VLRS", "CTRA", "CPS", "CTB", "CTK",
"CORE", "CMT", "CRMD", "CNR", "CLDB", "CRVS", "ICBK", "CPAH", "CVLG", "CBRL", "BREW", "CR",
"CRD-B", "CRD-A", "CRTD", "CREX", "CS", "CCAP", "CXDO", "CFB", "CRWS", "CCK", "CRY", "CTO",
"CFR", "CULP", "CPIX", "CRIS", "CURO", "CUBI", "CYAN", "CYCC", "CYCN", "CTEK", "CTSO",
"BOOM", "DHX", "DLHC", "DXPE", "DFPH", "DARE", "DQ", "DRIO", "DSKE", "DAIO", "DTSS",
"DWSN", "DXR", "DECK", "DCTH", "DK", "DLA", "DEN", "DLX", "DBI", "DXLG", "DHIL", "DBD",
"DRAD", "DGLY", "DCOM", "DMS", "DIN", "DISCB", "DXYN", "RDY", "DLB", "UFS", "DCI", "DGICA",
"DGICB", "RRD", "DFIN", "DORM", "PLOW", "DVD", "DPW", "DS", "DCO", "DLTH", "DUOT", "DXF",
"DRRX", "DYAI", "DY", "DT", "DZSI", "EDAP", "EH", "E", "EVOP", "EVI", "EBMT", "FCRD",
"EXP", "ESTE", "EWBC", "EML", "EAST", "ECHO", "MOHO", "EC", "EPC", "EDNT", "EDUC", "EIGR",
"BCOW", "ETNB", "EKSO", "ELAN", "ELSE", "ELMD", "ELVT", "ESBK", "ELOX", "EMAN", "AKO-A",
"AKO-B", "EMCF", "ERJ", "EBS", "MSN", "EIG", "EDN", "WIRE", "EHC", "EFOI", "ENR", "NDRA",
"ENS", "EPAC", "ENG", "EBF", "ENOB", "NPO", "ENSV", "ETTX", "ENTG", "ETM", "EBTC", "EFSC",
"EVC", "ELA", "ENZ", "NVST", "EQH", "ETRN", "EQBK", "EQS", "ERYP", "ESCA", "ESE", "ESP",
"ESSA", "ESQ", "GMBL", "WTRG", "ETH", "EEFT", "EVBN", "EVLO", "EVK", "EVER", "EPM", "EVOK",
"EVOL", "EOLS", "XGN", "XCUR", "EXLS", "XONE", "EXPC", "EXPR", "EZPW", "EYEG", "EYEN",
"FFG", "FNB", "FNCB", "FBK", "FFBW", "FSBW", "FTSI", "FRPH", "FCN", "FLMN", "SFUN", "DUO",
"FARM", "FMAO", "FMNB", "FARO", "FBSS", "AGM-A", "AGM", "FSS", "FHI", "FNHC", "FOE",
"FDBC", "FNF", "FDUS", "FRGI", "JOBS", "FISI", "FINV", "FAF", "FNLC", "FBNC", "FBMS",
"FRBA", "FBIZ", "FCAP", "FCBP", "FCF", "FCCO", "FCBC", "FCCY", "FFBC", "THFF", "FFNW",
"FFWM", "FGBI", "INBK", "FIBK", "FLIC", "FRME", "FMBH", "FMBI", "FXNC", "FNWB", "FSFG",
"FSEA", "FUNC", "FUSB", "MYFW", "SVVC", "FBC", "FIVE", "WBAI", "FPRX", "FVE", "BDL",
"FLXS", "FLXN", "FPAY", "FND", "FTK", "FLO", "FLNT", "FFIC", "FLUX", "FLY", "FOCS", "FMX",
"FONR", "FORTY", "FRTA", "FBRX", "FBHS", "FET", "FWRD", "FWP", "FIII", "FSTR", "FBM",
"FEDU", "FOX", "FRAN", "FC", "FRAF", "RAIL", "FMS", "FRD", "FTEK", "FSKR", "FUBO", "FULC",
"FLGT", "FLL", "FUL", "FF", "FTFT", "FVCB", "GBL", "GLIBA", "JOB", "GDS", "GWGH", "GPX",
"GVP", "GIII", "GTT", "GXGX", "GMS", "GAIA", "GLPG", "GALT", "GRTX", "GARS", "GENC",
"GNSS", "GNRC", "GMO", "GCO", "GENE", "GEN", "GNFT", "GNE", "GMAB", "GNMK", "GNCA", "THRM",
"GOVX", "GGB", "GABC", "ROCK", "GLAD", "GLT", "GKOS", "GLBZ", "GSAT", "GMED", "GBLI",
"GLYC", "GOL", "GFI", "GORO", "AUMN", "GV", "GSBD", "GBDC", "GTIM", "GDP", "GRSV", "GHIV",
"GRC", "GRA", "GGG", "GHC", "GRAM", "GTE", "LOPE", "GVA", "GPK", "GTN", "GTN-A", "GECC",
"GEC", "GLDD", "GSBC", "GWB", "GRBK", "GDOT", "GPRE", "GCBC", "GHL", "GNLN", "GNRS",
"GRNQ", "GEF", "GEF-B", "GSUM", "GRIF", "GRFS", "GRTS", "GPI", "GGAL", "SIM", "TV", "OMAB",
"PAC", "ASR", "AVAL", "SUPV", "GSH", "GNTY", "GFED", "GIFI", "GURE", "GPOR", "GYRO", "HBT",
"HCHC", "HCI", "HFFG", "HMNF", "HNI", "HTGM", "HVBC", "HAE", "HAIN", "HLG", "HNRG", "HOFV",
"HALL", "HBB", "HWC", "HJLI", "HNGR", "HAFC", "HONE", "HMY", "HARP", "HROW", "HSC", "HCAP",
"HVT", "HVT-A", "HE", "HA", "HWKN", "HWBK", "HAYN", "HCSG", "HHR", "HCAT", "HTLD", "HL",
"HEI-A", "HLIO", "HSDT", "HLX", "HMTV", "HNNA", "HTBK", "HRI", "HTGC", "HFWA", "HRTG",
"HESM", "HXL", "HX", "HPR", "HPK", "HIL", "HI", "HGV", "HIFS", "HQI", "HSTO", "HOL", "HFC",
"HOMB", "HBCP", "HFBL", "HMST", "HTBI", "HMC", "HOFT", "HOOK", "HMN", "HBNC", "HZN",
"TWNK", "HOTH", "HWCC", "HOV", "HBMD", "HHC", "HUBG", "HTHT", "HEC", "HSON", "HDSN",
"HUIZ", "HGEN", "HII", "HUN", "HURC", "HURN", "HCM", "HYMC", "IDT", "HYRE", "HY", "IAA",
"ICFI", "ICCH", "ICAD", "IEC", "IROQ", "IESC", "IFMK", "IMAC", "IRS", "ITCB", "ITT", "IBN",
"ICON", "IEP", "IDA", "ICLK", "IPWR", "IDYA", "IEX", "IDRA", "IKNX", "ISNS", "IMBI",
"IMRA", "ICCC", "IMNPQ", "IMH", "IMMP", "IMVT", "IMUX", "PI", "ICD", "IHC", "INDB", "IBCP",
"IBTX", "IBA", "INFI", "III", "INFY", "ING", "INFU", "IEA", "NGVT", "INGR", "INOD", "ISIG",
"IOSP", "ISSC", "INSP", "INWK", "IIIN", "NSPR", "IBP", "IPHA", "INMB", "IHT", "INS", "IDN",
"ITGR", "IHG", "INTG", "IBOC", "IMXI", "IDXG", "IPV", "XENT", "ICMB", "INTT", "IVC", "IIN",
"IPI", "INUV", "ISTR", "ITIC", "NVIV", "IO", "IRMD", "IRIX", "IRCP", "ISR", "ISDR", "ITP",
"ITMR", "ITI", "IIIV", "ISEE", "YY", "JJSF", "JAX", "JILL", "JACK", "BOTJ", "JHX", "JAN",
"JELD", "JRSH", "JT", "JYNT", "JLL", "JNCE", "JP", "JIH", "KAR", "KB", "KBR", "KLXE", "KT",
"KDMN", "KALU", "KLDO", "KLR", "KALV", "KAMN", "KSPN", "KBH", "KRNY", "KELYB", "KMPH",
"KMT", "KFFB", "KROS", "KTCC", "KZR", "KIN", "KC", "KINS", "KFS", "KTRA", "KEX", "KIRK",
"KNL", "KNX", "KN", "KOP", "KOSS", "KTOS", "KRA", "KRO", "LCNB", "LGL", "LPL", "LGIH",
"LKQ", "LCII", "DFNS", "LMFA", "LPLA", "LXU", "LYTS", "LJPC", "LZB", "LAIX", "LSBK",
"LBAI", "LW", "LANC", "LNDC", "LARK", "LE", "LCI", "LPI", "LRMR", "LAWS", "LAZY", "LEAF",
"LEA", "LPTX", "LEE", "LEGH", "LEGN", "LACQ", "LC", "LEN-B", "LII", "LEVL", "LBRT", "LWAY",
"LFVN", "LCUT", "LTBR", "LPTH", "LITB", "LSAC", "LMST", "LMB", "LMNR", "LINC", "LIND",
"LNN", "LCTX", "LN", "LINX", "LGHL", "LIQT", "LQDA", "LOAK", "LIVE", "LIVX", "LXEH", "LYG",
"LMPX", "LOGC", "LOMA", "LONE", "LGVW", "LOOP", "LPX", "LOVE", "LUB", "LL", "LBC", "LDL",
"LYRA", "MBI", "MDC", "MTG", "MHO", "MKSI", "MMAC", "MRC", "MSA", "MSM", "MSGN", "MTBC",
"MVBF", "MVC", "MYRG", "MCBC", "MFNC", "MIC", "MSGS", "MSGE", "MGTA", "MX", "MGY", "MGYR",
"MNSB", "MBUU", "MLVF", "TUSK", "MTW", "MTEX", "MN", "MMI", "MCS", "MRIN", "MPX", "MRNS",
"MRLN", "MBII", "MRTN", "MTZ", "MHH", "MCFT", "MTDR", "MTRN", "MTNB", "MTRX", "MATX",
"MLP", "MMS", "MEC", "MKC-V", "MUX", "MTL-P", "MTL", "MFIN", "MDLA", "MDIA", "MED", "MDGS",
"MD", "MCC", "MDLY", "MLCO", "MBWM", "MERC", "MBIN", "MFH", "MREO", "MCMJ", "MRBK", "EBSB",
"MTOR", "MACK", "MESA", "MLAB", "CASH", "MEI", "MCBS", "MCB", "MXC", "MFGP", "MVIS",
"MBOT", "MPB", "MSVB", "MBCN", "MSEX", "MOFG", "MLSS", "MLND", "MLR", "MIND", "MTX",
"NERV", "MGEN", "MSON", "MG", "MUFG", "MFG", "MBT", "MOD", "MWK", "MKD", "MBRX", "MOH",
"TAP-A", "MKGI", "MNPR", "MRCC", "MR", "MOG-A", "MOG-B", "MORN", "MOR", "MOSY", "MPAA",
"MOTS", "MOV", "MOXC", "MLI", "MWA", "GRIL", "MBIO", "MYE", "MYO", "MYOS", "NBTB", "NCR",
"NCSM", "NL", "NNBR", "NVEE", "NNVC", "NNDM", "NAOV", "NATH", "NBHC", "NKSH", "NHC", "NFG",
"NGHC", "NGG", "NHLD", "NPK", "NSEC", "EYE", "NWLI", "NAII", "NTCO", "NHTC", "NGVC",
"NATR", "NWG", "NTZ", "NAV", "NAVB", "NP", "NMRD", "NLTX", "NEON", "NEOS", "NEPH", "NSCO",
"UEPS", "NTWK", "NTIP", "NURO", "NTRP", "STIM", "NBSE", "NRBO", "NVRO", "GBR", "NFE",
"NWHM", "NJR", "NMFC", "NPA", "NYC", "NYCB", "NYT", "NBEV", "NWGI", "NEU", "NR", "NEWT",
"NEX", "NXST", "NEXT", "NODK", "NXGN", "NCBS", "NINE", "NOAH", "NMR", "NDLS", "NDSN",
"NSYS", "NBN", "NOG", "NFBK", "NRIM", "NWN", "NWPX", "NWE", "NWFL", "NVFY", "NVUS", "NUS",
"NCNA", "NUZE", "OGE", "OLB", "NXTD", "NES", "OFS", "OIIM", "OPBK", "OVLY", "OCSL", "OCSI",
"OAS", "OBLN", "OBLG", "OBCI", "OPTT", "OII", "OFED", "OCN", "OCUL", "OMEX", "OVBC", "ODC",
"OIS", "OPOF", "OSBC", "OLN", "ZEUS", "OFLX", "ONDK", "ONCS", "OCX", "ONCT", "PIH", "YI",
"OMF", "ONEW", "ONTO", "OOMA", "LPRO", "OPNT", "OPRT", "OPY", "OCC", "OPHC", "OPRX",
"ORMP", "OPTN", "ORAN", "ORBC", "OEG", "ORGS", "ONVO", "ORGO", "OBNK", "ORIC", "OESX",
"ORN", "IX", "ORRF", "OSK", "OSN", "OTEL", "OTIC", "OTTR", "OTLK", "OSG", "OVID", "OVV",
"OC", "ORCC", "OXM", "PFIN", "PDLB", "PAE", "PTSI", "CNXN", "PCB", "PCSB", "PDCE", "PICO",
"PGTI", "PJT", "PHI", "PKX", "PNM", "PRAA", "PRGX", "PUYI", "PMBC", "PKG", "PTN", "PAM",
"PHX", "PZZA", "PAR", "PARR", "PZG", "TEUM", "PRK", "PKOH", "PSN", "PTRS", "PBHC", "PATK",
"PNBK", "PATI", "PTEN", "PDSB", "PGC", "PSO", "PED", "PVAC", "PNTG", "PNNT", "PFLT",
"PWOD", "PAG", "PEN", "PEBO", "PEBK", "PFIS", "PRCP", "PRDO", "PFGC", "PFMT", "PESI",
"PPIH", "PRSP", "PSNL", "TLK", "PTR", "PBR-A", "PFNX", "PHAS", "FENG", "DNK", "PHR",
"PHUN", "PIRS", "PBFS", "PPSI", "PIPR", "PAGP", "PLAG", "PLT", "AGS", "PLBC", "PSTI",
"PSTV", "PLXP", "PTE", "PTMN", "POST", "PBPB", "PWFL", "PQG", "PFBC", "POAI", "PLPC",
"PFBI", "PBH", "PSMT", "PNRG", "PRIM", "PFG", "PDEX", "PRTH", "IPDN", "PFHD", "PFIE",
"PRPH", "PUMP", "PROS", "PB", "PLX", "TARA", "PTGX", "PTVCA", "PTVCB", "PTI", "PVBC",
"PROV", "PFS", "PBIP", "PUK", "PMD", "PCYO", "PSTG", "PRPL", "QCRH", "QUAD", "KWR", "PZN",
"QEP", "QTWO", "QK", "NX", "QRHC", "QUIK", "QUMU", "QUOT", "RBB", "RMED", "RICK", "RCMT",
"RCM", "REVG", "RFIL", "RLI", "RMG", "RES", "RH", "RPM", "RYB", "RLGT", "RFL", "RAND",
"RNDB", "RNGR", "PACK", "RAVE", "RAVN", "RJF", "RYAM", "ROLL", "RMAX", "RDI", "RLGY",
"REPH", "RLH", "RRBI", "RRGB", "RRR", "REED", "RGS", "RGLS", "RGA", "REKR", "RS", "RELV",
"RELX", "RBNC", "SOL", "RENN", "RBCAA", "FRBK", "REFR", "RSSS", "REZI", "RVP", "REV",
"REX", "REXN", "REYN", "RBKB", "RIBT", "RELL", "RMBI", "RNET", "REI", "REDU", "RVSB",
"RIVE", "RCKY", "RMCF", "ROG", "ROCH", "RDS-B", "RDS-A", "RBCN", "RMBL", "RUSHA", "RUSHB",
"RYAAY", "RYI", "STBA", "WORX", "SBFG", "SEIC", "SMHI", "SGBX", "SJW", "SM", "SP", "SRAX",
"SGRP", "SWKH", "SANW", "SFET", "SFE", "SGA", "JOE", "SLRX", "SALM", "SAL", "SD", "JBSS",
"SGMO", "SC", "SAR", "STSA", "SVRA", "SMIT", "SNDR", "SCHL", "SWM", "SAIC", "SMG", "SCPH",
"SCU", "SCYX", "SEB", "SBCF", "CKH", "SPNE", "EYES", "SECO", "SNFCA", "SEEL", "SIC",
"WTTR", "SEM", "SELB", "SLS", "LEDS", "SENEB", "SENEA", "SNES", "AIHS", "SXT", "SENS",
"SRTS", "SQNS", "SQBG", "SCI", "SERV", "SFBS", "SVT", "SESN", "SVBI", "SMED", "SHSP",
"SHEN", "TYHT", "SHG", "SHBI", "SIEB", "BSRR", "SIEN", "SRRA", "SIF", "SIFY", "SGLB",
"SGMA", "SBNY", "SLN", "SLGN", "SAMG", "SBOW", "SI", "SSNT", "SFNC", "SSD", "SHI", "SINO",
"TSLX", "SKX", "SKYS", "SWBI", "SNN", "SMBK", "SND", "SY", "SQM", "SCKT", "SWI", "SOI",
"SLNO", "SNGX", "SLDB", "XPL", "SAH", "SONM", "SON", "SNOA", "SOS", "SFBC", "SJI", "SPFI",
"SSB", "SFST", "SMBC", "SONA", "SPKE", "LOV", "SPPI", "SPB", "SPRO", "STXB", "SPOK",
"SBPH", "SFM", "SRAC", "STAF", "STND", "SMP", "SGU", "SCX", "MITO", "STCN", "SCS", "SCL",
"STXS", "STL", "SBT", "STRL", "STC", "SF", "SYBT", "BANX", "SRI", "STON", "SNEX", "SSKN",
"STRT", "STRS", "STRM", "MSC", "RGR", "SMFG", "SUMR", "SMMF", "SUM", "SSBI", "SMMT",
"WISA", "SXC", "SNDE", "SSY", "STG", "NOVA", "SCON", "SLGG", "SDPI", "SUP", "SGC", "SPRT",
"SURF", "SRGA", "SSSS", "STRO", "SUZ", "SWCH", "SYNL", "SYN", "SYPR", "SYBX", "SYX",
"CGBD", "TCF", "TELA", "TESS", "TFFP", "GLG", "TPIC", "TSRI", "TAIT", "TLC", "TAK", "TKAT",
"TALO", "TEDU", "TTM", "TAYD", "TCRR", "TISI", "TCCO", "TRC", "TEO", "TDY", "VIV", "TDS",
"TNAV", "TLGT", "TPX", "TS", "TENX", "TGC", "TEN", "TX", "TBNK", "TTI", "ODP", "NCTY",
"STKS", "THR", "KRKR", "TDW", "TLYS", "TSU", "TMBR", "TMST", "TWI", "TITN", "TLSA", "TMP",
"TR", "TRCH", "TTC", "TBLT", "TSQ", "TCON", "TW", "TACT", "TCI", "TRXC", "TGS", "TA",
"TREC", "TG", "THS", "TRVI", "TCBK", "TRS", "TRN", "TPHS", "TRT", "TPVG", "TBK", "TGI",
"TRST", "TRMK", "MEDS", "TTOO", "TC", "TOUR", "TKC", "TPB", "THCB", "THCA", "TPC", "XXII",
"TRWH", "TYME", "UFPT", "USAU", "USAK", "GROW", "UMRX", "USNA", "USCR", "USPH", "SLCA",
"ULBI", "UGP", "UA", "UNAM", "UFI", "UL", "UNB", "UFAB", "UBOH", "UCBI", "UBCP", "UFCS",
"UG", "UNFI", "UAMY", "USEG", "USLM", "USFD", "USWS", "UNTY", "UNVR", "UEIC", "UUU",
"USAP", "ULH", "UTI", "UVSP", "TIGR", "UONEK", "USIO", "ECOL", "UTMD", "VTVT", "EGY",
"VCNX", "VHI", "VALE", "VMI", "VALU", "VAPO", "VGR", "VEC", "VEDL", "PCVX", "VERO", "VRA",
"VNE", "VSTM", "VERB", "VBTX", "VRTV", "VCEL", "VRME", "VERY", "VRNA", "VRRM", "VRCA",
"VTNR", "VERU", "VRT", "VIACA", "VRAY", "VLGEA", "VNCE", "VIOT", "VIRC", "VHC", "VTSI",
"VRTS", "VSH", "VPG", "VIST", "VC", "VTGN", "VMAC", "VIVE", "VOLT", "VOYA", "VJET", "WTI",
"WDFC", "WSFS", "WVFC", "WPP", "VYNE", "WNC", "WAB", "WDR", "WD", "HCC", "WASH", "WSO-B",
"WSO", "WEI", "WBT", "WERN", "WSBC", "WCC", "WTBA", "WABC", "WSTL", "WLK", "WBK", "WWR",
"WEX", "WEYS", "WHF", "WLL", "FREE", "WOW", "WYY", "JW-A", "JW-B", "WHLM", "WVVI", "WSM",
"WLFC", "WSC", "WINT", "WGO", "WTT", "WETF", "WKEY", "WWW", "WF", "WRLD", "WOR", "XYF",
"XPO", "XPEL", "XTLB", "XELB", "XBIO", "XIN", "XOMA", "XTNT", "XFOR", "YPF", "YRCW",
"YELP", "YTEN", "YRD", "YIN", "YETI", "YORW", "DAO", "YGYI", "CTIB", "ZAGG", "ZEAL",
"ZDGE", "ZG", "ZSAN", "ZVO", "ZYNE", "BNSO", "DSWL", "ATIF", "BHVN", "BRLI", "CHNR",
"CCCL", "CCRC", "SXTC", "DOGZ", "CLWT", "GTEC", "HEBT", "HIHO", "HOLI", "HUSN", "LLIT",
"LKCO", "MTC", "NESR", "NTP", "NEWA", "NOMD", "SEED", "RETO", "SJ", "TANH", "PETZ", "MYT",
"WAFU", "ZKIN", "AAMC"]
def get_investing_lists():
investment_list = investing_list_of_industrials + investing_list_of_technology + \
investing_list_of_communication_services + investing_list_of_energy + \
investing_list_of_utilities_and_real_estate + investing_list_of_materials + \
investing_list_of_consumer_discretionary + investing_list_of_consumer_staples + \
investing_list_of_healthcare + investing_list_of_financials + investing_list_of_oct_nov
random.shuffle(investment_list)
print(len(investment_list))
return investment_list
# print(get_investing_lists())
| 104.472674 | 120 | 0.364226 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 37,147 | 0.525209 |
b3af58f083b1707dd8c5557c8ab04196db2c3a61 | 3,150 | py | Python | elliot/utils/read.py | gategill/elliot | 113763ba6d595976e14ead2e3d460d9705cd882e | [
"Apache-2.0"
] | 175 | 2021-03-04T15:46:25.000Z | 2022-03-31T05:56:58.000Z | elliot/utils/read.py | gategill/elliot | 113763ba6d595976e14ead2e3d460d9705cd882e | [
"Apache-2.0"
] | 15 | 2021-03-06T17:53:56.000Z | 2022-03-24T17:02:07.000Z | elliot/utils/read.py | gategill/elliot | 113763ba6d595976e14ead2e3d460d9705cd882e | [
"Apache-2.0"
] | 39 | 2021-03-04T15:46:26.000Z | 2022-03-09T15:37:12.000Z | """
Module description:
"""
__version__ = '0.3.1'
__author__ = 'Vito Walter Anelli, Claudio Pomo'
__email__ = 'vitowalter.anelli@poliba.it, claudio.pomo@poliba.it'
import pandas as pd
import configparser
import pickle
import numpy as np
import os
from types import SimpleNamespace
def read_csv(filename):
"""
Args:
filename (str): csv file path
Return:
A pandas dataframe.
"""
df = pd.read_csv(filename, index_col=False)
return df
def read_np(filename):
"""
Args:
filename (str): filename of numpy to load
Return:
The loaded numpy.
"""
return np.load(filename)
def read_imagenet_classes_txt(filename):
"""
Args:
filename (str): txt file path
Return:
A list with 1000 imagenet classes as strings.
"""
with open(filename) as f:
idx2label = eval(f.read())
return idx2label
def read_config(sections_fields):
"""
Args:
sections_fields (list): list of fields to retrieve from configuration file
Return:
A list of configuration values.
"""
config = configparser.ConfigParser()
config.read('./config/configs.ini')
configs = []
for s, f in sections_fields:
configs.append(config[s][f])
return configs
def read_multi_config():
"""
It reads a config file that contains the configuration parameters for the recommendation systems.
Return:
A list of configuration settings.
"""
config = configparser.ConfigParser()
config.read('./config/multi.ini')
configs = []
for section in config.sections():
single_config = SimpleNamespace()
single_config.name = section
for field, value in config.items(section):
single_config.field = value
configs.append(single_config)
return configs
def load_obj(name):
"""
Load the pkl object by name
:param name: name of file
:return:
"""
with open(name, 'rb') as f:
return pickle.load(f)
def find_checkpoint(dir, restore_epochs, epochs, rec, best=0):
"""
:param dir: directory of the model where we start from the reading.
:param restore_epochs: epoch from which we start from.
:param epochs: epochs from which we restore (0 means that we have best)
:param rec: recommender model
:param best: 0 No Best - 1 Search for the Best
:return:
"""
if best:
for r, d, f in os.walk(dir):
for file in f:
if 'best-weights-'.format(restore_epochs) in file:
return dir + file.split('.')[0]
return ''
if rec == "apr" and restore_epochs < epochs:
# We have to restore from an execution of bprmf
dir_stored_models = os.walk('/'.join(dir.split('/')[:-2]))
for dir_stored_model in dir_stored_models:
if 'bprmf' in dir_stored_model[0]:
dir = dir_stored_model[0] + '/'
break
for r, d, f in os.walk(dir):
for file in f:
if 'weights-{0}-'.format(restore_epochs) in file:
return dir + file.split('.')[0]
return ''
| 25.2 | 101 | 0.613968 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,338 | 0.424762 |
b3afb558d9c9edc836599e07c90b89b367f0d512 | 5,792 | py | Python | examples/Mujoco/path_and_orientation_planner_bell_shaped.py | elsuizo/abr_control | d7d47a1c152dfcb8d1a3093083d53f19cc4922d6 | [
"BSD-3-Clause"
] | 1 | 2021-07-07T13:26:38.000Z | 2021-07-07T13:26:38.000Z | examples/Mujoco/path_and_orientation_planner_bell_shaped.py | elsuizo/abr_control | d7d47a1c152dfcb8d1a3093083d53f19cc4922d6 | [
"BSD-3-Clause"
] | null | null | null | examples/Mujoco/path_and_orientation_planner_bell_shaped.py | elsuizo/abr_control | d7d47a1c152dfcb8d1a3093083d53f19cc4922d6 | [
"BSD-3-Clause"
] | null | null | null | """
Running operational space control using Mujoco. The controller will
move the end-effector to the target object's position and orientation.
This example controls all 6 degrees of freedom (position and orientation),
and applies a second order path planner to both position and orientation targets
After termination the script will plot results
"""
import numpy as np
import glfw
from abr_control.controllers import OSC, Damping, path_planners
from abr_control.arms.mujoco_config import MujocoConfig as arm
from abr_control.interfaces.mujoco import Mujoco
from abr_control.utils import transformations
# initialize our robot config
robot_config = arm('jaco2')
# damp the movements of the arm
damping = Damping(robot_config, kv=10)
# create opreational space controller
ctrlr = OSC(
robot_config,
kp=30, # position gain
kv=20,
ko=180, # orientation gain
null_controllers=[damping],
vmax=None, # [m/s, rad/s]
# control all DOF [x, y, z, alpha, beta, gamma]
ctrlr_dof = [True, True, True, True, True, True])
# create our interface
interface = Mujoco(robot_config, dt=.001)
interface.connect()
feedback = interface.get_feedback()
hand_xyz = robot_config.Tx('EE', feedback['q'])
def get_target(robot_config):
# pregenerate our path and orientation planners
n_timesteps = 2000
traj_planner = path_planners.BellShaped(
error_scale=0.01, n_timesteps=n_timesteps)
starting_orientation = robot_config.quaternion('EE', feedback['q'])
target_orientation = np.random.random(3)
target_orientation /= np.linalg.norm(target_orientation)
# convert our orientation to a quaternion
target_orientation = [0] + list(target_orientation)
#target_position = [0.4, -0.3, 0.5]
mag = 0.6
target_position = np.random.random(3)*0.5
target_position = target_position / np.linalg.norm(target_position) * mag
traj_planner.generate_path(
position=hand_xyz, target_pos=target_position)
_, orientation_planner = traj_planner.generate_orientation_path(
orientation=starting_orientation, target_orientation=target_orientation)
return traj_planner, orientation_planner, target_position, target_orientation
# set up lists for tracking data
ee_track = []
ee_angles_track = []
target_track = []
target_angles_track = []
try:
count = 0
print('\nSimulation starting...\n')
while 1:
if interface.viewer.exit:
glfw.destroy_window(interface.viewer.window)
break
# get arm feedback
feedback = interface.get_feedback()
hand_xyz = robot_config.Tx('EE', feedback['q'])
if count % 3000 == 0:
traj_planner, orientation_planner, target_position, target_orientation = get_target(robot_config)
interface.set_mocap_xyz('target_orientation', target_position)
interface.set_mocap_orientation('target_orientation', target_orientation)
pos, vel = traj_planner.next()
orient = orientation_planner.next()
target = np.hstack([pos, orient])
interface.set_mocap_xyz('path_planner_orientation', target[:3])
interface.set_mocap_orientation('path_planner_orientation',
transformations.quaternion_from_euler(
orient[0], orient[1], orient[2], 'rxyz'))
u = ctrlr.generate(
q=feedback['q'],
dq=feedback['dq'],
target=target,
#target_vel=np.hstack([vel, np.zeros(3)])
)
# apply the control signal, step the sim forward
interface.send_forces(u)
# track data
ee_track.append(np.copy(hand_xyz))
ee_angles_track.append(transformations.euler_from_matrix(
robot_config.R('EE', feedback['q']), axes='rxyz'))
target_track.append(np.copy(target[:3]))
target_angles_track.append(np.copy(target[3:]))
count += 1
finally:
# stop and reset the simulation
interface.disconnect()
print('Simulation terminated...')
ee_track = np.array(ee_track).T
ee_angles_track = np.array(ee_angles_track).T
target_track = np.array(target_track).T
target_angles_track = np.array(target_angles_track).T
if ee_track.shape[0] > 0:
# plot distance from target and 3D trajectory
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d # pylint: disable=W0611
label_pos = ['x', 'y', 'z']
label_or = ['a', 'b', 'g']
c = ['r', 'g', 'b']
fig = plt.figure(figsize=(8,12))
ax1 = fig.add_subplot(311)
ax1.set_ylabel('3D position (m)')
for ii, ee in enumerate(ee_track):
ax1.plot(ee, label='EE: %s' % label_pos[ii], c=c[ii])
ax1.plot(target_track[ii], label='Target: %s' % label_pos[ii],
c=c[ii], linestyle='--')
ax1.legend()
ax2 = fig.add_subplot(312)
for ii, ee in enumerate(ee_angles_track):
ax2.plot(ee, label='EE: %s' % label_or[ii], c=c[ii])
ax2.plot(target_angles_track[ii], label='Target: %s'%label_or[ii],
c=c[ii], linestyle='--')
ax2.set_ylabel('3D orientation (rad)')
ax2.set_xlabel('Time (s)')
ax2.legend()
ee_track = ee_track.T
target_track = target_track.T
ax3 = fig.add_subplot(313, projection='3d')
ax3.set_title('End-Effector Trajectory')
ax3.plot(ee_track[:, 0], ee_track[:, 1], ee_track[:, 2], label='ee_xyz')
ax3.plot(target_track[:, 0], target_track[:, 1], target_track[:, 2],
label='ee_xyz', c='g', linestyle='--')
ax3.scatter(target_track[-1, 0], target_track[-1, 1],
target_track[-1, 2], label='target', c='g')
ax3.legend()
plt.show()
| 35.10303 | 109 | 0.653488 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,324 | 0.228591 |
b3b082ac1a55a800ca823b94a1ccae634841d953 | 7,770 | py | Python | birg_chemometrics_tools/peak_finding/cwt.py | BiRG/chemometrics_tools | f96aa5fc2478ce454f110f4940ff29632c2e0324 | [
"MIT"
] | null | null | null | birg_chemometrics_tools/peak_finding/cwt.py | BiRG/chemometrics_tools | f96aa5fc2478ce454f110f4940ff29632c2e0324 | [
"MIT"
] | null | null | null | birg_chemometrics_tools/peak_finding/cwt.py | BiRG/chemometrics_tools | f96aa5fc2478ce454f110f4940ff29632c2e0324 | [
"MIT"
] | null | null | null | import numpy as np
from collections import deque
from scipy.signal import cwt, ricker
from scipy.stats import mode, scoreatpercentile
def local_extreme(data, comparator,
axis=0, order=1, take_mode='clip'):
if (int(order) != order) or (order < 1):
raise ValueError('Order must be an int >= 1')
datalen = data.shape[axis]
locs = np.arange(0, datalen)
results = np.ones(data.shape, dtype=bool)
main = data.take(locs, axis=axis, mode=take_mode)
for shift in range(1, order + 1):
plus = data.take(locs + shift, axis=axis, mode=take_mode)
minus = data.take(locs - shift, axis=axis, mode=take_mode)
results &= comparator(main, plus)
results &= comparator(main, minus)
return results
def ridge_detection(local_max, row_best, col, n_rows, n_cols, minus=True, plus=True):
cols = deque()
rows = deque()
cols.append(col)
rows.append(row_best)
col_plus = col
col_minus = col
for i in range(1, n_rows):
row_plus = row_best + i
row_minus = row_best - i
segment_plus = 1
segment_minus = 1
if minus and row_minus > 0 and segment_minus < col_minus < n_cols - segment_minus - 1:
if local_max[row_minus, col_minus + 1]:
col_minus += 1
elif local_max[row_minus, col_minus - 1]:
col_minus -= 1
elif local_max[row_minus, col_minus]:
col_minus = col_minus
else:
col_minus = -1
if col_minus != -1:
rows.appendleft(row_minus)
cols.appendleft(col_minus)
if plus and row_plus < n_rows and segment_plus < col_plus < n_cols - segment_plus - 1:
if local_max[row_plus, col_plus + 1]:
col_plus += 1
elif local_max[row_plus, col_plus - 1]:
col_plus -= 1
elif local_max[row_plus, col_plus]:
col_plus = col_plus
else:
col_plus = -1
if col_plus != -1:
rows.append(row_plus)
cols.append(col_plus)
if (minus and False == plus and col_minus == -1) or \
(False == minus and True == plus and col_plus == -1) or \
(True == minus and True == plus and col_plus == -1 and col_minus == -1):
break
return rows, cols
def peaks_position(vec, ridges, cwt2d, wnd=2):
n_cols = cwt2d.shape[1]
negs = cwt2d < 0
local_minus = local_extreme(cwt2d, np.less, axis=1, order=1)
zero_crossing = np.abs(np.diff(np.sign(cwt2d))) / 2
# # figure(figsize=(12, 3))
# imshow(zero_crossing, cmap=cmap_black)
# ylabel("Scales")
# # figure(figsize=(12, 3))
# imshow(local_minus, cmap=cmap_blue)
# ylabel("Scales")
negs |= local_minus
negs[:, [0, n_cols - 1]] = True
ridges_select = []
peaks = []
for ridge in ridges:
inds = np.where(cwt2d[ridge[0, :], ridge[1, :]] > 0)[0]
if len(inds) > 0:
col = int(mode(ridge[1, inds])[0][0])
rows = ridge[0, :][(ridge[1, :] == col)]
row = rows[0]
cols_start = max(col - np.where(negs[row, 0:col][::-1])[0][0], 0)
cols_end = min(col + np.where(negs[row, col:n_cols])[0][0], n_cols)
# print col, row, cols_start, cols_end
if cols_end > cols_start:
inds = range(cols_start, cols_end)
peaks.append(inds[np.argmax(vec[inds])])
ridges_select.append(ridge)
elif ridge.shape[1] > 2: # local wavelet coefficients < 0
cols_accurate = ridge[1, 0:int(ridge.shape[1] / 2)]
cols_start = max(np.min(cols_accurate) - 3, 0)
cols_end = min(np.max(cols_accurate) + 4, n_cols - 1)
inds = range(cols_start, cols_end)
if len(inds) > 0:
peaks.append(inds[np.argmax(vec[inds])])
ridges_select.append(ridge)
# print peaks
ridges_refine = []
peaks_refine = []
ridges_len = np.array([ridge.shape[1] for ridge in ridges_select])
# print zip(peaks, ridges_len)
for peak in np.unique(peaks):
inds = np.where(peaks == peak)[0]
ridge = ridges_select[inds[np.argmax(ridges_len[inds])]]
inds = np.clip(range(peak - wnd, peak + wnd + 1), 0, len(vec) - 1)
inds = np.delete(inds, np.where(inds == peak))
if np.all(vec[peak] > vec[inds]):
ridges_refine.append(ridge)
peaks_refine.append(peak)
return peaks_refine, ridges_refine
def ridges_detection(cwt2d, vec):
n_rows = cwt2d.shape[0]
n_cols = cwt2d.shape[1]
local_max = local_extreme(cwt2d, np.greater, axis=1, order=1)
ridges = []
rows_init = np.array(range(1, 6))
cols_small_peaks = np.where(np.sum(local_max[rows_init, :], axis=0) > 0)[0]
for col in cols_small_peaks:
best_rows = rows_init[np.where(local_max[rows_init, col])[0]]
rows, cols = ridge_detection(local_max, best_rows[0], col, n_rows, n_cols, True, True)
staightness = 1 - float(sum(abs(np.diff(cols)))) / float(len(cols))
if len(rows) >= 2 and \
staightness > 0.2 and \
not (
len(ridges) > 0 and
rows[0] == ridges[-1][0, 0] and
rows[-1] == ridges[-1][0, -1] and
cols[0] == ridges[-1][1, 0] and
cols[-1] == ridges[-1][1, -1] and
len(rows) == ridges[-1].shape[1]
):
ridges.append(np.array([rows, cols], dtype=np.int32))
# figure(figsize=(12, 3))
# imshow(cwt2d)
# ylabel("Scales")
# figure()
# plot(cwt2d[3,:])
# figure(figsize=(9, 4))
# imshow(local_max, cmap=cmap_red)
# ylabel("Scales")
return ridges
def signal_noise_ratio(cwt2d, ridges, peaks):
n_cols = cwt2d.shape[1]
row_one = cwt2d[0, :]
row_one_del = np.delete(row_one, np.where(abs(row_one) < 10e-5))
t = 3 * np.median(np.abs(row_one_del - np.median(row_one_del))) / 0.67
row_one[row_one > t] = t
row_one[row_one < -t] = -t
noises = np.zeros(len(peaks))
signals = np.zeros(len(peaks))
for ind, val in enumerate(peaks):
hf_window = ridges[ind].shape[1] * 1
window = range(int(max([val - hf_window, 0])), int(min([val + hf_window, n_cols])))
noises[ind] = scoreatpercentile(np.abs(row_one[window]), per=90)
signals[ind] = np.max(cwt2d[ridges[ind][0, :], ridges[ind][1, :]])
sig = [1 if s > 0 and n >= 0 else - 1 for s, n in zip(signals, noises)]
# print zip(peaks, signals, noises)
# figure()
# plot(row_one, label='scale = 1')
# # plot(cwt2d[1, :], label='scale = 2')
# plot(cwt2d[3, :], label='scale = 4')
# # plot(cwt2d[5, :], label='scale = 6')
# legend()
return np.sqrt(np.abs((signals + np.finfo(float).eps) / (noises + np.finfo(float).eps))) * sig, signals
def peaks_detection(vec, scales, min_snr=3):
cwt2d = cwt(vec, ricker, scales)
ridges = ridges_detection(cwt2d, vec)
# print ridges
peaks, ridges = peaks_position(vec, ridges, cwt2d)
# print ridges
# print peaks
snr, signals = signal_noise_ratio(cwt2d, ridges, peaks)
# print zip(peaks, snr)
# peaks_refine = [peak for i, peak in enumerate(peaks) if snr[i] >= min_snr]
# signals_refine = [signal for i, signal in enumerate(signals) if snr[i] >= min_snr]
# print peaks_refine
peaks_refine = [peak for i, peak in enumerate(peaks) if signals[i] >= min_snr]
signals_refine = [signal for i, signal in enumerate(signals) if signals[i] >= min_snr]
return peaks_refine, signals_refine
| 39.045226 | 107 | 0.569884 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 944 | 0.121493 |
b3b308144a89e4fa0b94da6be42bebb4778d0030 | 88 | py | Python | autorop/call/__init__.py | mariuszskon/autorop | 5735073008f722fab00f3866ef4a05f04620593b | [
"MIT"
] | 15 | 2020-10-03T05:20:31.000Z | 2022-03-20T06:19:29.000Z | autorop/call/__init__.py | mariuszskon/autorop | 5735073008f722fab00f3866ef4a05f04620593b | [
"MIT"
] | 8 | 2020-10-02T09:51:39.000Z | 2021-04-24T03:14:18.000Z | autorop/call/__init__.py | mariuszskon/autorop | 5735073008f722fab00f3866ef4a05f04620593b | [
"MIT"
] | 2 | 2021-04-16T06:33:49.000Z | 2021-09-03T09:21:10.000Z | from autorop.call.Custom import Custom
from autorop.call.SystemBinSh import SystemBinSh
| 29.333333 | 48 | 0.863636 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
b3b4137e15129c499432a055f79b2a1c626e8623 | 14,662 | py | Python | exams/models.py | akmohtashami/mcexam | 27ba5e11bafcf247e46132c09d4901e84a35ddf7 | [
"MIT"
] | null | null | null | exams/models.py | akmohtashami/mcexam | 27ba5e11bafcf247e46132c09d4901e84a35ddf7 | [
"MIT"
] | null | null | null | exams/models.py | akmohtashami/mcexam | 27ba5e11bafcf247e46132c09d4901e84a35ddf7 | [
"MIT"
] | 1 | 2019-06-23T17:44:22.000Z | 2019-06-23T17:44:22.000Z | # -*- coding: utf-8 -*-
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext as _
from users.models import Member
from adminsortable.models import Sortable
from adminsortable.fields import SortableForeignKey
from django.template import Template, Context
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.core.exceptions import ValidationError
from django.core.cache import cache
import os
import datetime
# Create your models here.
def user_in_its_time_frame(exam, user):
d = exam.duration
if d == 0:
return True
else:
try:
p = Participation.objects.get(user=user,exam=exam)
delta = datetime.timedelta(minutes=d)
end_date = p.start_date + delta
return timezone.now() <= end_date
except Participation.DoesNotExist:
return False
def get_statement_path(instance, filename):
return os.path.join(instance.resources_dir, 'statements', filename)
class Exam(models.Model):
name = models.CharField(max_length=500, verbose_name=_("Name"))
activation_date = models.DateTimeField(
_("Activation date"),
help_text=_("After this time the exam is considered open. "
"Importers can download the questions and import answer sheets. "
"Everybody can see their answer sheet."),
)
duration = models.PositiveIntegerField(verbose_name=_("Duration(min)"), default=0,
help_text=_("If entered each user may participate for a window of \
this length anytime inside the online exam time frame(USACO-like)"))
online_start_date = models.DateTimeField(_("Online exam start date"))
online_end_date = models.DateTimeField(_("Online exam end date"))
sealing_date = models.DateTimeField(
_("Sealing date"),
help_text=_("After this time the exam is sealed. "
"Importers will no longer be able to import answer sheets"),
)
publish_results_date = models.DateTimeField(
_("Result publishing date"),
help_text=_("After this time the results and correct answers will be published "),
)
questions_per_column = models.PositiveIntegerField(_("Number of questions per column in answer sheet"), default=20)
exam_pdf_template = models.TextField(
verbose_name=_("PDF template"),
help_text=_("Django-Tex template for creating pdf files"),
default=""
)
statements_file = models.FileField(
max_length=5000,
upload_to=get_statement_path,
blank=True,
null=True,
storage=FileSystemStorage(location='/')
)
class Meta:
verbose_name = _("Exam")
verbose_name_plural = _("Exams")
permissions = (
("can_view", _("Can view exam")),
("can_import", _("Can import answer sheets")),
("out_of_competition", _("Participated out of competition")),
("import_all", _("Can import at any examsite at anytime")),
("see_all_results", _("Can see all results")),
)
def __unicode__(self):
return self.name
def mode(self):
if timezone.now() < self.activation_date:
return -2 # exam is not activated
elif timezone.now() < self.online_start_date:
return -1 # online exam not started
elif timezone.now() < self.online_end_date:
return 0 # online exam is running
elif timezone.now() < self.sealing_date:
return 1 # online exam finished. exam not sealed
elif timezone.now() < self.publish_results_date:
return 2 # exam is sealed. results are not published
else:
return 3 # exam is finished and results are published
def get_all_implicit_permissions(self, user):
implicit_permissions = {
"view_answer_sheet": user.has_perm("exams.change_exam", self) or self.mode() > -2,
"save_answer_sheet": user.has_perm("exams.change_exam", self) or (self.mode() == 0 and user_in_its_time_frame(self, user)),
"view_statements": user.has_perm("exams.change_exam", self) or self.mode() > -1,
"import": user.has_perm("exams.can_import", self) and
((self.mode() > -2 and self.mode() < 2) or user.has_perm("exams.import_all", self)),
"view_results": user.has_perm("exams.see_all_results", self) or self.mode() >= 3
}
perms = []
for perm in implicit_permissions:
if implicit_permissions[perm]:
perms.append(perm)
return perms
def check_implicit_permission(self, user, perm):
return perm in self.get_all_implicit_permissions(user)
def get_statements_tex_file(self):
context = {
"exam": self
}
exam_template = Template(self.exam_pdf_template)
return exam_template.render(Context(context)).encode("utf-8")
@property
def resources_dir(self):
return os.path.join(settings.PRIVATE_MEDIA_ROOT, 'examfiles', str(self.id))
def add_tex_resources_to_environ(self, base_env=os.environ):
env = base_env.copy()
xelatex_path = getattr(settings, "XELATEX_BIN_PATH", None)
if xelatex_path is not None:
env["PATH"] = os.pathsep.join([xelatex_path, env["PATH"]])
env["TEXINPUTS"] = self.resources_dir + "//:" + env.get("TEXINPUTS", "")
env["TTFONTS"] = self.resources_dir + "//:" + env.get("TTFONTS", "")
env["OPENTYPEFONTS"] = self.resources_dir + "//:" + env.get("OPENTYPEFONTS", "")
return env
def calculate_all_ranks(self):
participants = ParticipantResult.objects.filter(exam=self)
last_participant = None
current_rank = 1
for participant in participants:
user_cache = "exam_" + str(self.id) + "_user_" + str(participant.user.id) + "_result"
cache.delete(user_cache)
if participant.user.exam_site is not None:
site_cache = "exam_" + str(self.id) + "_site_" + str(participant.user.exam_site.id) + "_result"
cache.delete(site_cache)
if last_participant is None or last_participant.score > participant.score:
participant.rank = current_rank
else:
participant.rank = last_participant.rank
participant.save()
last_participant = participant
if participant.user.has_perm("exams.out_of_competition", self):
pass
elif len(MadeChoice.objects.filter(choice__question__exam=self, user=participant.user)) > 0:
current_rank += 1
def calculate_user_score(self, user):
try:
result = ParticipantResult.objects.get(exam=self, user=user)
except ParticipantResult.DoesNotExist:
result = ParticipantResult(user=user, exam=self)
result.score = 0
result.correct = 0
result.wrong = 0
for question in self.question_set.filter(is_info=False):
try:
marked_choice = MadeChoice.objects.get(user=user, choice__in=question.choice_set.all()).choice
if marked_choice.is_correct:
result.correct += 1
result.score += question.correct_score
else:
result.wrong += 1
result.score -= question.wrong_penalty
except MadeChoice.DoesNotExist:
pass
result.rank = 0
result.save()
def calculate_all_results(self):
"""
This calculates the score and rank of all users who have at least one answered question
"""
#Calculating score
for user in Member.objects.all():
user_cache = "exam_" + str(self.id) + "_user_" + str(user.id) + "_result"
cache.delete(user_cache)
if user.exam_site is not None:
site_cache = "exam_" + str(self.id) + "_site_" + str(user.exam_site.id) + "_result"
cache.delete(site_cache)
self.calculate_user_score(user)
#Calculating rank
self.calculate_all_ranks()
def calculate_total_score(self):
total_score = 0
for question in self.question_set.filter(is_info=False):
total_score += question.correct_score
return total_score
@property
def total_score(self):
cache_name = "exam_" + str(self.id) + "_total_score"
if cache.get(cache_name) is None:
total_score = self.calculate_total_score()
cache.set(cache_name, total_score)
return cache.get(cache_name)
def get_user_question_details(self, user):
question_list = []
for question in self.question_set.filter(is_info=False):
try:
marked_choice = MadeChoice.objects.get(user=user, choice__in=question.choice_set.all()).choice
except MadeChoice.DoesNotExist:
marked_choice = None
question_list.append((question, marked_choice))
return question_list
def get_key_question_details(self):
question_list = []
for question in self.question_set.filter(is_info=False):
marked_choice = None
question_list.append((question, marked_choice))
return question_list
def clean(self):
if self.activation_date > self.online_start_date:
raise ValidationError("Exam must be activated before or at the same time the online exam starts")
if self.online_start_date > self.online_end_date:
raise ValidationError("Online exam must start before or at the same time the online exam ends")
if self.online_end_date > self.sealing_date:
raise ValidationError("Online exam must end before or at the same time the exam is sealed")
if self.sealing_date > self.publish_results_date:
raise ValidationError("Exam must be sealed before the results are published")
class Question(Sortable):
exam = models.ForeignKey(Exam, verbose_name=_("Related exam"))
statement = models.TextField(verbose_name=_("Question's Statement"))
is_info = models.BooleanField(default=False,
verbose_name=_("Info"),
help_text=_("If you want to put some info between some of the question write info "
"in question statement and check this box"))
correct_score = models.PositiveSmallIntegerField(
verbose_name=_("Correct Answer Score"),
help_text=_("Amount of score which is increased for correct answer"),
default=4,
)
wrong_penalty = models.PositiveSmallIntegerField(
verbose_name=_("Wrong Answer Penalty"),
help_text=_("Amount of score which is decreased for incorrent answer"),
default=1
)
def __unicode__(self):
name = self.exam.name + " - " + _("Question #") + " " + str(self.order)
if self.is_info:
name += "(" + _("Info") + ")"
return name
@property
def resources_dir(self):
return os.path.join(self.exam.resources_dir, str(self.id))
class Meta(Sortable.Meta):
verbose_name = _("Question")
verbose_name_plural = _("Questions")
class Choice(Sortable):
question = SortableForeignKey(Question, verbose_name="Related question")
choice = models.CharField(max_length=10000, verbose_name=_("Choice"))
is_correct = models.BooleanField(default=False,
verbose_name="Correct",
help_text="Is this a correct answer to question?")
def __unicode__(self):
name = self.question.__unicode__() + ": " + self.choice
if self.is_correct:
name += "(" + _("Correct") + ")"
return name
class Meta(Sortable.Meta):
verbose_name = _("Choice")
verbose_name_plural = _("Choices")
class MadeChoice(models.Model):
user = models.ForeignKey(Member)
choice = models.ForeignKey(Choice)
def __unicode__(self):
return self.user.__unicode__() + " - " + self.choice.question.__unicode__()
def clean(self):
current = MadeChoice.objects.filter(user=self.user, choice__question=self.choice.question)
if (not current.exists()) or (self.id is not None and current[0].id == self.id):
super(MadeChoice, self).clean()
else:
raise ValidationError(_("User has another answer for this question in database"),
code='multiple_answer')
class Meta:
ordering = ['user', 'choice__question__exam', 'choice__question']
verbose_name = _("Made Choice")
verbose_name_plural = _("Made Choices")
class ExamSite(models.Model):
exam = models.ForeignKey(Exam, verbose_name=_("Exam"))
importer = models.ForeignKey(Member, verbose_name=_("Importer"))
name = models.CharField(max_length=255, verbose_name=_("Exam Site"))
def __unicode__(self):
return self.name
def participants_count(self):
return len(Member.objects.filter(exam_site=self))
participants_count.short_description = _("Number of participants")
class Meta:
verbose_name = _("Exam Site")
verbose_name_plural = _("Exam Sites")
class ParticipantResult(models.Model):
exam = models.ForeignKey(Exam, verbose_name=_("Exam"))
user = models.ForeignKey(Member, verbose_name=_("Participant"))
score = models.IntegerField(verbose_name=_("Score"))
correct = models.PositiveIntegerField(verbose_name=_("Correct answers"))
wrong = models.PositiveIntegerField(verbose_name=_("Wrong answers"))
rank = models.PositiveIntegerField(verbose_name=_("Rank"))
def __unicode__(self):
return self.exam.__unicode__() + ": " + self.user.get_full_name()
class Meta:
ordering = ['exam', '-score']
verbose_name = _("Participant Result")
verbose_name_plural = _("Participants Results")
class Participation(models.Model):
user = models.ForeignKey(Member, verbose_name=_("Participant"))
exam = models.ForeignKey(Exam, verbose_name=_("Exam"))
start_date = models.DateTimeField(_("Online exam start date"))
def __unicode__(self):
return self.user.username + '-' + self.exam.name
class Meta:
verbose_name = _("Participant")
verbose_name_plural = _("Participants")
| 40.614958 | 135 | 0.632792 | 13,574 | 0.925795 | 0 | 0 | 505 | 0.034443 | 0 | 0 | 2,974 | 0.202837 |
b3b6541b01dfd184dca64906972592b52fde11f6 | 2,371 | py | Python | happy/HappyLinkList.py | yunhanw-google/happy | d482f1eeb188a03e3bcd1aefe54424fb2589c9e9 | [
"Apache-2.0"
] | 42 | 2017-09-20T07:09:59.000Z | 2021-11-08T12:08:30.000Z | happy/HappyLinkList.py | yunhanw-google/happy | d482f1eeb188a03e3bcd1aefe54424fb2589c9e9 | [
"Apache-2.0"
] | 30 | 2018-06-16T14:48:14.000Z | 2020-10-13T04:02:35.000Z | happy/HappyLinkList.py | yunhanw-google/happy | d482f1eeb188a03e3bcd1aefe54424fb2589c9e9 | [
"Apache-2.0"
] | 17 | 2017-09-20T10:37:56.000Z | 2021-02-09T06:27:44.000Z | #!/usr/bin/env python3
#
# Copyright (c) 2015-2017 Nest Labs, 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.
#
##
# @file
# Implements HappyLinkList class that displays a list of virtual links.
#
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
from happy.ReturnMsg import ReturnMsg
from happy.Utils import *
from happy.HappyLink import HappyLink
options = {}
options["quiet"] = False
def option():
return options.copy()
class HappyLinkList(HappyLink):
"""
Displays a list of virtual links.
happy-link-list [-h --help] [-q --quiet]
return:
0 success
1 fail
"""
def __init__(self, opts=options):
HappyLink.__init__(self)
self.quiet = opts["quiet"]
def __pre_check(self):
pass
def __list_links(self):
cmd = "ip link show"
result, _ = self.CallAtHostForOutput(cmd)
if result != "":
self.logger.info(result)
def __show_links(self):
if self.quiet:
return
link_ids = self.getLinkIds()
link_ids.sort()
for link_id in link_ids:
print(link_id)
if self.getLinkNetwork(link_id) is None:
print("\tNetwork: not assigned")
else:
print("\tNetwork: " + self.getLinkNetwork(link_id))
if self.getLinkNode(link_id) is None:
print("\tNode: not assigned")
else:
print("\tNode: " + self.getLinkNode(link_id))
print("\tType: " + self.getLinkType(link_id))
print()
def __post_check(self):
pass
def run(self):
self.__pre_check()
self.__show_links()
self.__post_check()
return ReturnMsg(0)
| 23.245098 | 77 | 0.616196 | 1,318 | 0.555884 | 0 | 0 | 0 | 0 | 0 | 0 | 1,001 | 0.422185 |
b3b6a876ddc74d9307c59885076ee5699c71e501 | 3,209 | py | Python | monteCarlo_investopedia.py | sztang/py_practice | fa4aa87fed53abb8b8cc4b85e95fc967f8f1d2ae | [
"MIT"
] | null | null | null | monteCarlo_investopedia.py | sztang/py_practice | fa4aa87fed53abb8b8cc4b85e95fc967f8f1d2ae | [
"MIT"
] | null | null | null | monteCarlo_investopedia.py | sztang/py_practice | fa4aa87fed53abb8b8cc4b85e95fc967f8f1d2ae | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Monte Carlo Simulation: Dice Game
# Based on Investopedia: Creating a Monte Carlo Simulation
# investopedia.com/articles/investing/093015/create-monte-carlo-simulation-using-excel.asp\
# Here's how the dice game rolls:
# The player throws three dice that have 6 sides 3 times.
# If the total of the 3 throws is 7 or 11, the player wins.
# If the total of the 3 throws is: 3, 4, 5, 16, 17 or 18, the player loses.
# If the total is any other outcome, the player plays again and re-rolls the dice.
# When the player throws the dice again, the game continues in the same way, except
# that the player wins when the total is equal to the sum determined in the first round.
# 5,000 results are needed to prepare the Monte Carlo simulation.
import random
class dice:
def roll(self):
return random.randint(1,6)
dice1 = dice()
dice2 = dice()
dice3 = dice()
win = [7,11]
lose = [3,4,5,16,17,18]
wins = 0
losses = 0
noresult = 0
def main():
global wins, losses, noresult
simulationRuns = 5000
singleSimRolls = 50
rollTimes = 1
for i in range(simulationRuns):
print(f'Simulation {i+1}:')
if goRoll(singleSimRolls, 1) == 'reroll':
threeRoll(singleSimRolls, 2)
win.pop(-1)
print(f'No of wins = {wins}')
print(f'Probability of win = {(wins / simulationRuns * 100):.1f}%')
print(f'No of losses = {losses}')
print(f'Probability of loss = {(losses / simulationRuns * 100):.1f}%')
print(f'No of incomplete = {noresult}')
print(f'Probability of incomplete = {(noresult / simulationRuns * 100):.1f}%')
def goRoll(singleSimRolls, rollTimes):
global wins, losses, noresult
rollSum = dice1.roll() + dice2.roll() + dice3.roll()
print(f'Roll {rollTimes}: {rollSum}')
if rollCheck(rollSum) == 'reroll':
win.append(rollSum)
rollSum = 0
return 'reroll'
elif rollCheck(rollSum) == 'win':
wins +=1
print(f'Won by rolling {rollSum} after {rollTimes} rolls')
return 'win'
elif rollCheck(rollSum) == 'lose':
losses += 1
print(f'Lost by rolling {rollSum} after {rollTimes} rolls')
return 'lose'
def threeRoll(singleSimRolls, rollTimes):
global wins, losses, noresult
if rollTimes <= singleSimRolls:
rollSum = dice1.roll() + dice2.roll() + dice3.roll()
print(f'Roll {rollTimes}: {rollSum}')
if rollCheck(rollSum) == 'win':
print(f'Won by rolling {rollSum} after {rollTimes} rolls')
wins += 1
return 'win'
elif rollCheck(rollSum) == 'lose':
print(f'Lost by rolling {rollSum} after {rollTimes} rolls')
losses += 1
return 'lose'
elif rollCheck(rollSum) == 'reroll':
threeRoll(singleSimRolls, rollTimes + 1)
elif rollTimes > singleSimRolls:
print(f'Did not win or lose after {rollTimes} rolls')
noresult += 1
return 'noresult'
def rollCheck(rollSum = 0):
global win, lose
if rollSum in win:
return 'win'
elif rollSum in lose:
return 'lose'
else:
return 'reroll'
if __name__ == '__main__': main() | 34.138298 | 94 | 0.62761 | 66 | 0.020567 | 0 | 0 | 0 | 0 | 0 | 0 | 1,487 | 0.463384 |
b3b73b58e26317b8a2fdb64a3c8c5b80e517412a | 7,341 | py | Python | examples/run_parametric_elliptic_optimal_control_alpha.py | s274001/PINA | beb33f0da20581338c46f0c525775904b35a1130 | [
"MIT"
] | 4 | 2022-02-16T14:52:55.000Z | 2022-03-17T13:31:42.000Z | examples/run_parametric_elliptic_optimal_control_alpha.py | s274001/PINA | beb33f0da20581338c46f0c525775904b35a1130 | [
"MIT"
] | 3 | 2022-02-17T08:57:42.000Z | 2022-03-28T08:41:53.000Z | examples/run_parametric_elliptic_optimal_control_alpha.py | s274001/PINA | beb33f0da20581338c46f0c525775904b35a1130 | [
"MIT"
] | 7 | 2022-02-13T14:35:00.000Z | 2022-03-28T08:51:11.000Z | import numpy as np
import torch
import argparse
from pina.pinn import PINN
from pina.ppinn import ParametricPINN as pPINN
from pina.label_tensor import LabelTensor
from torch.nn import ReLU, Tanh, Softplus
from pina.adaptive_functions.adaptive_softplus import AdaptiveSoftplus
from problems.parametric_elliptic_optimal_control_alpha_variable import ParametricEllipticOptimalControl
from pina.multi_deep_feed_forward import MultiDeepFeedForward
from pina.deep_feed_forward import DeepFeedForward
alpha = 1
class myFeature(torch.nn.Module):
"""
Feature: sin(x)
"""
def __init__(self):
super(myFeature, self).__init__()
def forward(self, x):
return (-x[:, 0]**2+1) * (-x[:, 1]**2+1)
class CustomMultiDFF(MultiDeepFeedForward):
def __init__(self, dff_dict):
super().__init__(dff_dict)
def forward(self, x):
out = self.uu(x)
p = LabelTensor((out['u_param'] * x[:, 3]).reshape(-1, 1), ['p'])
a = LabelTensor.hstack([out, p])
return a
model = CustomMultiDFF(
{
'uu': {
'input_variables': ['x1', 'x2', 'mu', 'alpha'],
'output_variables': ['u_param', 'y'],
'layers': [40, 40, 20],
'func': Softplus,
'extra_features': [myFeature()],
},
# 'u_param': {
# 'input_variables': ['u', 'mu'],
# 'output_variables': ['u_param'],
# 'layers': [],
# 'func': None
# },
# 'p': {
# 'input_variables': ['u'],
# 'output_variables': ['p'],
# 'layers': [10],
# 'func': None
# },
}
)
opc = ParametricEllipticOptimalControl(alpha)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run PINA")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-s", "-save", action="store_true")
group.add_argument("-l", "-load", action="store_true")
args = parser.parse_args()
# model = DeepFeedForward(
# layers=[40, 40, 20],
# output_variables=['u_param', 'y', 'p'],
# input_variables=opc.input_variables+['mu', 'alpha'],
# func=Softplus,
# extra_features=[myFeature()]
# )
pinn = pPINN(
opc,
model,
lr=0.002,
error_norm='mse',
regularizer=1e-8,
lr_accelerate=None)
if args.s:
pinn.span_pts(30, 'grid', ['D1'])
pinn.span_pts(50, 'grid', ['gamma1', 'gamma2', 'gamma3', 'gamma4'])
pinn.train(10000, 20)
# with open('ocp_wrong_history.txt', 'w') as file_:
# for i, losses in enumerate(pinn.history):
# file_.write('{} {}\n'.format(i, sum(losses).item()))
pinn.save_state('pina.ocp')
else:
pinn.load_state('working.pina.ocp')
pinn.load_state('pina.ocp')
import matplotlib
matplotlib.use('GTK3Agg')
import matplotlib.pyplot as plt
# res = 64
# param = torch.tensor([[3., 1]])
# pts_container = []
# for mn, mx in [[-1, 1], [-1, 1]]:
# pts_container.append(np.linspace(mn, mx, res))
# grids_container = np.meshgrid(*pts_container)
# unrolled_pts = torch.tensor([t.flatten() for t in grids_container]).T
# unrolled_pts = torch.cat([unrolled_pts, param.double().repeat(unrolled_pts.shape[0], 1).reshape(-1, 2)], axis=1)
# unrolled_pts = LabelTensor(unrolled_pts, ['x1', 'x2', 'mu', 'alpha'])
# Z_pred = pinn.model(unrolled_pts.tensor)
# print(Z_pred.tensor.shape)
# plt.subplot(2, 3, 1)
# plt.pcolor(Z_pred['y'].reshape(res, res).detach())
# plt.colorbar()
# plt.subplot(2, 3, 2)
# plt.pcolor(Z_pred['u_param'].reshape(res, res).detach())
# plt.colorbar()
# plt.subplot(2, 3, 3)
# plt.pcolor(Z_pred['p'].reshape(res, res).detach())
# plt.colorbar()
# with open('ocp_mu3_a1_plot.txt', 'w') as f_:
# f_.write('x y u p ys\n')
# for (x, y), tru, pre, e in zip(unrolled_pts[:, :2],
# Z_pred['u_param'].reshape(-1, 1),
# Z_pred['p'].reshape(-1, 1),
# Z_pred['y'].reshape(-1, 1),
# ):
# f_.write('{} {} {} {} {}\n'.format(x.item(), y.item(), tru.item(), pre.item(), e.item()))
# param = torch.tensor([[3.0, 0.01]])
# unrolled_pts = torch.tensor([t.flatten() for t in grids_container]).T
# unrolled_pts = torch.cat([unrolled_pts, param.double().repeat(unrolled_pts.shape[0], 1).reshape(-1, 2)], axis=1)
# unrolled_pts = LabelTensor(unrolled_pts, ['x1', 'x2', 'mu', 'alpha'])
# Z_pred = pinn.model(unrolled_pts.tensor)
# plt.subplot(2, 3, 4)
# plt.pcolor(Z_pred['y'].reshape(res, res).detach())
# plt.colorbar()
# plt.subplot(2, 3, 5)
# plt.pcolor(Z_pred['u_param'].reshape(res, res).detach())
# plt.colorbar()
# plt.subplot(2, 3, 6)
# plt.pcolor(Z_pred['p'].reshape(res, res).detach())
# plt.colorbar()
# plt.show()
# with open('ocp_mu3_a0.01_plot.txt', 'w') as f_:
# f_.write('x y u p ys\n')
# for (x, y), tru, pre, e in zip(unrolled_pts[:, :2],
# Z_pred['u_param'].reshape(-1, 1),
# Z_pred['p'].reshape(-1, 1),
# Z_pred['y'].reshape(-1, 1),
# ):
# f_.write('{} {} {} {} {}\n'.format(x.item(), y.item(), tru.item(), pre.item(), e.item()))
y = {}
u = {}
for alpha in [0.01, 0.1, 1]:
y[alpha] = []
u[alpha] = []
for p in np.linspace(0.5, 3, 32):
a = pinn.model(LabelTensor(torch.tensor([[0, 0, p, alpha]]).double(), ['x1', 'x2', 'mu', 'alpha']).tensor)
y[alpha].append(a['y'].detach().numpy()[0])
u[alpha].append(a['u_param'].detach().numpy()[0])
plt.plot(np.linspace(0.5, 3, 32), u[1], label='u')
plt.plot(np.linspace(0.5, 3, 32), u[0.01], label='u')
plt.plot(np.linspace(0.5, 3, 32), u[0.1], label='u')
plt.plot([1, 2, 3], [0.28, 0.56, 0.85], 'o', label='Truth values')
plt.legend()
plt.show()
print(y[1])
print(y[0.1])
print(y[0.01])
with open('elliptic_param_y.txt', 'w') as f_:
f_.write('mu 1 01 001\n')
for mu, y1, y01, y001 in zip(np.linspace(0.5, 3, 32), y[1], y[0.1], y[0.01]):
f_.write('{} {} {} {}\n'.format(mu, y1, y01, y001))
with open('elliptic_param_u.txt', 'w') as f_:
f_.write('mu 1 01 001\n')
for mu, y1, y01, y001 in zip(np.linspace(0.5, 3, 32), u[1], u[0.1], u[0.01]):
f_.write('{} {} {} {}\n'.format(mu, y1, y01, y001))
plt.plot(np.linspace(0.5, 3, 32), y, label='y')
plt.plot([1, 2, 3], [0.062, 0.12, 0.19], 'o', label='Truth values')
plt.legend()
plt.show()
| 35.293269 | 122 | 0.503201 | 509 | 0.069337 | 0 | 0 | 0 | 0 | 0 | 0 | 3,459 | 0.471189 |
b3b7971054166b3e113cd28da11c99033b9339be | 248 | py | Python | todolist/api/urls.py | yusukhobok/TodoAPI | 9f9d93b54cfe3c841dbe2de91798c5e6a28c7edf | [
"MIT"
] | null | null | null | todolist/api/urls.py | yusukhobok/TodoAPI | 9f9d93b54cfe3c841dbe2de91798c5e6a28c7edf | [
"MIT"
] | 6 | 2020-06-05T20:06:44.000Z | 2021-09-22T18:08:06.000Z | todolist/api/urls.py | Yus27/TodoAPI | 1308aeac356b2168cec02045aa6774b16443d17b | [
"MIT"
] | null | null | null | from django.urls import path
from .views import TodoViewSet
from rest_framework_bulk.routes import BulkRouter
from rest_framework import routers
router = BulkRouter()
router.register(r'', TodoViewSet, basename='todos')
urlpatterns = router.urls | 22.545455 | 51 | 0.814516 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 0.040323 |
b3b8c9350fdcc10478be9ff8a551df1606e7ecf2 | 880 | py | Python | controllers/portal.py | R-E-A-L-iT/odoo-proportals-module | f4f500632c7e15eb7b1e47f3c915a36a78d7e3da | [
"MIT"
] | null | null | null | controllers/portal.py | R-E-A-L-iT/odoo-proportals-module | f4f500632c7e15eb7b1e47f3c915a36a78d7e3da | [
"MIT"
] | null | null | null | controllers/portal.py | R-E-A-L-iT/odoo-proportals-module | f4f500632c7e15eb7b1e47f3c915a36a78d7e3da | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import binascii
from odoo import fields, http, _
from odoo.exceptions import AccessError, MissingError, UserError
from odoo.http import request
from odoo.addons.payment.controllers.portal import PaymentProcessing
from odoo.addons.portal.controllers.mail import _message_post_helper
from odoo.addons.portal.controllers.portal import CustomerPortal, pager as portal_pager, get_records_pager
from odoo.osv import expression
class CustomerPortal(CustomerPortal):
@http.route(['/my/products', '/my/products/page/<int:page>'], type='http', auth="user", website=True)
def products(self):
company = request.env.user.partner_id.parent_id
values = {
'company': company
}
return request.render("proportal.portal_products", values)
| 36.666667 | 106 | 0.744318 | 355 | 0.403409 | 0 | 0 | 308 | 0.35 | 0 | 0 | 189 | 0.214773 |
b3b8fdb7ee87591bb03fea19135fb3fea98d20aa | 6,222 | py | Python | google/cloud/videointelligence/v1/videointelligence-v1-py/google/cloud/videointelligence/__init__.py | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 7 | 2021-02-21T10:39:41.000Z | 2021-12-07T07:31:28.000Z | google/cloud/videointelligence/v1/videointelligence-v1-py/google/cloud/videointelligence/__init__.py | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 6 | 2021-02-02T23:46:11.000Z | 2021-11-15T01:46:02.000Z | google/cloud/videointelligence/v1/videointelligence-v1-py/google/cloud/videointelligence/__init__.py | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 4 | 2021-01-28T23:25:45.000Z | 2021-08-30T01:55:16.000Z | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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 google.cloud.videointelligence_v1.services.video_intelligence_service.client import VideoIntelligenceServiceClient
from google.cloud.videointelligence_v1.services.video_intelligence_service.async_client import VideoIntelligenceServiceAsyncClient
from google.cloud.videointelligence_v1.types.video_intelligence import AnnotateVideoProgress
from google.cloud.videointelligence_v1.types.video_intelligence import AnnotateVideoRequest
from google.cloud.videointelligence_v1.types.video_intelligence import AnnotateVideoResponse
from google.cloud.videointelligence_v1.types.video_intelligence import DetectedAttribute
from google.cloud.videointelligence_v1.types.video_intelligence import DetectedLandmark
from google.cloud.videointelligence_v1.types.video_intelligence import Entity
from google.cloud.videointelligence_v1.types.video_intelligence import ExplicitContentAnnotation
from google.cloud.videointelligence_v1.types.video_intelligence import ExplicitContentDetectionConfig
from google.cloud.videointelligence_v1.types.video_intelligence import ExplicitContentFrame
from google.cloud.videointelligence_v1.types.video_intelligence import FaceAnnotation
from google.cloud.videointelligence_v1.types.video_intelligence import FaceDetectionAnnotation
from google.cloud.videointelligence_v1.types.video_intelligence import FaceDetectionConfig
from google.cloud.videointelligence_v1.types.video_intelligence import FaceFrame
from google.cloud.videointelligence_v1.types.video_intelligence import FaceSegment
from google.cloud.videointelligence_v1.types.video_intelligence import LabelAnnotation
from google.cloud.videointelligence_v1.types.video_intelligence import LabelDetectionConfig
from google.cloud.videointelligence_v1.types.video_intelligence import LabelFrame
from google.cloud.videointelligence_v1.types.video_intelligence import LabelSegment
from google.cloud.videointelligence_v1.types.video_intelligence import LogoRecognitionAnnotation
from google.cloud.videointelligence_v1.types.video_intelligence import NormalizedBoundingBox
from google.cloud.videointelligence_v1.types.video_intelligence import NormalizedBoundingPoly
from google.cloud.videointelligence_v1.types.video_intelligence import NormalizedVertex
from google.cloud.videointelligence_v1.types.video_intelligence import ObjectTrackingAnnotation
from google.cloud.videointelligence_v1.types.video_intelligence import ObjectTrackingConfig
from google.cloud.videointelligence_v1.types.video_intelligence import ObjectTrackingFrame
from google.cloud.videointelligence_v1.types.video_intelligence import PersonDetectionAnnotation
from google.cloud.videointelligence_v1.types.video_intelligence import PersonDetectionConfig
from google.cloud.videointelligence_v1.types.video_intelligence import ShotChangeDetectionConfig
from google.cloud.videointelligence_v1.types.video_intelligence import SpeechContext
from google.cloud.videointelligence_v1.types.video_intelligence import SpeechRecognitionAlternative
from google.cloud.videointelligence_v1.types.video_intelligence import SpeechTranscription
from google.cloud.videointelligence_v1.types.video_intelligence import SpeechTranscriptionConfig
from google.cloud.videointelligence_v1.types.video_intelligence import TextAnnotation
from google.cloud.videointelligence_v1.types.video_intelligence import TextDetectionConfig
from google.cloud.videointelligence_v1.types.video_intelligence import TextFrame
from google.cloud.videointelligence_v1.types.video_intelligence import TextSegment
from google.cloud.videointelligence_v1.types.video_intelligence import TimestampedObject
from google.cloud.videointelligence_v1.types.video_intelligence import Track
from google.cloud.videointelligence_v1.types.video_intelligence import VideoAnnotationProgress
from google.cloud.videointelligence_v1.types.video_intelligence import VideoAnnotationResults
from google.cloud.videointelligence_v1.types.video_intelligence import VideoContext
from google.cloud.videointelligence_v1.types.video_intelligence import VideoSegment
from google.cloud.videointelligence_v1.types.video_intelligence import WordInfo
from google.cloud.videointelligence_v1.types.video_intelligence import Feature
from google.cloud.videointelligence_v1.types.video_intelligence import LabelDetectionMode
from google.cloud.videointelligence_v1.types.video_intelligence import Likelihood
__all__ = ('VideoIntelligenceServiceClient',
'VideoIntelligenceServiceAsyncClient',
'AnnotateVideoProgress',
'AnnotateVideoRequest',
'AnnotateVideoResponse',
'DetectedAttribute',
'DetectedLandmark',
'Entity',
'ExplicitContentAnnotation',
'ExplicitContentDetectionConfig',
'ExplicitContentFrame',
'FaceAnnotation',
'FaceDetectionAnnotation',
'FaceDetectionConfig',
'FaceFrame',
'FaceSegment',
'LabelAnnotation',
'LabelDetectionConfig',
'LabelFrame',
'LabelSegment',
'LogoRecognitionAnnotation',
'NormalizedBoundingBox',
'NormalizedBoundingPoly',
'NormalizedVertex',
'ObjectTrackingAnnotation',
'ObjectTrackingConfig',
'ObjectTrackingFrame',
'PersonDetectionAnnotation',
'PersonDetectionConfig',
'ShotChangeDetectionConfig',
'SpeechContext',
'SpeechRecognitionAlternative',
'SpeechTranscription',
'SpeechTranscriptionConfig',
'TextAnnotation',
'TextDetectionConfig',
'TextFrame',
'TextSegment',
'TimestampedObject',
'Track',
'VideoAnnotationProgress',
'VideoAnnotationResults',
'VideoContext',
'VideoSegment',
'WordInfo',
'Feature',
'LabelDetectionMode',
'Likelihood',
)
| 53.637931 | 130 | 0.851013 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,545 | 0.248312 |
b3ba429b584473910459cd9abd6680855878d8b8 | 406 | py | Python | whileIF.py | JulianConneely/Python-Problem-Sets | 315a43b00c98bff0a9889c730ae13ca963d5fa6c | [
"Apache-2.0"
] | null | null | null | whileIF.py | JulianConneely/Python-Problem-Sets | 315a43b00c98bff0a9889c730ae13ca963d5fa6c | [
"Apache-2.0"
] | null | null | null | whileIF.py | JulianConneely/Python-Problem-Sets | 315a43b00c98bff0a9889c730ae13ca963d5fa6c | [
"Apache-2.0"
] | null | null | null | #Julian Conneely, 21/03/18
#WhileIF loop with increment
#first 5 is printed
#then it is decreased to 4
#as it is not satisfying i<=2
#it moves on
#then 4 is printed
#then it is decreased to 3
#as it is not satisfying i<=2,it moves on
#then 3 is printed
#then it is decreased to 2
#as now i<=2 has completely satisfied, the loop breaks
i = 5
while True:
print(i)
i=i-1
if i<=2:
break
| 19.333333 | 55 | 0.684729 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 324 | 0.79803 |
b3bc40604998529df6bc48de77ceab6a0500f44e | 1,166 | py | Python | board/boardmanager.py | nh-99/COS125-OhMyCheckers | 8e8af36532547e30162a9f4c4d3f204b56b42a6c | [
"MIT"
] | null | null | null | board/boardmanager.py | nh-99/COS125-OhMyCheckers | 8e8af36532547e30162a9f4c4d3f204b56b42a6c | [
"MIT"
] | 3 | 2016-10-23T08:25:19.000Z | 2016-10-24T02:15:41.000Z | board/boardmanager.py | nh-99/COS125-OhMyCheckers | 8e8af36532547e30162a9f4c4d3f204b56b42a6c | [
"MIT"
] | null | null | null | from colorama import Style, Fore
import gamepiece
header = ' 0 1 2 3 4 5 6 7'
footer = ' +---+---+---+---+---+---+---+---+'
def construct_board():
print("\n" * 100)
print Fore.CYAN + "______ _ _ _ _____ _ _"
print "| ___ \ (_) | / __ \ | | | "
print "| |_/ / |_| |_ ___| / \/ |__ ___ ___| | _____ _ __ ___ "
print "| ___ \ | | __|_ / | | '_ \ / _ \/ __| |/ / _ \ '__/ __|"
print "| |_/ / | | |_ / /| \__/\ | | | __/ (__| < __/ | \__ \\"
print "\____/|_|_|\__/___|\____/_| |_|\___|\___|_|\_\___|_| |___/" + Fore.RESET
print
print
print header
print footer
for y in range(0, 8):
to_print = chr(y + 97).upper() + ' '
for x in range(0, 9):
piece = gamepiece.get_piece(str(x) + str(y))
if piece:
to_print += '| ' + piece.get_team() + 'O' + Style.RESET_ALL + ' '
else:
to_print += '| '
print to_print
print footer
def init_board():
gamepiece.init_pieces()
construct_board()
def update_board():
construct_board()
| 29.15 | 84 | 0.43482 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 448 | 0.38422 |
b3bc9203c8074991c7351558c34b1c4b3515287e | 133 | py | Python | config.py | dufftt/social_distance_detector | b5726b544ba34051f0c9acbcba78fc6a87c93397 | [
"MIT"
] | null | null | null | config.py | dufftt/social_distance_detector | b5726b544ba34051f0c9acbcba78fc6a87c93397 | [
"MIT"
] | null | null | null | config.py | dufftt/social_distance_detector | b5726b544ba34051f0c9acbcba78fc6a87c93397 | [
"MIT"
] | 2 | 2020-12-04T04:47:26.000Z | 2021-01-25T10:11:53.000Z | MIN_CONF = 0.3
NMS_THRESH = 0.3
USE_GPU = False
MIN_DISTANCE = 50
WEIGHT_PATH = "yolov3-tiny.weights"
CONFIG_PATH = "yolov3-tiny.cfg" | 22.166667 | 35 | 0.75188 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 38 | 0.285714 |
b3bc9655cec3454fb8290cc9ec39072f8654231f | 82 | py | Python | python/testData/docstrings/googleNoClosingParenthesisAfterParamType.py | jnthn/intellij-community | 8fa7c8a3ace62400c838e0d5926a7be106aa8557 | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | python/testData/docstrings/googleNoClosingParenthesisAfterParamType.py | jnthn/intellij-community | 8fa7c8a3ace62400c838e0d5926a7be106aa8557 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | python/testData/docstrings/googleNoClosingParenthesisAfterParamType.py | jnthn/intellij-community | 8fa7c8a3ace62400c838e0d5926a7be106aa8557 | [
"Apache-2.0"
] | 2 | 2020-03-15T08:57:37.000Z | 2020-04-07T04:48:14.000Z | def f(x, y):
"""
Args:
x (Foo
y (Bar : description
""" | 13.666667 | 28 | 0.353659 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 65 | 0.792683 |
b3bcab9f6387335ff3ee3f73f9b2f6baf6b2f599 | 8,266 | py | Python | analysisAPI/utilities.py | steuwe/coco-analyze | c1e6aa9e64522940342f5487b9160e1ee0dd274f | [
"MIT"
] | null | null | null | analysisAPI/utilities.py | steuwe/coco-analyze | c1e6aa9e64522940342f5487b9160e1ee0dd274f | [
"MIT"
] | null | null | null | analysisAPI/utilities.py | steuwe/coco-analyze | c1e6aa9e64522940342f5487b9160e1ee0dd274f | [
"MIT"
] | null | null | null | ## imports
import os, sys, time, json
import numpy as np
from colour import Color
import matplotlib.pyplot as plt
import matplotlib.path as mplPath
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
from skimage.transform import resize as imresize
import skimage.io as io
"""
Utility functions
"""
num_kpts = 20
oks = [0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95]
sqrt_neg_log_oks = np.sqrt(-2*np.log(oks))
sigmas = np.array([.028, .028, .07, .07,.07,.07, .07, .084,.07, .07, .07, .07, .052, .052, .052, .052, .042, .042, .042, .042])
#sigmas = np.array([.04, .04, .1, .1, .1, .1, .1, .12, .1, .1, .1, .1, .075, .075, .075, .075, .06, .06, .06, .06])
#sigmas = np.array([.028, .028, .07, .07,.07,.07, .07, .084,.07, .07, .07, .07, .052, .052, .052, .052, .042, .042, .042, .042])*2
variances = (sigmas * 2)**2
skeleton = [[0, 3], [1, 3], [3, 2], [0, 1], [5, 0], [6, 1], [2, 4], [4, 7], [7, 10], [7, 11], [8, 12], [9, 13], [12, 16], [13, 17], [10, 14], [11, 15], [14, 18], [15,19]]
colors = {(0,3): '#cd87ff', (1,3): '#cd87ff', (3,2): '#cd87ff', (0,1): '#cd87ff', (5,0): '#cd87ff',
(6,1): '#74c8f9', (2,4): '#74c8f9', (4,7): '#feff95', (7,10): '#74c8f9', (7,11): '#feff95',
(8,12): '#74c8f9', (9,13): '#feff95',(12,16): '#74c8f9', (13,17): '#74c8f9',(10,14): '#feff95',
(11,15): '#a2805b',(14,18): '#a2805b',(15,19): '#a2805b'}
def show_dets(coco_dts, coco_gts, img_info, save_path=None):
if len(coco_dts) == 0 and len(coco_gts)==0:
return 0
I = io.imread(img_info['coco_url'])
plt.figure(figsize=(10,10)); plt.axis('off')
plt.imshow(I)
ax = plt.gca(); ax.set_autoscale_on(False)
polygons = []; color = []
for ann in coco_gts:
c = (np.random.random((1, 3))*0.6+0.4).tolist()[0]
if 'keypoints' in ann and type(ann['keypoints']) == list:
# turn skeleton into zero-based index
sks = np.array(skeleton)
kp = np.array(ann['keypoints'])
x = kp[0::3]; y = kp[1::3]; v = kp[2::3]
for sk in sks:
if np.all(v[sk]>0):
plt.plot(x[sk],y[sk], linewidth=3, color='green')
plt.plot(x[v>0], y[v>0],'o',markersize=2, markerfacecolor='green',
markeredgecolor='k',markeredgewidth=3)
plt.plot(x[v>1], y[v>1],'o',markersize=2, markerfacecolor='green',
markeredgecolor='green', markeredgewidth=2)
for x1, y1, sigma1 in zip(x[v>0], y[v>0], sigmas[v>0]):
r = sigma1 * (np.sqrt(ann["area"])+np.spacing(1))
circle = plt.Circle((x1,y1), sqrt_neg_log_oks[0]*r, fc=(1,0,0,0.4),ec='k')
ax.add_patch(circle)
for a1 in sqrt_neg_log_oks[1:]:
circle = plt.Circle((x1,y1), a1*r, fc=(0,0,0,0),ec='k')
ax.add_patch(circle)
if len(coco_dts)==0 and len(coco_gts)==1:
bbox = ann['bbox']
rect = plt.Rectangle((bbox[0],bbox[1]),bbox[2],bbox[3],fill=False,edgecolor=[1, .6, 0],linewidth=3)
ax.add_patch(rect)
title = "[%d][%d][%d]"%(coco_gts[0]['image_id'],coco_gts[0]['id'],coco_gts[0]['num_keypoints'])
plt.title(title,fontsize=20)
for ann in coco_dts:
c = (np.random.random((1, 3))*0.6+0.4).tolist()[0]
sks = np.array(skeleton)
kp = np.array(ann['keypoints'])
x = kp[0::3]; y = kp[1::3]; v = kp[2::3]
for sk in sks:
plt.plot(x[sk],y[sk], linewidth=3, color=colors[sk[0],sk[1]])
for kk in range(20):
if kk in [0,5,8,10,12,14,16,18]:
plt.plot(x[kk], y[kk],'o',markersize=5, markerfacecolor='r',
markeredgecolor='r', markeredgewidth=3)
elif kk in [1,6,9,11,13,15,17,19]:
plt.plot(x[kk], y[kk],'o',markersize=5, markerfacecolor='g',
markeredgecolor='g', markeredgewidth=3)
else:
plt.plot(x[kk], y[kk],'o',markersize=5, markerfacecolor='b',
markeredgecolor='b', markeredgewidth=3)
bbox = ann['bbox']; score = ann['score']
rect = plt.Rectangle((bbox[0],bbox[1]),bbox[2],bbox[3],fill=False,edgecolor=[1, .6, 0],linewidth=3)
if len(coco_dts)==1:
if len(coco_gts)==0:
title = "[%d][%d][%.3f]"%(coco_dts[0]['image_id'],coco_dts[0]['id'],coco_dts[0]['score'])
plt.title(title,fontsize=20)
if len(coco_gts)==1:
oks = compute_kpts_oks(coco_dts[0]['keypoints'], coco_gts[0]['keypoints'],coco_gts[0]['area'])
title = "[%.3f][%.3f][%d][%d][%d]"%(score,oks,coco_gts[0]['image_id'],coco_gts[0]['id'],coco_dts[0]['id'])
plt.title(title,fontsize=20)
else:
ax.annotate("[%.3f][%.3f]"%(score,0), (bbox[0]+bbox[2]/2.0, bbox[1]-5),
color=[1, .6, 0], weight='bold', fontsize=12, ha='center', va='center')
ax.add_patch(rect)
p = PatchCollection(polygons, facecolor=color, linewidths=0, alpha=0.4)
ax.add_collection(p)
p = PatchCollection(polygons, facecolor="none", edgecolors=color, linewidths=2)
ax.add_collection(p)
if save_path:
plt.savefig(save_path,bbox_inches='tight',dpi=50)
else:
plt.show()
plt.close()
def compute_kpts_oks(dt_kpts, gt_kpts, area):
# this function only works for computing oks with keypoints
g = np.array(gt_kpts); xg = g[0::3]; yg = g[1::3]; vg = g[2::3]
assert( np.count_nonzero(vg > 0) > 0)
d = np.array(dt_kpts); xd = d[0::3]; yd = d[1::3]
dx = xd - xg; dy = yd - yg
e = (dx**2 + dy**2) / variances / (area+np.spacing(1)) / 2
e=e[vg > 0]
return np.sum(np.exp(-e)) / e.shape[0]
def compute_oks(dts, gts):
if len(dts) * len(gts) == 0:
return np.array([])
oks_mat = np.zeros((len(dts), len(gts)))
# compute oks between each detection and ground truth object
for j, gt in enumerate(gts):
# create bounds for ignore regions(double the gt bbox)
g = np.array(gt['keypoints'])
xg = g[0::3]; yg = g[1::3]; vg = g[2::3]
k1 = np.count_nonzero(vg > 0)
bb = gt['bbox']
x0 = bb[0] - bb[2]; x1 = bb[0] + bb[2] * 2
y0 = bb[1] - bb[3]; y1 = bb[1] + bb[3] * 2
for i, dt in enumerate(dts):
d = np.array(dt['keypoints'])
xd = d[0::3]; yd = d[1::3]
if k1>0:
# measure the per-keypoint distance if keypoints visible
dx = xd - xg
dy = yd - yg
else:
# measure minimum distance to keypoints in (x0,y0) & (x1,y1)
z = np.zeros((len(sigmas)))
dx = np.max((z, x0-xd),axis=0)+np.max((z, xd-x1),axis=0)
dy = np.max((z, y0-yd),axis=0)+np.max((z, yd-y1),axis=0)
e = (dx**2 + dy**2) / variances / (gt['area']+np.spacing(1)) / 2
if k1 > 0:
e=e[vg > 0]
oks_mat[i, j] = np.sum(np.exp(-e)) / e.shape[0]
return oks_mat
def compute_iou(bbox_1, bbox_2):
x1_l = bbox_1[0]
x1_r = bbox_1[0] + bbox_1[2]
y1_t = bbox_1[1]
y1_b = bbox_1[1] + bbox_1[3]
w1 = bbox_1[2]
h1 = bbox_1[3]
x2_l = bbox_2[0]
x2_r = bbox_2[0] + bbox_2[2]
y2_t = bbox_2[1]
y2_b = bbox_2[1] + bbox_2[3]
w2 = bbox_2[2]
h2 = bbox_2[3]
xi_l = max(x1_l, x2_l)
xi_r = min(x1_r, x2_r)
yi_t = max(y1_t, y2_t)
yi_b = min(y1_b, y2_b)
width = max(0, xi_r - xi_l)
height = max(0, yi_b - yi_t)
a1 = w1 * h1
a2 = w2 * h2
if float(a1 + a2 - (width * height)) == 0:
return 0
else:
iou = (width * height) / float(a1 + a2 - (width * height))
return iou
def compute_ious(anns):
num_boxes = len(anns)
ious = np.zeros((num_boxes, num_boxes))
for i in range(num_boxes):
for j in range(i,num_boxes):
ious[i,j] = compute_iou(anns[i]['bbox'],anns[j]['bbox'])
if i!=j:
ious[j,i] = ious[i,j]
return ious
| 40.519608 | 171 | 0.510162 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,177 | 0.142391 |
b3c169da3d4b81dde59b6bb476806e478d3ea83d | 3,493 | py | Python | lib/python/batch_sim/gcloud_fakes.py | leozz37/makani | c94d5c2b600b98002f932e80a313a06b9285cc1b | [
"Apache-2.0"
] | 1,178 | 2020-09-10T17:15:42.000Z | 2022-03-31T14:59:35.000Z | lib/python/batch_sim/gcloud_fakes.py | leozz37/makani | c94d5c2b600b98002f932e80a313a06b9285cc1b | [
"Apache-2.0"
] | 1 | 2020-05-22T05:22:35.000Z | 2020-05-22T05:22:35.000Z | lib/python/batch_sim/gcloud_fakes.py | leozz37/makani | c94d5c2b600b98002f932e80a313a06b9285cc1b | [
"Apache-2.0"
] | 107 | 2020-09-10T17:29:30.000Z | 2022-03-18T09:00:14.000Z | # Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""Fake gcloud utils for testing without cloud access."""
from makani.lib.python.batch_sim import gcloud_util
class FakeFilesystem(object):
"""A fake filesystem.
A FakeFilesystem instance is simply a dictionary of file names to file
contents, with Save() and Load() methods to make access look a bit more
file-like.
The class itself also contains LOCAL and CLOUD variables intended to store
references to particular FakeFilesystem instances. These are initialized to
None and intended to be defined as needed via mock.patch. For example:
with mock.patch('makani.batch_sim.gcloud_fakes.FakeFilesystem.LOCAL',
FakeFilesystem()) as local_fs:
<Do something with local files>
with mock.patch('makani.batch_sim.gcloud_fakes.FakeFilesystem.CLOUD',
FakeFilesystem()) as remote_fs:
<Do something with remote files>
In particular, many of the fakes in this module use FakeFilesystem.LOCAL and
FakeFilesystem.CLOUD to simulate actual storage patterns.
"""
LOCAL = None
CLOUD = None
def __init__(self):
self.files = {}
def Save(self, filename, descriptor):
self.files[filename] = descriptor
def Load(self, filename):
return self.files[filename]
class FakeCloudStorageApi(object):
"""A fake of gcloud_util.CloudStorageApi.
This performs simple transfers between FakeFilesystem.LOCAL and
FakeFilesystem.CLOUD.
To simulate working with different local filesystems, FakeFilesystem.LOCAL
may be patched before instantiating the FakeCloudStorageApi.
"""
def __init__(self, bucket=None):
self._local_fs = FakeFilesystem.LOCAL
self._cloud_fs = FakeFilesystem.CLOUD
self._bucket = bucket
def _RemoveBucketFromCloudName(self, cloud_name):
cloud_name = cloud_name.strip()
if cloud_name.startswith('gs://'):
_, cloud_name = gcloud_util.ParseBucketAndPath(cloud_name, None)
return cloud_name
def DownloadFile(self, cloud_name, stream):
cloud_name = self._RemoveBucketFromCloudName(cloud_name)
stream.write(self._cloud_fs.Load(cloud_name))
def UploadFile(self, local_name, cloud_name):
cloud_name = self._RemoveBucketFromCloudName(cloud_name)
self._cloud_fs.Save(cloud_name, self._local_fs.Load(local_name))
def UploadStream(self, stream, cloud_name):
cloud_name = self._RemoveBucketFromCloudName(cloud_name)
self._cloud_fs.Save(cloud_name, stream.getvalue())
def DeletePrefix(self, prefix):
for filename in self.List(prefix):
if filename.startswith(prefix):
self._cloud_fs.files.pop(filename)
def DeleteFile(self, cloud_name):
cloud_name = self._RemoveBucketFromCloudName(cloud_name)
self._cloud_fs.files.pop(cloud_name)
def List(self, prefix):
prefix = self._RemoveBucketFromCloudName(prefix)
return [name for name in self._cloud_fs.files if name.startswith(prefix)]
| 34.93 | 78 | 0.744918 | 2,786 | 0.797595 | 0 | 0 | 0 | 0 | 0 | 0 | 1,823 | 0.521901 |
b3c521b47e06a118b0cd9b713ebd107b3f031206 | 13,030 | py | Python | sequential_inference/envs/robosuite_envs/wipe/wipe_located.py | cvoelcker/sequential_inference | acdc23aa8fdbfc76ded771e82a4abcdd081a3280 | [
"MIT"
] | null | null | null | sequential_inference/envs/robosuite_envs/wipe/wipe_located.py | cvoelcker/sequential_inference | acdc23aa8fdbfc76ded771e82a4abcdd081a3280 | [
"MIT"
] | null | null | null | sequential_inference/envs/robosuite_envs/wipe/wipe_located.py | cvoelcker/sequential_inference | acdc23aa8fdbfc76ded771e82a4abcdd081a3280 | [
"MIT"
] | null | null | null | import numpy as np
import multiprocessing
from robosuite.environments.manipulation.wipe import Wipe, DEFAULT_WIPE_CONFIG
from robosuite.models.tasks import ManipulationTask
from .wipe_located_arena import WipeLocatedArena
class WipeLocated(Wipe):
def __init__(
self,
num_paths=20,
continuous_paths=True,
location_paths="everywhere", # everywhere, left, right, up, down
seed=None,
num_markers=20,
):
self.num_paths = num_paths
self.continuous_paths = continuous_paths
self.location_paths = location_paths
self.seed = seed
config = DEFAULT_WIPE_CONFIG
config.update({"num_markers": num_markers, "arm_limit_collision_penalty": -200})
controller_configs = {
"type": "JOINT_POSITION",
"input_max": 1,
"input_min": -1,
"output_max": 0.05,
"output_min": -0.05,
"kp": 50,
"damping_ratio": 1,
"impedance_mode": "fixed",
"kp_limits": [0, 300],
"damping_ratio_limits": [0, 10],
"qpos_limits": None,
"interpolation": None,
"ramp_ratio": 0.2,
}
super().__init__(
task_config=config,
robots="Panda",
# robots="Sawyer",
has_renderer=False,
has_offscreen_renderer=True,
use_camera_obs=False,
hard_reset=False,
controller_configs=controller_configs,
)
def _load_model(self):
"""
Loads an xml model, puts it in self.model
"""
super()._load_model()
# Adjust base pose accordingly
xpos = self.robots[0].robot_model.base_xpos_offset["table"](
self.table_full_size[0]
)
self.robots[0].robot_model.set_base_xpos(xpos)
# Get robot's contact geoms
self.robot_contact_geoms = self.robots[0].robot_model.contact_geoms
mujoco_arena = WipeLocatedArena(
table_full_size=self.table_full_size,
table_friction=self.table_friction,
table_offset=self.table_offset,
table_friction_std=self.table_friction_std,
coverage_factor=self.coverage_factor,
num_markers=self.num_markers,
line_width=self.line_width,
num_paths=self.num_paths,
continuous_paths=self.continuous_paths,
location_paths=self.location_paths,
seed=self.seed,
)
# Arena always gets set to zero origin
mujoco_arena.set_origin([0, 0, 0])
# task includes arena, robot, and objects of interest
self.model = ManipulationTask(
mujoco_arena=mujoco_arena,
mujoco_robots=[robot.robot_model for robot in self.robots],
)
def reward(self, action=None):
"""
Reward function for the task.
Sparse un-normalized reward:
- a discrete reward of self.unit_wiped_reward is provided per single dirt (peg) wiped during this step
- a discrete reward of self.task_complete_reward is provided if all dirt is wiped
Note that if the arm is either colliding or near its joint limit, a reward of 0 will be automatically given
Un-normalized summed components if using reward shaping (individual components can be set to 0:
- Reaching: in [0, self.distance_multiplier], proportional to distance between wiper and centroid of dirt
and zero if the table has been fully wiped clean of all the dirt
- Table Contact: in {0, self.wipe_contact_reward}, non-zero if wiper is in contact with table
- Wiping: in {0, self.unit_wiped_reward}, non-zero for each dirt (peg) wiped during this step
- Cleaned: in {0, self.task_complete_reward}, non-zero if no dirt remains on the table
- Collision / Joint Limit Penalty: in {self.arm_limit_collision_penalty, 0}, nonzero if robot arm
is colliding with an object
- Note that if this value is nonzero, no other reward components can be added
- Large Force Penalty: in [-inf, 0], scaled by wiper force and directly proportional to
self.excess_force_penalty_mul if the current force exceeds self.pressure_threshold_max
- Large Acceleration Penalty: in [-inf, 0], scaled by estimated wiper acceleration and directly
proportional to self.ee_accel_penalty
Note that the final per-step reward is normalized given the theoretical best episode return and then scaled:
reward_scale * (horizon /
(num_markers * unit_wiped_reward + horizon * (wipe_contact_reward + task_complete_reward)))
Args:
action (np array): [NOT USED]
Returns:
float: reward value
"""
reward = 0
total_force_ee = np.linalg.norm(
np.array(self.robots[0].recent_ee_forcetorques.current[:3])
)
# Skip checking whether limits are achieved (maybe unsafe for real robots)
active_markers = []
# Current 3D location of the corners of the wiping tool in world frame
c_geoms = self.robots[0].gripper.important_geoms["corners"]
corner1_id = self.sim.model.geom_name2id(c_geoms[0])
corner1_pos = np.array(self.sim.data.geom_xpos[corner1_id])
corner2_id = self.sim.model.geom_name2id(c_geoms[1])
corner2_pos = np.array(self.sim.data.geom_xpos[corner2_id])
corner3_id = self.sim.model.geom_name2id(c_geoms[2])
corner3_pos = np.array(self.sim.data.geom_xpos[corner3_id])
corner4_id = self.sim.model.geom_name2id(c_geoms[3])
corner4_pos = np.array(self.sim.data.geom_xpos[corner4_id])
# Unit vectors on my plane
v1 = corner1_pos - corner2_pos
v1 /= np.linalg.norm(v1)
v2 = corner4_pos - corner2_pos
v2 /= np.linalg.norm(v2)
# Corners of the tool in the coordinate frame of the plane
t1 = np.array(
[
np.dot(corner1_pos - corner2_pos, v1),
np.dot(corner1_pos - corner2_pos, v2),
]
)
t2 = np.array(
[
np.dot(corner2_pos - corner2_pos, v1),
np.dot(corner2_pos - corner2_pos, v2),
]
)
t3 = np.array(
[
np.dot(corner3_pos - corner2_pos, v1),
np.dot(corner3_pos - corner2_pos, v2),
]
)
t4 = np.array(
[
np.dot(corner4_pos - corner2_pos, v1),
np.dot(corner4_pos - corner2_pos, v2),
]
)
pp = [t1, t2, t4, t3]
# Normal of the plane defined by v1 and v2
n = np.cross(v1, v2)
n /= np.linalg.norm(n)
def isLeft(P0, P1, P2):
return (P1[0] - P0[0]) * (P2[1] - P0[1]) - (P2[0] - P0[0]) * (P1[1] - P0[1])
def PointInRectangle(X, Y, Z, W, P):
return (
isLeft(X, Y, P) < 0
and isLeft(Y, Z, P) < 0
and isLeft(Z, W, P) < 0
and isLeft(W, X, P) < 0
)
# Only go into this computation if there are contact points
if self.sim.data.ncon != 0:
# Check each marker that is still active
for marker in self.model.mujoco_arena.markers:
# Current marker 3D location in world frame
marker_pos = np.array(
self.sim.data.body_xpos[
self.sim.model.body_name2id(marker.root_body)
]
)
# We use the second tool corner as point on the plane and define the vector connecting
# the marker position to that point
v = marker_pos - corner2_pos
# Shortest distance between the center of the marker and the plane
dist = np.dot(v, n)
# Projection of the center of the marker onto the plane
projected_point = np.array(marker_pos) - dist * n
# Positive distances means the center of the marker is over the plane
# The plane is aligned with the bottom of the wiper and pointing up, so the marker would be over it
if dist > 0.0:
# Distance smaller than this threshold means we are close to the plane on the upper part
if dist < 0.02:
# Write touching points and projected point in coordinates of the plane
pp_2 = np.array(
[
np.dot(projected_point - corner2_pos, v1),
np.dot(projected_point - corner2_pos, v2),
]
)
# Check if marker is within the tool center:
if PointInRectangle(pp[0], pp[1], pp[2], pp[3], pp_2):
active_markers.append(marker)
# Obtain the list of currently active (wiped) markers that where not wiped before
# These are the markers we are wiping at this step
lall = np.where(np.isin(active_markers, self.wiped_markers, invert=True))
new_active_markers = np.array(active_markers)[lall]
# Loop through all new markers we are wiping at this step
for new_active_marker in new_active_markers:
# Grab relevant marker id info
new_active_marker_geom_id = self.sim.model.geom_name2id(
new_active_marker.visual_geoms[0]
)
# Make this marker transparent since we wiped it (alpha = 0)
self.sim.model.geom_rgba[new_active_marker_geom_id][3] = 0
# Add this marker the wiped list
self.wiped_markers.append(new_active_marker)
# Add reward if we're using the dense reward
if self.reward_shaping:
reward += self.unit_wiped_reward
# Additional reward components if using dense rewards
if self.reward_shaping:
# If we haven't wiped all the markers yet, add a smooth reward for getting closer
# to the centroid of the dirt to wipe
if len(self.wiped_markers) < self.num_markers:
_, _, mean_pos_to_things_to_wipe = self._get_wipe_information
mean_distance_to_things_to_wipe = np.linalg.norm(
mean_pos_to_things_to_wipe
)
dist = 5 * mean_distance_to_things_to_wipe
reward += -(dist ** 2 + np.log(dist ** 2 + 1e-6))
# reward += self.distance_multiplier * (
# 1 - np.tanh(self.distance_th_multiplier * mean_distance_to_things_to_wipe))
# Reward for keeping contact
if self.sim.data.ncon != 0 and self._has_gripper_contact:
reward += self.wipe_contact_reward
# Penalty for excessive force with the end-effector
if total_force_ee > self.pressure_threshold_max:
reward -= self.excess_force_penalty_mul * total_force_ee
self.f_excess += 1
# Reward for pressing into table
# TODO: Need to include this computation somehow in the scaled reward computation
elif total_force_ee > self.pressure_threshold and self.sim.data.ncon > 1:
reward += self.wipe_contact_reward + 0.01 * total_force_ee
if self.sim.data.ncon > 50:
reward += 10.0 * self.wipe_contact_reward
# Penalize large accelerations
reward -= self.ee_accel_penalty * np.mean(
abs(self.robots[0].recent_ee_acc.current)
)
# Final reward if all wiped
if len(self.wiped_markers) == self.num_markers:
reward += self.task_complete_reward
# Printing results
if self.print_results:
string_to_print = (
"Process {pid}, timestep {ts:>4}: reward: {rw:8.4f}"
"wiped markers: {ws:>3} collisions: {sc:>3} f-excess: {fe:>3}".format(
pid=id(multiprocessing.current_process()),
ts=self.timestep,
rw=reward,
ws=len(self.wiped_markers),
sc=self.collisions,
fe=self.f_excess,
)
)
print(string_to_print)
# If we're scaling our reward, we normalize the per-step rewards given the theoretical best episode return
# This is equivalent to scaling the reward by:
# reward_scale * (horizon /
# (num_markers * unit_wiped_reward + horizon * (wipe_contact_reward + task_complete_reward)))
if self.reward_scale:
reward *= self.reward_scale * self.reward_normalization_factor
return reward
| 41.496815 | 117 | 0.582655 | 12,804 | 0.982655 | 0 | 0 | 0 | 0 | 0 | 0 | 4,858 | 0.372832 |
b3c523babfa6c91c516925e84f0584c0ee39d7fd | 1,574 | py | Python | tpp_tensorflow/models/dense.py | gfrogat/tpp_tensorflow | 711dd8cc0a8155ce6b6e5663afb2331b55748d30 | [
"MIT"
] | null | null | null | tpp_tensorflow/models/dense.py | gfrogat/tpp_tensorflow | 711dd8cc0a8155ce6b6e5663afb2331b55748d30 | [
"MIT"
] | null | null | null | tpp_tensorflow/models/dense.py | gfrogat/tpp_tensorflow | 711dd8cc0a8155ce6b6e5663afb2331b55748d30 | [
"MIT"
] | null | null | null |
from tensorflow.keras import layers, Model, regularizers
class DenseHead(Model):
def __init__(self, params):
super(DenseHead, self).__init__()
# Correctly handle SELU
dropout = layers.AlphaDropout if params.activation == "selu" else layers.Dropout
kernel_init = (
"lecun_normal" if params.activation == "selu" else params.kernel_init
)
kernel_reg = (
regularizers.l2(params.reg_l2_rate)
if params.reg_l2_rate is not None
else None
)
self.hidden_layers = []
self.dropout_layers = []
for i in range(params.hidden_layers):
self.hidden_layers.append(
layers.Dense(
params.hidden_units,
activation=params.activation,
kernel_initializer=kernel_init,
kernel_regularizer=kernel_reg,
name="dense_{}".format(i),
)
)
self.dropout_layers.append(
dropout(
params.dropout_rate,
seed=params.dropout_seed,
name="dropout_{}".format(i),
)
)
self.output_layer = layers.Dense(
params.num_classes, activation=None, name="dense_output"
)
def call(self, x, training=False):
for h_layer, d_layer in zip(self.hidden_layers, self.dropout_layers):
x = d_layer(x, training)
x = h_layer(x)
return self.output_layer(x)
| 30.862745 | 88 | 0.541296 | 1,513 | 0.961245 | 0 | 0 | 0 | 0 | 0 | 0 | 85 | 0.054003 |
b3ccac0791a7fa5430a1fcfe5c670dbca799bbe5 | 167 | py | Python | boundlexx/celery/management/commands/purge_in_progress.py | AngellusMortis/boundlexx | 407f5e38e8e0f067cbcb358787fc9af6a9be9b2a | [
"MIT"
] | 1 | 2021-04-23T11:49:50.000Z | 2021-04-23T11:49:50.000Z | boundlexx/celery/management/commands/purge_in_progress.py | AngellusMortis/boundlexx | 407f5e38e8e0f067cbcb358787fc9af6a9be9b2a | [
"MIT"
] | 1 | 2021-04-17T18:17:12.000Z | 2021-04-17T18:17:12.000Z | boundlexx/celery/management/commands/purge_in_progress.py | AngellusMortis/boundlexx | 407f5e38e8e0f067cbcb358787fc9af6a9be9b2a | [
"MIT"
] | null | null | null | import djclick as click
from django_celery_results.models import TaskResult
@click.command()
def command():
TaskResult.objects.filter(status="STARTED").delete()
| 20.875 | 56 | 0.784431 | 0 | 0 | 0 | 0 | 88 | 0.526946 | 0 | 0 | 9 | 0.053892 |
b3cce8916fc9bfd0ead2ad75214492f8a80b5d93 | 20,516 | py | Python | Example Device - Thermostat.indigoPlugin/Contents/Server Plugin/plugin.py | IndigoDomotics/IndigoSDK | fbbca6fdbaa0c23e6faa848523e5fa121f3100b4 | [
"MIT"
] | null | null | null | Example Device - Thermostat.indigoPlugin/Contents/Server Plugin/plugin.py | IndigoDomotics/IndigoSDK | fbbca6fdbaa0c23e6faa848523e5fa121f3100b4 | [
"MIT"
] | 1 | 2022-02-11T21:03:44.000Z | 2022-02-11T21:06:16.000Z | Example Device - Thermostat.indigoPlugin/Contents/Server Plugin/plugin.py | IndigoDomotics/IndigoSDK | fbbca6fdbaa0c23e6faa848523e5fa121f3100b4 | [
"MIT"
] | 2 | 2022-02-10T23:53:03.000Z | 2022-03-05T17:18:43.000Z | #! /usr/bin/env python
# -*- coding: utf-8 -*-
####################
# Copyright (c) 2022, Perceptive Automation, LLC. All rights reserved.
# https://www.indigodomo.com
import indigo
import os
import sys
import random
# Note the "indigo" module is automatically imported and made available inside
# our global name space by the host process.
################################################################################
HVAC_MODE_ENUM_TO_STR_MAP = {
indigo.kHvacMode.Cool : "cool",
indigo.kHvacMode.Heat : "heat",
indigo.kHvacMode.HeatCool : "auto",
indigo.kHvacMode.Off : "off",
indigo.kHvacMode.ProgramHeat : "program heat",
indigo.kHvacMode.ProgramCool : "program cool",
indigo.kHvacMode.ProgramHeatCool : "program auto"
}
FAN_MODE_ENUM_TO_STR_MAP = {
indigo.kFanMode.AlwaysOn : "always on",
indigo.kFanMode.Auto : "auto"
}
def _lookup_action_str_from_hvac_mode(hvac_mode):
return HVAC_MODE_ENUM_TO_STR_MAP.get(hvac_mode, "unknown")
def _lookup_action_str_from_fan_mode(fan_mode):
return FAN_MODE_ENUM_TO_STR_MAP.get(fan_mode, "unknown")
################################################################################
class Plugin(indigo.PluginBase):
########################################
def __init__(self, plugin_id, plugin_display_name, plugin_version, plugin_prefs):
super().__init__(plugin_id, plugin_display_name, plugin_version, plugin_prefs)
self.debug = False
self.simulate_temp_changes = True # Every few seconds update to random temperature values
self.simulate_humidity_changes = True # Every few seconds update to random humidity values
self.refresh_delay = 2 # Simulate new temperature values every 2 seconds
########################################
# Internal utility methods. Some of these are useful to provide
# a higher-level abstraction for accessing/changing thermostat
# properties or states.
######################
def _change_temp_sensor_count(self, dev, count):
new_props = dev.pluginProps
new_props["NumTemperatureInputs"] = count
dev.replacePluginPropsOnServer(new_props)
def _change_humidity_sensor_count(self, dev, count):
new_props = dev.pluginProps
new_props["NumHumidityInputs"] = count
dev.replacePluginPropsOnServer(new_props)
def _change_all_temp_sensor_counts(self, count):
for dev in indigo.devices.iter("self"):
self._change_temp_sensor_count(dev, count)
def _change_all_humidity_sensor_counts(self, count):
for dev in indigo.devices.iter("self"):
self._change_humidity_sensor_count(dev, count)
######################
def _change_temp_sensor_value(self, dev, index, value, key_val_list):
# Update the temperature value at index. If index is greater than the "NumTemperatureInputs"
# an error will be displayed in the Event Log "temperature index out-of-range"
state_key = "temperatureInput" + str(index)
key_val_list.append({'key':state_key, 'value':value, 'uiValue':f"{value} °F"})
self.logger.debug(f"\"{dev.name}\" updating {state_key} {value}")
def _change_humidity_sensor_value(self, dev, index, value, key_val_list):
# Update the humidity value at index. If index is greater than the "NumHumidityInputs"
# an error will be displayed in the Event Log "humidity index out-of-range"
state_key = "humidityInput" + str(index)
key_val_list.append({'key':state_key, 'value':value, 'uiValue':f"{value}%"})
self.logger.debug(f"\"{dev.name}\" updating {state_key} {value}")
######################
# Poll all of the states from the thermostat and pass new values to
# Indigo Server.
def _refresh_states_from_hardware(self, dev, log_refresh, comm_just_started):
# As an example here we update the temperature and humidity
# sensor states to random values.
key_val_list = []
if self.simulate_temp_changes:
# Simulate changing temperature values coming in from the
# hardware by updating all temp values randomly:
num_temps = dev.temperatureSensorCount
for index in range(1, num_temps + 1):
example_temp = random.randint(62, 88)
self._change_temp_sensor_value(dev, index, example_temp, key_val_list)
if log_refresh:
self.logger.info(f"received \"{dev.name}\" temperature{index} update to {example_temp:.1f}°")
if dev.pluginProps.get("ShowCoolHeatEquipmentStateUI", False) and "hvacOperationMode" in dev.states and "setpointCool" in dev.states and "setpointHeat" in dev.states:
if dev.states["hvacOperationMode"] in [indigo.kHvacMode.Cool, indigo.kHvacMode.HeatCool, indigo.kHvacMode.ProgramCool, indigo.kHvacMode.ProgramHeatCool]:
key_val_list.append({'key':'hvacCoolerIsOn', 'value':example_temp > dev.states["setpointCool"]})
if dev.states["hvacOperationMode"] in [indigo.kHvacMode.Heat, indigo.kHvacMode.HeatCool, indigo.kHvacMode.ProgramHeat, indigo.kHvacMode.ProgramHeatCool]:
key_val_list.append({'key':'hvacHeaterIsOn', 'value':example_temp < dev.states["setpointHeat"]})
if self.simulate_humidity_changes:
# Simulate changing humidity values coming in from the
# hardware by updating all humidity values randomly:
num_sensors = dev.humiditySensorCount
for index in range(1, num_sensors + 1):
example_humidity = random.randint(15, 90)
self._change_humidity_sensor_value(dev, index, example_humidity, key_val_list)
if log_refresh:
self.logger.info(f"received \"{dev.name}\" humidity{index} update to {example_humidity:.0f}%")
# Other states that should also be updated:
# ** IMPLEMENT ME **
# key_val_list.append({'key':'setpointHeat', 'value':floating number here})
# key_val_list.append({'key':'setpointCool', 'value':floating number here})
# key_val_list.append({'key':'hvacOperationMode', 'value':some indigo.kHvacMode.* value here})
# key_val_list.append({'key':'hvacFanMode', 'value':some indigo.kFanMode.* value here})
# key_val_list.append({'key':'hvacCoolerIsOn', 'value':True or False here})
# key_val_list.append({'key':'hvacHeaterIsOn', 'value':True or False here})
# key_val_list.append({'key':'hvacFanIsOn', 'value':True or False here})
if comm_just_started:
# As an example, we force these thermostat states to specific values.
if "setpointHeat" in dev.states:
key_val_list.append({'key':'setpointHeat', 'value':66.5, 'uiValue':"66.5 °F"})
if "setpointCool" in dev.states:
key_val_list.append({'key':'setpointCool', 'value':77.5, 'uiValue':"77.5 °F"})
if "hvacOperationMode" in dev.states:
key_val_list.append({'key':'hvacOperationMode', 'value':indigo.kHvacMode.HeatCool})
if "hvacFanMode" in dev.states:
key_val_list.append({'key':'hvacFanMode', 'value':indigo.kFanMode.Auto})
key_val_list.append({'key':'backlightBrightness', 'value':85, 'uiValue':"85%"})
if len(key_val_list) > 0:
dev.updateStatesOnServer(key_val_list)
if log_refresh:
if "setpointHeat" in dev.states:
self.logger.info(f"received \"{dev.name}\" cool setpoint update to {dev.states['setpointHeat']:.1f}°")
if "setpointCool" in dev.states:
self.logger.info(f"received \"{dev.name}\" heat setpoint update to {dev.states['setpointCool']:.1f}°")
if "hvacOperationMode" in dev.states:
action_str = _lookup_action_str_from_hvac_mode(dev.states["hvacOperationMode"])
self.logger.info(f"received \"{dev.name}\" main mode update to {action_str}")
if "hvacFanMode" in dev.states:
action_str = _lookup_action_str_from_fan_mode(dev.states["hvacFanMode"])
self.logger.info(f"received \"{dev.name}\" fan mode update to {action_str}")
self.logger.info(f"received \"{dev.name}\" backlight brightness update to {dev.states['backlightBrightness']}%")
######################
# Process action request from Indigo Server to change main thermostat's main mode.
def _handle_change_hvac_mode_action(self, dev, new_hvac_mode):
# Command hardware module (dev) to change the thermostat mode here:
# ** IMPLEMENT ME **
send_success = True # Set to False if it failed.
action_str = _lookup_action_str_from_hvac_mode(new_hvac_mode)
if send_success:
# If success then log that the command was successfully sent.
self.logger.info(f"sent \"{dev.name}\" mode change to {action_str}")
# And then tell the Indigo Server to update the state.
if "hvacOperationMode" in dev.states:
dev.updateStateOnServer("hvacOperationMode", new_hvac_mode)
else:
# Else log failure but do NOT update state on Indigo Server.
self.logger.error(f"send \"{dev.name}\" mode change to {action_str} failed")
######################
# Process action request from Indigo Server to change thermostat's fan mode.
def _handle_change_fan_mode_action(self, dev, new_fan_mode):
# Command hardware module (dev) to change the fan mode here:
# ** IMPLEMENT ME **
send_success = True # Set to False if it failed.
action_str = _lookup_action_str_from_fan_mode(new_fan_mode)
if send_success:
# If success then log that the command was successfully sent.
self.logger.info(f"sent \"{dev.name}\" fan mode change to {action_str}")
# And then tell the Indigo Server to update the state.
if "hvacFanMode" in dev.states:
dev.updateStateOnServer("hvacFanMode", new_fan_mode)
else:
# Else log failure but do NOT update state on Indigo Server.
self.logger.error(f"send \"{dev.name}\" fan mode change to {action_str} failed")
######################
# Process action request from Indigo Server to change a cool/heat setpoint.
def _handle_change_setpoint_action(self, dev, new_setpoint, log_action_name, state_key):
if new_setpoint < 40.0:
new_setpoint = 40.0 # Arbitrary -- set to whatever hardware minimum setpoint value is.
elif new_setpoint > 95.0:
new_setpoint = 95.0 # Arbitrary -- set to whatever hardware maximum setpoint value is.
send_success = False
if state_key == "setpointCool":
# Command hardware module (dev) to change the cool setpoint to new_setpoint here:
# ** IMPLEMENT ME **
send_success = True # Set to False if it failed.
elif state_key == "setpointHeat":
# Command hardware module (dev) to change the heat setpoint to new_setpoint here:
# ** IMPLEMENT ME **
send_success = True # Set to False if it failed.
if send_success:
# If success then log that the command was successfully sent.
self.logger.info(f"sent \"{dev.name}\" {log_action_name} to {new_setpoint:.1f}°")
# And then tell the Indigo Server to update the state.
if state_key in dev.states:
dev.updateStateOnServer(state_key, new_setpoint, uiValue=f"{new_setpoint:.1f} °F")
else:
# Else log failure but do NOT update state on Indigo Server.
self.logger.error(f"send \"{dev.name}\" {log_action_name} to {new_setpoint:.1f}° failed")
########################################
def startup(self):
self.logger.debug("startup called")
def shutdown(self):
self.logger.debug("shutdown called")
########################################
def runConcurrentThread(self):
try:
while True:
for dev in indigo.devices.iter("self"):
if not dev.enabled or not dev.configured:
continue
# Plugins that need to poll out the status from the thermostat
# could do so here, then broadcast back the new values to the
# Indigo Server.
self._refresh_states_from_hardware(dev, False, False)
self.sleep(self.refresh_delay)
except self.StopThread:
pass # Optionally catch the StopThread exception and do any needed cleanup.
########################################
def validateDeviceConfigUi(self, values_dict, type_id, dev_id):
return (True, values_dict)
########################################
def deviceStartComm(self, dev):
# Called when communication with the hardware should be established.
# Here would be a good place to poll out the current states from the
# thermostat. If periodic polling of the thermostat is needed (that
# is, it doesn't broadcast changes back to the plugin somehow), then
# consider adding that to runConcurrentThread() above.
self._refresh_states_from_hardware(dev, True, True)
def deviceStopComm(self, dev):
# Called when communication with the hardware should be shutdown.
pass
########################################
# Thermostat Action callback
######################
# Main thermostat action bottleneck called by Indigo Server.
def actionControlThermostat(self, action, dev):
###### SET HVAC MODE ######
if action.thermostatAction == indigo.kThermostatAction.SetHvacMode:
self._handle_change_hvac_mode_action(dev, action.actionMode)
###### SET FAN MODE ######
elif action.thermostatAction == indigo.kThermostatAction.SetFanMode:
self._handle_change_fan_mode_action(dev, action.actionMode)
###### SET COOL SETPOINT ######
elif action.thermostatAction == indigo.kThermostatAction.SetCoolSetpoint:
new_setpoint = action.actionValue
self._handle_change_setpoint_action(dev, new_setpoint, "change cool setpoint", "setpointCool")
###### SET HEAT SETPOINT ######
elif action.thermostatAction == indigo.kThermostatAction.SetHeatSetpoint:
new_setpoint = action.actionValue
self._handle_change_setpoint_action(dev, new_setpoint, "change heat setpoint", "setpointHeat")
###### DECREASE/INCREASE COOL SETPOINT ######
elif action.thermostatAction == indigo.kThermostatAction.DecreaseCoolSetpoint:
new_setpoint = dev.coolSetpoint - action.actionValue
self._handle_change_setpoint_action(dev, new_setpoint, "decrease cool setpoint", "setpointCool")
elif action.thermostatAction == indigo.kThermostatAction.IncreaseCoolSetpoint:
new_setpoint = dev.coolSetpoint + action.actionValue
self._handle_change_setpoint_action(dev, new_setpoint, "increase cool setpoint", "setpointCool")
###### DECREASE/INCREASE HEAT SETPOINT ######
elif action.thermostatAction == indigo.kThermostatAction.DecreaseHeatSetpoint:
new_setpoint = dev.heatSetpoint - action.actionValue
self._handle_change_setpoint_action(dev, new_setpoint, "decrease heat setpoint", "setpointHeat")
elif action.thermostatAction == indigo.kThermostatAction.IncreaseHeatSetpoint:
new_setpoint = dev.heatSetpoint + action.actionValue
self._handle_change_setpoint_action(dev, new_setpoint, "increase heat setpoint", "setpointHeat")
###### REQUEST STATE UPDATES ######
elif action.thermostatAction in [indigo.kThermostatAction.RequestStatusAll, indigo.kThermostatAction.RequestMode,
indigo.kThermostatAction.RequestEquipmentState, indigo.kThermostatAction.RequestTemperatures, indigo.kThermostatAction.RequestHumidities,
indigo.kThermostatAction.RequestDeadbands, indigo.kThermostatAction.RequestSetpoints]:
self._refresh_states_from_hardware(dev, True, False)
########################################
# General Action callback
######################
def actionControlUniversal(self, action, dev):
###### BEEP ######
if action.deviceAction == indigo.kUniversalAction.Beep:
# Beep the hardware module (dev) here:
# ** IMPLEMENT ME **
self.logger.info(f"sent \"{dev.name}\" beep request")
###### ENERGY UPDATE ######
elif action.deviceAction == indigo.kUniversalAction.EnergyUpdate:
# Request hardware module (dev) for its most recent meter data here:
# ** IMPLEMENT ME **
self.logger.info(f"sent \"{dev.name}\" energy update request")
###### ENERGY RESET ######
elif action.deviceAction == indigo.kUniversalAction.EnergyReset:
# Request that the hardware module (dev) reset its accumulative energy usage data here:
# ** IMPLEMENT ME **
self.logger.info(f"sent \"{dev.name}\" energy reset request")
###### STATUS REQUEST ######
elif action.deviceAction == indigo.kUniversalAction.RequestStatus:
# Query hardware module (dev) for its current status here. This differs from the
# indigo.kThermostatAction.RequestStatusAll action - for instance, if your thermo
# is battery powered you might only want to update it only when the user uses
# this status request (and not from the RequestStatusAll). This action would
# get all possible information from the thermostat and the other call
# would only get thermostat-specific information:
# ** GET BATTERY INFO **
# and call the common function to update the thermo-specific data
self._refresh_states_from_hardware(dev, True, False)
self.logger.info(f"sent \"{dev.name}\" status request")
########################################
# Custom Plugin Action callbacks (defined in Actions.xml)
######################
def set_backlight_brightness(self, plugin_action, dev):
try:
new_brightness = int(plugin_action.props.get("brightness", 100))
except ValueError:
# The int() cast above might fail if the user didn't enter a number:
self.logger.error(f"set backlight brightness action to device \"{dev.name}\" -- invalid brightness value")
return
# Command hardware module (dev) to set backlight brightness here:
# FIXME: add implementation here
send_success = True # Set to False if it failed.
if send_success:
# If success then log that the command was successfully sent.
self.logger.info(f"sent \"{dev.name}\" set backlight brightness to {new_brightness}")
# And then tell the Indigo Server to update the state:
dev.updateStateOnServer("backlightBrightness", new_brightness)
else:
# Else log failure but do NOT update state on Indigo Server.
self.logger.error(f"send \"{dev.name}\" set backlight brightness to {new_brightness} failed")
########################################
# Actions defined in MenuItems.xml. In this case we just use these menu actions to
# simulate different thermostat configurations (how many temperature and humidity
# sensors they have).
####################
def change_temp_sensor_count_to_1(self):
self._change_all_temp_sensor_counts(1)
def change_temp_sensor_count_to_2(self):
self._change_all_temp_sensor_counts(2)
def change_temp_sensor_count_to_3(self):
self._change_all_temp_sensor_counts(3)
def change_humidity_sensor_count_to_0(self):
self._change_all_humidity_sensor_counts(0)
def change_humidity_sensor_count_to_1(self):
self._change_all_humidity_sensor_counts(1)
def change_humidity_sensor_count_to_2(self):
self._change_all_humidity_sensor_counts(2)
def change_humidity_sensor_count_to_3(self):
self._change_all_humidity_sensor_counts(3)
| 52.071066 | 182 | 0.634285 | 19,250 | 0.937881 | 0 | 0 | 0 | 0 | 0 | 0 | 9,155 | 0.446041 |
b3ceb7bacaabc9d374ce9e5489d90bcedfbf69ad | 159 | py | Python | dp_tornado/helper/security/web/__init__.py | donghak-shin/dp-tornado | 095bb293661af35cce5f917d8a2228d273489496 | [
"MIT"
] | 18 | 2015-04-07T14:28:39.000Z | 2020-02-08T14:03:38.000Z | dp_tornado/helper/security/web/__init__.py | donghak-shin/dp-tornado | 095bb293661af35cce5f917d8a2228d273489496 | [
"MIT"
] | 7 | 2016-10-05T05:14:06.000Z | 2021-05-20T02:07:22.000Z | dp_tornado/helper/security/web/__init__.py | donghak-shin/dp-tornado | 095bb293661af35cce5f917d8a2228d273489496 | [
"MIT"
] | 11 | 2015-12-15T09:49:39.000Z | 2021-09-06T18:38:21.000Z | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from dp_tornado.engine.helper import Helper as dpHelper
class WebHelper(dpHelper):
pass
| 15.9 | 55 | 0.748428 | 35 | 0.220126 | 0 | 0 | 0 | 0 | 0 | 0 | 23 | 0.144654 |
b3d08a0120015a60c620ea1e806103c54c2cbf58 | 196 | py | Python | LeetCode/python3/136.py | ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 279 | 2019-02-19T16:00:32.000Z | 2022-03-23T12:16:30.000Z | LeetCode/python3/136.py | ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 2 | 2019-03-31T08:03:06.000Z | 2021-03-07T04:54:32.000Z | LeetCode/python3/136.py | ZintrulCre/LeetCode_Crawler | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 12 | 2019-01-29T11:45:32.000Z | 2019-02-04T16:31:46.000Z | class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
k = 0
for n in nums:
k ^= n
return k | 19.6 | 33 | 0.408163 | 196 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 65 | 0.331633 |
b3d2818801e85a29eccfd608b62683f33282a6d9 | 2,071 | py | Python | src/genie/libs/parser/iosxr/tests/ShowVrrpSummary/cli/equal/golden_output_1_expected.py | nielsvanhooy/genieparser | 9a1955749697a6777ca614f0af4d5f3a2c254ccd | [
"Apache-2.0"
] | null | null | null | src/genie/libs/parser/iosxr/tests/ShowVrrpSummary/cli/equal/golden_output_1_expected.py | nielsvanhooy/genieparser | 9a1955749697a6777ca614f0af4d5f3a2c254ccd | [
"Apache-2.0"
] | null | null | null | src/genie/libs/parser/iosxr/tests/ShowVrrpSummary/cli/equal/golden_output_1_expected.py | nielsvanhooy/genieparser | 9a1955749697a6777ca614f0af4d5f3a2c254ccd | [
"Apache-2.0"
] | null | null | null | expected_output = {
"address_family":{
"ipv4":{
"bfd_sessions_down":0,
"bfd_sessions_inactive":1,
"bfd_sessions_up":0,
"intf_down":1,
"intf_up":1,
"num_bfd_sessions":1,
"num_intf":2,
"state":{
"all":{
"sessions":2,
"slaves":0,
"total":2
},
"backup":{
"sessions":1,
"slaves":0,
"total":1
},
"init":{
"sessions":1,
"slaves":0,
"total":1
},
"master":{
"sessions":0,
"slaves":0,
"total":0
},
"master(owner)":{
"sessions":0,
"slaves":0,
"total":0
}
},
"virtual_addresses_active":0,
"virtual_addresses_inactive":2,
"vritual_addresses_total":2
},
"ipv6":{
"bfd_sessions_down":0,
"bfd_sessions_inactive":0,
"bfd_sessions_up":0,
"intf_down":0,
"intf_up":1,
"num_bfd_sessions":0,
"num_intf":1,
"state":{
"all":{
"sessions":1,
"slaves":0,
"total":1
},
"backup":{
"sessions":0,
"slaves":0,
"total":0
},
"init":{
"sessions":0,
"slaves":0,
"total":0
},
"master":{
"sessions":1,
"slaves":0,
"total":1
},
"master(owner)":{
"sessions":0,
"slaves":0,
"total":0
}
},
"virtual_addresses_active":1,
"virtual_addresses_inactive":0,
"vritual_addresses_total":1
},
"num_tracked_objects":2,
"tracked_objects_down":2,
"tracked_objects_up":0
}
}
| 24.081395 | 40 | 0.356832 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 811 | 0.391598 |
b3d5ab9d0c7d20b407fce0bfd20bb2118f0eb307 | 2,159 | py | Python | characterCrowd.py | campbellwmorgan/charactercrowd | 968f53ea23c347d57e7e45d46206ab4dc8fb39ca | [
"Apache-2.0"
] | 1 | 2016-08-04T11:49:12.000Z | 2016-08-04T11:49:12.000Z | characterCrowd.py | campbellwmorgan/charactercrowd | 968f53ea23c347d57e7e45d46206ab4dc8fb39ca | [
"Apache-2.0"
] | null | null | null | characterCrowd.py | campbellwmorgan/charactercrowd | 968f53ea23c347d57e7e45d46206ab4dc8fb39ca | [
"Apache-2.0"
] | null | null | null | """
Plugin for manually animating
large numbers of rigs given a small number of source rigs
See README for installation instructions and usage
"""
from pymel.api.plugins import Command
import maya.OpenMayaMPx as OpenMayaMPx
from characterCrowdSrc.characterCrowd import *
class characterCrowdGui(Command):
def doIt(self, args):
print("loading gui...")
gui()
class ccPreRenderFrame(Command):
def doIt(self, args):
preRender()
class ccPostRenderFrame(Command):
def doIt(self, args):
postRender()
class ccGenerate(Command):
def doIt(self, args):
generateStandin()
class ccDuplicate(Command):
def doIt(self, args):
duplicateStandin()
class ccSave(Command):
def doIt(self, args):
saveStandin()
class ccEdit(Command):
def doIt(self, args):
editStandin()
class ccCache(Command):
def doIt(self, args):
"""
Usage: ccCache # caches selected entire frame range
ccCache 2 5 # caches selected from frame 2 to 5
"""
if args.length() is 0:
return cacheStandin()
else:
startFrame = args.asInt(0)
endFrame = args.asInt(1)
cacheStandin(startFrame, endFrame)
class ccSelectAll(Command):
def doIt(self, args):
selectAllStandins()
## initialize the script plug-in
def initializePlugin(mobject):
mplugin = OpenMayaMPx.MFnPlugin( mobject, "CampbellMorgan", "0.01" )
characterCrowdGui.register()
ccPreRenderFrame.register()
ccPostRenderFrame.register()
ccGenerate.register()
ccDuplicate.register()
ccSave.register()
ccEdit.register()
ccCache.register()
ccSelectAll.register()
print("Loaded CharacterCrowd")
# uninitialize the script plug-in
def uninitializePlugin(mobject):
mplugin = OpenMayaMPx.MFnPlugin( mobject )
characterCrowdGui.deregister()
ccPreRenderFrame.deregister()
ccPostRenderFrame.deregister()
ccGenerate.deregister()
ccDuplicate.deregister()
ccSave.deregister()
ccEdit.deregister()
ccCache.deregister()
ccSelectAll.deregister()
print("Unloaded CharacterCrowd")
| 24.816092 | 72 | 0.678555 | 1,034 | 0.478925 | 0 | 0 | 0 | 0 | 0 | 0 | 429 | 0.198703 |
b3d5be07df5ced34dc59e990bef205aa91454a35 | 36 | py | Python | python/cendalytics/core/__init__.py | jiportilla/ontology | 8a66bb7f76f805c64fc76cfc40ab7dfbc1146f40 | [
"MIT"
] | null | null | null | python/cendalytics/core/__init__.py | jiportilla/ontology | 8a66bb7f76f805c64fc76cfc40ab7dfbc1146f40 | [
"MIT"
] | null | null | null | python/cendalytics/core/__init__.py | jiportilla/ontology | 8a66bb7f76f805c64fc76cfc40ab7dfbc1146f40 | [
"MIT"
] | null | null | null | from .cendant_api import CendantAPI
| 18 | 35 | 0.861111 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
b3daaedddba54c9f389ca1ec586ac8d5df49336a | 1,381 | py | Python | python/test/test_spreadsheet_api.py | dlens/dlxapi | 189a6519240ce625d7a9cdb89e305a335d2aa045 | [
"MIT"
] | null | null | null | python/test/test_spreadsheet_api.py | dlens/dlxapi | 189a6519240ce625d7a9cdb89e305a335d2aa045 | [
"MIT"
] | 1 | 2020-08-20T17:31:43.000Z | 2020-08-20T17:31:43.000Z | python/test/test_spreadsheet_api.py | dlens/dlxapi | 189a6519240ce625d7a9cdb89e305a335d2aa045 | [
"MIT"
] | null | null | null | # coding: utf-8
"""
Decision Lens API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import dlxapi
from dlxapi.api.spreadsheet_api import SpreadsheetApi # noqa: E501
from dlxapi.rest import ApiException
class TestSpreadsheetApi(unittest.TestCase):
"""SpreadsheetApi unit test stubs"""
def setUp(self):
self.api = dlxapi.api.spreadsheet_api.SpreadsheetApi() # noqa: E501
def tearDown(self):
pass
def test_create_spreadsheet(self):
"""Test case for create_spreadsheet
"""
pass
def test_create_spreadsheet_for_kloudless_file(self):
"""Test case for create_spreadsheet_for_kloudless_file
"""
pass
def test_delete_spreadsheet(self):
"""Test case for delete_spreadsheet
Delete spreadsheet and mappings # noqa: E501
"""
pass
def test_get_mappings_for_spreadsheet(self):
"""Test case for get_mappings_for_spreadsheet
"""
pass
def test_get_spreadsheet(self):
"""Test case for get_spreadsheet
"""
pass
if __name__ == '__main__':
unittest.main()
| 20.924242 | 119 | 0.666908 | 878 | 0.635771 | 0 | 0 | 0 | 0 | 0 | 0 | 660 | 0.477915 |
b3dab3fac30d61cfc2247c371cd1c7ec086bd037 | 8,485 | py | Python | demo/demo_window.py | aakhundov/tf-attend-infer-repeat | 77d4ac8773b389022a2c7fc650e7a22b998ba14d | [
"MIT"
] | 57 | 2017-07-27T14:52:30.000Z | 2021-06-04T04:58:16.000Z | demo/demo_window.py | aakhundov/tf-attend-infer-repeat | 77d4ac8773b389022a2c7fc650e7a22b998ba14d | [
"MIT"
] | 7 | 2017-07-27T14:53:38.000Z | 2019-12-26T15:20:16.000Z | demo/demo_window.py | aakhundov/tf-attend-infer-repeat | 77d4ac8773b389022a2c7fc650e7a22b998ba14d | [
"MIT"
] | 8 | 2017-11-09T03:13:50.000Z | 2019-12-13T23:24:41.000Z | import tkinter as tk
import tkinter.ttk as ttk
from .pixel_canvas import PixelCanvas
class DemoWindow(ttk.Frame):
def __init__(self, master, model_wrapper,
canvas_size=50, window_size=28,
refresh_period=50, test_image=None, **kw):
ttk.Frame.__init__(self, master=master, **kw)
self.master = master
self.model_wrapper = model_wrapper
self.canvas_size = canvas_size
self.window_size = window_size
self.refresh_period = refresh_period
self._create_interface()
if test_image is not None:
self.cnv_orig.set_image(test_image)
self.columnconfigure(0, weight=410, minsize=215)
self.columnconfigure(1, weight=410, minsize=210)
self.columnconfigure(2, weight=140, minsize=65)
self.rowconfigure(0, weight=0, minsize=50)
self.rowconfigure(1, weight=1, minsize=220)
self.rowconfigure(2, weight=0, minsize=0)
self.master.after(50, lambda: master.focus_force())
self.master.after(100, self._reconstruct_image)
def _create_interface(self):
self.frm_controls = ttk.Frame(self, padding=(10, 15, 10, 10))
self.frm_controls.grid(row=0, column=0, columnspan=3, sticky=(tk.N, tk.S, tk.W, tk.E))
self.lbl_draw_mode = ttk.Label(self.frm_controls, text="Drawing Mode:")
self.lbl_line_width = ttk.Label(self.frm_controls, text="Line Width:")
self.lbl_refresh_rate = ttk.Label(self.frm_controls, text="Refresh (ms):")
self.var_draw_mode = tk.IntVar(value=1)
self.rad_draw = ttk.Radiobutton(self.frm_controls, text="Draw", variable=self.var_draw_mode, value=1)
self.rad_erase = ttk.Radiobutton(self.frm_controls, text="Erase", variable=self.var_draw_mode, value=0)
self.btn_clear = ttk.Button(
self.frm_controls, text="Clear Image",
command=lambda: self.cnv_orig.clear_image()
)
self.var_width = tk.StringVar(self.frm_controls)
self.spn_width = tk.Spinbox(
self.frm_controls, values=(1, 2, 3, 4, 5), width=10,
state="readonly", textvariable=self.var_width
)
self.var_rate = tk.StringVar(self.frm_controls)
self.spn_rate = tk.Spinbox(
self.frm_controls, values=(10, 20, 50, 100, 200, 500, 1000), width=10,
state="readonly", textvariable=self.var_rate
)
self.var_bbox = tk.IntVar(value=1)
self.cbx_bbox = ttk.Checkbutton(self.frm_controls, text="Bounding Boxes", variable=self.var_bbox)
self.lbl_draw_mode.grid(row=0, column=0, columnspan=2, sticky=(tk.N, tk.W))
self.lbl_line_width.grid(row=0, column=3, sticky=(tk.N, tk.W))
self.lbl_refresh_rate.grid(row=0, column=4, sticky=(tk.N, tk.W))
self.rad_draw.grid(row=1, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
self.rad_erase.grid(row=1, column=1, sticky=(tk.N, tk.S, tk.W, tk.E), padx=(0, 20))
self.btn_clear.grid(row=1, column=2, sticky=(tk.N, tk.S, tk.W, tk.E), padx=(0, 20))
self.spn_width.grid(row=1, column=3, sticky=(tk.N, tk.S, tk.W, tk.E), padx=(0, 20))
self.spn_rate.grid(row=1, column=4, sticky=(tk.N, tk.S, tk.W, tk.E), padx=(0, 20))
self.cbx_bbox.grid(row=1, column=5, sticky=(tk.N, tk.S, tk.W, tk.E))
self.var_draw_mode.trace("w", lambda *_: self._set_draw_mode(self.var_draw_mode.get() == 1))
self.var_width.trace("w", lambda *_: self.cnv_orig.set_line_width(int(self.var_width.get())))
self.var_rate.trace("w", lambda *_: self._set_refresh_period(int(self.var_rate.get())))
self.var_bbox.trace("w", lambda *_: self._set_bbox_visibility(self.var_bbox.get() == 1))
self.frm_canvas_orig = ttk.Frame(self, padding=(10, 10, 5, 10))
self.frm_canvas_orig.grid(row=1, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
self.frm_canvas_orig.columnconfigure(0, weight=1, minsize=200)
self.frm_canvas_orig.rowconfigure(0, weight=0, minsize=20)
self.frm_canvas_orig.rowconfigure(1, weight=1, minsize=200)
self.lbl_orig = ttk.Label(self.frm_canvas_orig, text="Original Image (draw here):")
self.cnv_orig = PixelCanvas(
self.frm_canvas_orig, self.canvas_size, self.canvas_size, drawable=True,
highlightthickness=0, borderwidth=0, width=400, height=400
)
self.lbl_orig.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
self.cnv_orig.grid(row=1, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
self.frm_canvas_rec = ttk.Frame(self, padding=(5, 10, 5, 10))
self.frm_canvas_rec.grid(row=1, column=1, sticky=(tk.N, tk.S, tk.W, tk.E))
self.frm_canvas_rec.columnconfigure(0, weight=1, minsize=200)
self.frm_canvas_rec.rowconfigure(0, weight=0, minsize=20)
self.frm_canvas_rec.rowconfigure(1, weight=1, minsize=200)
self.lbl_rec = ttk.Label(self.frm_canvas_rec, text="Reconstructed Image:")
self.cnv_rec = PixelCanvas(
self.frm_canvas_rec, self.canvas_size, self.canvas_size, drawable=False,
highlightthickness=0, borderwidth=0, width=400, height=400
)
self.lbl_rec.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
self.cnv_rec.grid(row=1, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
self.frm_windows = ttk.Frame(self, padding=(0, 0, 0, 0))
self.frm_windows.grid(row=1, column=2, sticky=(tk.N, tk.S, tk.W, tk.E))
self.frm_windows.columnconfigure(0, weight=1)
self.frm_canvas_win, self.lbl_win, self.cnv_win = [], [], []
for i in range(3):
self.frm_windows.rowconfigure(i, weight=1)
frm_canvas_win = ttk.Frame(
self.frm_windows,
padding=(5, 10 if i == 0 else 0, 10, 10 if i == 2 else 0)
)
frm_canvas_win.grid(row=i, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
frm_canvas_win.columnconfigure(0, weight=1, minsize=50)
frm_canvas_win.rowconfigure(0, weight=0, minsize=20)
frm_canvas_win.rowconfigure(1, weight=1, minsize=50)
lbl_win = ttk.Label(
frm_canvas_win, text="VAE Rec. #{0}:".format(i+1)
)
cnv_win = PixelCanvas(
frm_canvas_win, self.window_size, self.window_size, drawable=False,
highlightthickness=0, borderwidth=0, width=120, height=120
)
lbl_win.grid(row=0, column=0, sticky=(tk.S, tk.W))
cnv_win.grid(row=1, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
self.frm_canvas_win.append(frm_canvas_win)
self.lbl_win.append(lbl_win)
self.cnv_win.append(cnv_win)
self.lbl_status = ttk.Label(self, borderwidth=1, relief="sunken", padding=(5, 2))
self.lbl_status.grid(row=2, column=0, columnspan=3, sticky=(tk.N, tk.S, tk.W, tk.E))
self.cnv_orig.bind("<Button-2>", lambda *_: self.cnv_orig.clear_image())
self.cnv_orig.bind("<Button-3>", lambda *_: self.cnv_orig.clear_image())
self.var_draw_mode.set(1)
self.var_width.set("3")
self.var_rate.set("50")
self.var_bbox.set(1)
def _reconstruct_image(self):
dig, pos, rec, win, lat, loss = self.model_wrapper.infer(
[self.cnv_orig.get_image()]
)
self.cnv_rec.set_image(rec[0])
self.cnv_rec.set_bbox_positions(pos[0])
self.cnv_orig.set_bbox_positions(pos[0])
for i in range(len(self.cnv_win)):
if i < len(win[0]):
self.cnv_win[i].set_image(win[0][i])
self.cnv_win[i].set_bbox_positions(
[[0.0, -2.0, -2.0]] * i + [[0.99, 0.0, 0.0]]
)
else:
self.cnv_win[i].clear_image()
self.cnv_win[i].set_bbox_positions([])
self.lbl_status.configure(
text="Reconstruction loss (negative log-likelihood): {0:.3f}".format(
abs(loss[0])
)
)
self.master.after(self.refresh_period, self._reconstruct_image)
def _set_refresh_period(self, value):
self.refresh_period = value
def _set_bbox_visibility(self, visible):
self.cnv_orig.set_bbox_visibility(visible)
self.cnv_rec.set_bbox_visibility(visible)
def _set_draw_mode(self, draw):
self.cnv_orig.set_erasing_mode(not draw)
self.cnv_orig.config(cursor=("cross" if draw else "icon"))
| 45.61828 | 111 | 0.621921 | 8,396 | 0.989511 | 0 | 0 | 0 | 0 | 0 | 0 | 292 | 0.034414 |
b3db0f61a48ed17e172300c3cb8606a8b731cdc4 | 7,477 | py | Python | app/views.py | soje402/imageboard | 45db024dae3fc9b2ae3e4531a4c1b59a36629692 | [
"MIT"
] | null | null | null | app/views.py | soje402/imageboard | 45db024dae3fc9b2ae3e4531a4c1b59a36629692 | [
"MIT"
] | null | null | null | app/views.py | soje402/imageboard | 45db024dae3fc9b2ae3e4531a4c1b59a36629692 | [
"MIT"
] | null | null | null | # coding=utf-8
from flask import Flask, url_for, render_template, request, redirect, jsonify, session, send_file
import models
import json
import datetime
import time
import md5
from werkzeug import secure_filename
app = Flask(__name__)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg', 'webm', 'mp4', 'avi', 'mov', 'mpeg']
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.template_filter('dt')
def datetimee(date):
return datetime.datetime.utcfromtimestamp(float(date)).strftime("""%d-%m-%Y %H:%M:%S""")
@app.template_filter('log')
def log(tolog):
print(tolog)
@app.route('/test')
def test():
return render_template('test.html', date = int(time.time()))
#@app.route('/<id>')
#def hello_world(id=None):
# if request.method == 'GET':
# pass
# elif resquest.method == 'POST':
# pass
# user = models.User.get_user('toot')
# posts = models.Post.get_posts(user['username'])
# for post in posts:
# commentaires = models.Commentaire.get_commentaires(post['id'])
# post['commentaires'] = commentaires
# post['nb_com'] = len(commentaires)
# return render_template('index.html', posts = posts)
#mettre un champ invisible dans les form pour la redirection
#l'url de la form est /login mais on sait ou on doit rediriger si le login est bon
#l'url login doit être accessible en GET pour les messages d'erreurs (trop compliqués à intégrer dans le header)
#!!!!!!!!!!!!!!!!!!!!!
def do_login(nickname, clear_password, redirect_url):
connection = False
user = models.user.get_by_name(nickname)
if user:
hashed_pass = md5.new(clear_password).hexdigest()
if hashed_pass == user['password']:
connection = True
if connection :
session.permanent = True
session['nickname'] = nickname
session['password'] = clear_password
else:
session.clear()
return redirect(redirect_url)
@app.route('/login', methods=['POST'])
def login():
return do_login(request.form.get('nickname'), request.form.get('password'), request.form.get('redirect'))
@app.route('/register', methods=['GET', 'POST'])
def register():
print(request.form)
if(request.method == 'POST'):
champs = [
'nickname',
'password',
'password_confirm'
]
result = validate(request.form, champs)
print result
if result['valid']:
#résultat valide
if not models.user.exist(request.form.get('nickname')):
#le nickname n'existe pas déjà
models.user.create(request.form.get('nickname'), md5.new(request.form.get('password')).hexdigest())
session.permanent = True
session['nickname'] = request.form.get('nickname')
session['password'] = request.form.get('password')
print('session ajoutée')
return redirect(request.form.get('redirect'))
else:
result['errors']['nickname'] = 'Le nickname existe déjà !'.decode('utf-8')
print(result['errors'])
return render_template('register.html', redirect=request.form['redirect'], form=result['form'], errors=result['errors'])
return render_template('register.html')
def validate(form, champs):
result = {'valid': True, 'form': form, 'errors': {}}
for champ in champs:
result['valid'] = result['valid'] and champ_requis(form, champ, errors=result['errors'])
#if(champ == 'nickname'):
# result['form'][champ] = champ
#else:
# result['form'][champ] = ''
return result
def champ_requis(form, champ, errors):
if form.get(champ, '') == '':
errors[champ] = 'le champ {} est requis'.format(champ)
return False
else:
return True
@app.route('/threads/<thread_id>', methods=['GET'])
def thread(thread_id):
print('ok')
return render_template('thread.html', nav = models.board.get_nav(None, thread_id), thread=models.thread.get_full(thread_id))
@app.route('/logout', methods=['POST'])
def logout():
session.clear()
return redirect(request.form['redirect'])
@app.route('/post/<what>/<id>', methods=['POST'])
def post(what, id):
if(session):
user = models.user.get_by_name(session['nickname'])
if(user):
if not(models.user.check_connect(session['nickname'], md5.new(session['password']).hexdigest())):
session.clear()
else:
print(request.form)
#uploaded_files = request.files.getlist("file[]")
#next_post = models.post.get_max
#for file, index in enumerate(request.files.getlist('file')):
# if(file.filename != ''):
# filename = secure_filename(file.filename)
timestamp = int(time.time())
if(what == 'thread'):
#ici vérifier les input
models.thread.create(
id,
request.form['title'],
request.form['content'],
user['id'],
timestamp)
elif(what == 'reply'):
models.post.create(
id,
request.form['content'],
user['id'],
timestamp)
else:
#l'utilisateur n'existe plus
session.clear()
return redirect(request.form['redirect'])
@app.route('/boards/<boardname>', methods=['GET'])
def navboard(boardname):
if(session):
print('session ok')
if not(models.user.check_connect(session['nickname'], md5.new(session['password']).hexdigest())):
session.clear()
else:
print('no session')
return render_template(
'board.html',
nav = models.board.get_nav(boardname, None),
threads = models.thread.get_threads_review(boardname, 20, 3))
@app.route('/')
def root():
return redirect('/boards/{}'.format(models.board.get_random_board()))
#@app.route('/create_post', methods=['GET', 'POST'])
#def create_post():
# champs = [
# 'titre',
# 'contenu'
# ]
#
# if request.method == 'GET':
# return render_template('post.html', champs=champs, form={}, errors={})
# else:
# form = request.form
# result = validate(form, champs)
#
# if result['valid']:
# user = models.User.get_user('toot')
# models.Post.insert('toot', result['form']['titre'], result['form']['contenu'])
# return redirect('/')
#
# else:
# return render_template('post.html',
# champs=champs,
# form=result['form'],
# errors=result['errors'])
#
#
#def validate(form, champs):
# result = {'valid': True, 'form': form, 'errors': {}}
# for champ in champs:
# result['valid'] = result['valid'] and champ_requis(form, champ, errors=result['errors'])
#
# return result
#
#def champ_requis(form, champ, errors):
# if form.get(champ, None) == '':
# errors[champ] = 'le champ {} est requis'.format(champ)
# return False
# else:
# return True
| 35.103286 | 128 | 0.570817 | 0 | 0 | 0 | 0 | 3,985 | 0.532185 | 0 | 0 | 3,221 | 0.430155 |
b3ddd4bffc1ad8ddae78a2e0c9a8923f4b526a4b | 3,696 | py | Python | lib/Site.py | EthanZeigler/pastebin_scraper | 0c0ca01a6f37fc9f153327a236de74215dee584c | [
"MIT"
] | null | null | null | lib/Site.py | EthanZeigler/pastebin_scraper | 0c0ca01a6f37fc9f153327a236de74215dee584c | [
"MIT"
] | null | null | null | lib/Site.py | EthanZeigler/pastebin_scraper | 0c0ca01a6f37fc9f153327a236de74215dee584c | [
"MIT"
] | null | null | null | from queue import Queue
import time
from settings import USE_DB, DB_DB, DB_DUMP_TABLE, DB_ACCT_TABLE, REQUEST_SPACING
import logging
from . import helper
import sqlite3
import threading
class Site(object):
'''
Site - parent class used for a generic
'Queue' structure with a few helper methods
and features. Implements the following methods:
empty() - Is the Queue empty
get(): Get the next item in the queue
put(item): Puts an item in the queue
tail(): Shows the last item in the queue
peek(): Shows the next item in the queue
length(): Returns the length of the queue
clear(): Clears the queue
list(): Lists the contents of the Queue
download(url): Returns the content from the URL
'''
# Note from Jordan (original author)
# I would have used the built-in queue, but there is no support for a peek() method
# that I could find... So, I decided to implement my own queue with a few
# changes
def __init__(self, queue=None):
if queue is None:
self.queue = []
def empty(self):
return len(self.queue) == 0
def get(self):
if not self.empty():
result = self.queue[0]
del self.queue[0]
else:
result = None
return result
def put(self, item):
self.queue.append(item)
def peek(self):
return self.queue[0] if not self.empty() else None
def tail(self):
return self.queue[-1] if not self.empty() else None
def length(self):
return len(self.queue)
def clear(self):
self.queue = []
def list(self):
print('\n'.join(url for url in self.queue))
def monitor(self, t_lock, db_lock, db_client):
self.update()
while(1):
while not self.empty():
paste = self.get()
self.ref_id = paste.id
logging.info('[*] Checking + Spacer ' + paste.url)
paste.text = self.get_paste_text(paste)
time.sleep(REQUEST_SPACING)
interesting = helper.run_match(paste)
if interesting:
logging.info('[*] FOUND ' + (paste.type).upper() + ' ' + paste.url)
if USE_DB:
db_lock.acquire()
try:
cursor = db_client.cursor()
cursor.execute('''INSERT INTO %s (
text,
emails,
hashes,
num_emails,
num_hashes,
type,
db_keywords,
url,
author
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?
)''' % (DB_DUMP_TABLE), (paste.text, str(paste.emails), str(paste.hashes), paste.num_emails, paste.num_hashes, paste.type, str(paste.db_keywords), str("https://pastebin.com/"+paste.id), paste.author,))
except:
logging.info('[*] ERROR: Failed to save paste. Manual review: ' + paste.url)
db_lock.release()
self.update()
while self.empty():
logging.debug('[*] No results... sleeping')
time.sleep(self.sleep)
self.update()
| 35.883495 | 230 | 0.477273 | 3,493 | 0.945076 | 0 | 0 | 0 | 0 | 0 | 0 | 1,496 | 0.404762 |
b3de01a8894dc74cb15d7daba9f4b92d20584506 | 1,090 | py | Python | Convolution Neural Network/main.py | dhavalsharma97/ExpressionIdentifier | b69060cb115d99266a4d6b663d269771cbe1a0b0 | [
"MIT"
] | null | null | null | Convolution Neural Network/main.py | dhavalsharma97/ExpressionIdentifier | b69060cb115d99266a4d6b663d269771cbe1a0b0 | [
"MIT"
] | null | null | null | Convolution Neural Network/main.py | dhavalsharma97/ExpressionIdentifier | b69060cb115d99266a4d6b663d269771cbe1a0b0 | [
"MIT"
] | null | null | null | # Convolution Neural Networks
# importing the required libraries
from demo import demo
from model import train_model, valid_model
import tensorflow as tf
flags = tf.compat.v1.flags
flags.DEFINE_string('MODE', 'demo',
'Set program to run in different modes, including train, valid and demo.')
flags.DEFINE_string('checkpoint_dir', './models',
'Path to the model file.')
flags.DEFINE_string('train_data', '../data/fer2013/fer2013.csv',
'Path to the training data.')
flags.DEFINE_string('valid_data', '../data/fer2013/',
'Path to the training data.')
flags.DEFINE_boolean('show_box', True,
'If true, the results will show detection box')
FLAGS = flags.FLAGS
def main():
assert FLAGS.MODE in ('train', 'valid', 'demo')
if FLAGS.MODE == 'demo':
demo(FLAGS.checkpoint_dir, FLAGS.show_box)
elif FLAGS.MODE == 'train':
train_model(FLAGS.train_data)
elif FLAGS.MODE == 'valid':
valid_model(FLAGS.checkpoint_dir, FLAGS.valid_data)
if __name__ == '__main__':
main() | 31.142857 | 94 | 0.658716 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 432 | 0.39633 |
b3df745ca42527733326bd472f3dcaf4891e8d24 | 2,789 | py | Python | ETLPipeline (1).py | mudigosa/Disaster-Pipeline | 3a4a8cb78202def522f131d15e5f3938c15f1be5 | [
"CC-BY-4.0"
] | null | null | null | ETLPipeline (1).py | mudigosa/Disaster-Pipeline | 3a4a8cb78202def522f131d15e5f3938c15f1be5 | [
"CC-BY-4.0"
] | null | null | null | ETLPipeline (1).py | mudigosa/Disaster-Pipeline | 3a4a8cb78202def522f131d15e5f3938c15f1be5 | [
"CC-BY-4.0"
] | null | null | null | import sys
import pandas as pd
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
'''
input:
messages_filepath: The path of messages dataset.
categories_filepath: The path of categories dataset.
output:
df: The merged dataset
'''
disastermessages = pd.read_csv('disaster_messages.csv')
disastermessages.head()
# load categories dataset
disastercategories = pd.read_csv('disaster_categories.csv')
disastercategories.head()
df = pd.merge(disastermessages, disastercategories, left_on='id', right_on='id', how='outer')
return df
def clean_data(df):
'''
input:
df: The merged dataset in previous step.
output:
df: Dataset after cleaning.
'''
disastercategories = df.categories.str.split(';', expand = True)
# select the first row of the categories dataframe
row = disastercategories.iloc[0,:]
# use this row to extract a list of new column names for categories.
# one way is to apply a lambda function that takes everything
# up to the second to last character of each string with slicing
disastercategory_colnames = row.apply(lambda x:x[:-2])
print(disastercategory_colnames)
disastercategories.columns = category_colnames
for column in disastercategories:
# set each value to be the last character of the string
disastercategories[column] = disastercategories[column].str[-1]
# convert column from string to numeric
disastercategories[column] = disastercategories[column].astype(np.int)
disastercategories.head()
df.drop('categories', axis = 1, inplace = True)
df = pd.concat([df, categories], axis = 1)
# drop the original categories column from `df`
df = df.drop('categories',axis=1)
df.head()
# check number of duplicates
print('Number of duplicated rows: {} out of {} samples'.format(df.duplicated().sum(),df.shape[0]))
df.drop_duplicates(subset = 'id', inplace = True)
return df
def save_data(df):
engine = create_engine('sqlite:///disastermessages.db')
df.to_sql('df', engine, index=False)
def main():
df = load_data()
print('Cleaning data...')
df = clean_data(df)
save_data(df)
print('Cleaned data saved to database!')
else:
print('Please provide the filepaths of the messages and categories '\
'datasets as the first and second argument respectively, as '\
'well as the filepath of the database to save the cleaned data '\
'to as the third argument. \n\nExample: python process_data.py '\
'disaster_messages.csv disaster_categories.csv '\
'DisasterResponse.db')
if __name__ == '__main__':
main()
| 35.303797 | 102 | 0.674435 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,299 | 0.465758 |
b3e2ec988106df0c07fe3fcce90989007d7b9618 | 365 | py | Python | backend/presentation/admin.py | Weida-W/CMPUT404-project-socialdistribution | 41d8a7f7f013723d2a3878156953fbc11c2e6156 | [
"W3C-20150513"
] | null | null | null | backend/presentation/admin.py | Weida-W/CMPUT404-project-socialdistribution | 41d8a7f7f013723d2a3878156953fbc11c2e6156 | [
"W3C-20150513"
] | 75 | 2021-01-13T23:48:48.000Z | 2021-04-16T19:39:38.000Z | backend/presentation/admin.py | Weida-W/CMPUT404-project-socialdistribution | 41d8a7f7f013723d2a3878156953fbc11c2e6156 | [
"W3C-20150513"
] | 12 | 2021-01-13T23:22:35.000Z | 2021-04-28T08:13:38.000Z | from django.contrib import admin
# Register your models here.
from .models import *
admin.site.register(Author)
admin.site.register(Follower)
admin.site.register(Post)
admin.site.register(Comment)
admin.site.register(Request)
admin.site.register(Inbox)
admin.site.register(Likes)
admin.site.register(Liked)
admin.site.register(Usermod)
admin.site.register(Friend) | 24.333333 | 32 | 0.810959 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 28 | 0.076712 |
b3e3074f419ca7d66a4319f36dc79a3e5933c6a7 | 3,891 | py | Python | guessenv/__main__.py | EasyPost/guessenv | a5b65faa3b0776c764d21b1a10b891dbdd0c6fdf | [
"0BSD"
] | 3 | 2019-02-09T04:02:35.000Z | 2021-12-08T18:28:08.000Z | guessenv/__main__.py | EasyPost/guessenv | a5b65faa3b0776c764d21b1a10b891dbdd0c6fdf | [
"0BSD"
] | null | null | null | guessenv/__main__.py | EasyPost/guessenv | a5b65faa3b0776c764d21b1a10b891dbdd0c6fdf | [
"0BSD"
] | null | null | null | import argparse
import sys
import io
import os
import os.path
import re
from itertools import repeat
from . import guesser
if sys.version_info < (3, 0):
open_function = io.open
else:
open_function = open
class _Exclude(object):
def __init__(self, regex):
self.raw = regex
self.path = re.compile(regex)
def match(self, path):
path = path.lstrip('./')
return self.path.search(path)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('-q', '--quiet', action='store_true')
parser.add_argument('-O', '--with-optional', action='store_true', help='Include optional environment variables')
parser.add_argument('-A', '--assert-present', action='store_true',
help='Exit non-zero if any required environment variables are missing')
parser.add_argument('-x', '--exclude', action='append', default=[], type=_Exclude,
help='Exclude files matching the given regex. May be repeated')
parser.add_argument('-X', '--standard-exclude', action='store_true', help='Add a standard set of excludes')
parser.add_argument('files', nargs='+')
args = parser.parse_args()
if args.verbose and args.quiet:
parser.error('cannot pass both --verbose and --quiet')
if args.standard_exclude:
args.exclude.append(_Exclude('^venv/.*'))
args.exclude.append(_Exclude('^.tox/.*'))
args.exclude.append(_Exclude('^test/.*'))
args.exclude.append(_Exclude('^tests/.*'))
filenames = []
envvars = []
# Handle argv.
for file_or_dir_name in args.files:
if os.path.isdir(file_or_dir_name):
for root, _, files in os.walk(file_or_dir_name):
for f in files:
if f.endswith('.py'):
full_path = os.path.join(root, f)
if any(exclude.match(full_path) for exclude in args.exclude):
continue
filenames.append(os.path.join(root, f))
elif os.path.exists(file_or_dir_name):
if not any(exclude.match(file_or_dir_name) for exclude in args.exclude):
filenames.append(file_or_dir_name)
else:
pass
status = 0
for filename in filenames:
v = guesser.EnvVisitor()
with open_function(filename, 'r', encoding='utf-8') as f:
try:
v.parse_and_visit(f.read(), filename)
if args.with_optional:
envvars.extend(list(zip(
repeat(filename),
repeat('optional'),
sorted(v.optional_environment_variables)
)))
envvars.extend(list(zip(
repeat(filename),
repeat('required'),
sorted(v.required_environment_variables)
)))
except SyntaxError as e:
print('{filename}:{lineno} - syntax error!'.format(
filename=filename,
lineno=e.lineno
))
status = 1
if args.assert_present:
required_envvars = set(v for _, k, v in envvars if k == 'required')
for envvar in required_envvars:
if envvar not in os.environ:
print('MISSING: {0}'.format(envvar))
status = 1
if args.verbose:
for filename, kind, variable_name in envvars:
print('{filename} {kind} {variable_name}'.format(filename=filename, kind=kind, variable_name=variable_name))
elif not args.quiet:
envvars = set(v for _, _, v in envvars)
print('\n'.join(sorted(str(v) for v in envvars)))
return status
if __name__ == '__main__':
sys.exit(main())
| 34.741071 | 120 | 0.570547 | 216 | 0.055513 | 0 | 0 | 0 | 0 | 0 | 0 | 626 | 0.160884 |
b3e388297ce0c73ba9eddb04d2d2199bfb28b6a2 | 11,450 | py | Python | main_test.py | OniriCorpe/Motion | ee617b0f183c177e63b52fb91f52ede6eb1b1f83 | [
"WTFPL"
] | null | null | null | main_test.py | OniriCorpe/Motion | ee617b0f183c177e63b52fb91f52ede6eb1b1f83 | [
"WTFPL"
] | null | null | null | main_test.py | OniriCorpe/Motion | ee617b0f183c177e63b52fb91f52ede6eb1b1f83 | [
"WTFPL"
] | null | null | null | #!/usr/bin/env python
"""
The test file to use with pytest.
'(motion-venv) $ python -m pytest main_test.py'
"""
import main
def test_calculate_date_delta():
"""
Tests that the function calculate_date_delta(date_start, date_now)
calculates correctly the number of days between two dates.
"""
assert main.calculate_date_delta("2042-12-13", "2042-12-10") == 3
assert main.calculate_date_delta("2014-02-13", "2014-02-14") == 1
assert main.calculate_date_delta("1891-03-11", "1891-03-18") == 7
assert main.calculate_date_delta("1871-03-18", "1995-02-14") == 45258
def test_agenda_format_day():
"""
Tests that the function agenda_format_day(
number_of_days_before,
date_start,
cfg_today,
cfg_tomorrow,
cfg_in_days,)
formats properly a the string.
"""
assert (
main.agenda_format_day(
0,
"2022-13-12",
"ajd",
"dem",
" j",
)
== "ajd"
)
assert (
main.agenda_format_day(
0,
"2021-05-10T13:12:00",
"ajd",
"dem",
" j",
)
== "13:12"
)
assert (
main.agenda_format_day(
1,
"2022-13-12",
"ajd",
"dem",
" j",
)
== "dem"
)
assert (
main.agenda_format_day(
2,
"2022-13-12",
"ajd",
"dem",
" j",
)
== "2 j"
)
assert (
main.agenda_format_day(
3,
"2022-13-12",
"ajd",
"dem",
" j",
)
== "3 j"
)
def test_agenda_results():
"""
Tests that the function agenda_results(data) formats correctly under all conditions.
"""
assert not main.agenda_results(
{"results": []},
"2022-01-15",
"Date",
"Nom",
)
assert (
main.agenda_results(
{
"results": [
{
"properties": {
"Date": {
"date": {
"start": "2022-12-13",
"end": None,
},
},
"Nom": {
"title": [
{
"plain_text": "test 1",
}
],
},
},
}
],
},
"2022-12-13",
"Date",
"Nom",
)
== [("ajd", "test 1")],
)
assert (
main.agenda_results(
{
"results": [
{
"properties": {
"Date": {
"date": {
"start": "2022-12-13T13:12:00.000+01:00",
"end": None,
},
},
"Nom": {
"title": [
{
"plain_text": "test heure",
}
],
},
},
}
],
},
"2022-12-13",
"Date",
"Nom",
)
== [("13:12", "test heure")],
)
assert main.agenda_results(
{
"results": [
{
"properties": {
"Date": {
"date": {
"start": "2022-12-08",
"end": None,
},
},
"Nom": {
"title": [
{
"plain_text": "test 1",
}
],
},
},
},
{
"properties": {
"Date": {
"date": {
"start": "2022-12-08T13:12:00.000+01:00",
"end": None,
},
},
"Nom": {
"title": [
{
"plain_text": "test heure 2",
}
],
},
},
},
{
"properties": {
"Date": {
"date": {
"start": "2022-12-09T13:12:00.000+01:00",
"end": None,
},
},
"Nom": {
"title": [
{
"plain_text": "test 3",
}
],
},
},
},
{
"properties": {
"Date": {
"date": {
"start": "2022-12-11",
"end": "2022-12-12",
},
},
"Nom": {
"title": [
{
"plain_text": "test 4",
}
],
},
},
},
{
"properties": {
"Date": {
"date": {
"start": "2022-12-12T13:00:00.000+01:00",
"end": "2022-12-14T12:00:00.000+01:00",
},
},
"Nom": {
"title": [
{
"plain_text": "test 5",
}
],
},
},
},
],
},
"2022-12-08",
"Date",
"Nom",
) == [
("ajd", "test 1"),
("13:12", "test heure 2"),
("dem", "test 3"),
("3 j", "test 4"),
("4 j", "test 5"),
]
def test_meds_results():
"""
Tests that the function meds_results(data) formats correctly under all conditions.
"""
assert not main.meds_results({"results": []})
assert main.meds_results(
{
"results": [
{
"properties": {
"NbRefill": {
"formula": {"number": 1},
},
"Nom": {
"title": [
{
"plain_text": "test 1",
}
],
},
},
}
],
}
) == ["test 1 : ≥1"]
assert main.meds_results(
{
"results": [
{
"properties": {
"NbRefill": {
"formula": {"number": 1},
},
"Nom": {
"title": [
{
"plain_text": "test 1",
}
],
},
},
},
{
"properties": {
"NbRefill": {
"formula": {"number": 2},
},
"Nom": {
"title": [
{
"plain_text": "test 2",
}
],
},
},
},
]
}
) == ["test 1 : ≥1", "test 2 : ≥2"]
def test_int_to_tuple():
"""
Tests that the function int_to_tuple() returns tuples.
"""
assert main.int_to_tuple(1) == (1,)
assert main.int_to_tuple((2,)) == (2,)
assert main.int_to_tuple((3, )) == (3,) # fmt: skip
assert main.int_to_tuple((4, 5)) == (4, 5)
assert main.int_to_tuple((6,7)) == (6, 7) # fmt: skip
def test_generate_custom_text():
"""
Tests that the function generate_custom_text() returns good data.
"""
assert main.generate_custom_text([], 2, 14) == ""
assert main.generate_custom_text([["test not today", 2]], 1, 14) == ""
assert main.generate_custom_text([["test not today tuple", (2, 3)]], 1, 14) == ""
assert main.generate_custom_text([["test today", 2]], 2, 14) == "test today"
assert (
main.generate_custom_text([["test today tuple", (0, 2)]], 2, 14)
== "test today tuple"
)
assert main.generate_custom_text([["odd", "test odd", 2]], 2, 14) == "test odd"
assert (
main.generate_custom_text([["odd", "test odd tuple", (2, 5)]], 2, 14)
== "test odd tuple"
)
assert main.generate_custom_text([["even", "test even", 2]], 2, 15) == "test even"
assert (
main.generate_custom_text([["even", "test even tuple", (2, 6)]], 2, 15)
== "test even tuple"
)
assert main.generate_custom_text([["even", "test not even", 2]], 2, 14) == ""
assert (
main.generate_custom_text([["even", "test not even tuple", (2, 6)]], 2, 14)
== ""
)
assert main.generate_custom_text([["odd", "test not odd", 2]], 2, 15) == ""
assert (
main.generate_custom_text([["odd", "test not odd tuple", (2, 6)]], 2, 15) == ""
)
assert (
main.generate_custom_text(
[["test multiple lists not today", 2], ["test multiple lists", 3]], 1, 14
)
== ""
)
assert (
main.generate_custom_text(
[
["test multiple lists not today tuple", (2, 4)],
["test multiple lists 2", 3],
],
1,
14,
)
== ""
)
assert (
main.generate_custom_text(
[["test multiple lists 1", 2], ["test multiple lists 2", 1]], 1, 14
)
== "test multiple lists 2"
)
assert (
main.generate_custom_text(
[["test multiple lists 1 tuple", (2, 5)], ["test multiple lists 2", 1]],
1,
14,
)
== "test multiple lists 2"
)
| 29.060914 | 88 | 0.291179 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,896 | 0.252793 |
b3e6496b03fe0d2f66798fb80e121601679ea548 | 5,200 | py | Python | deps/libffi/generate-osx-source-and-headers.py | liuqsqq/node-ffi | 169773db0d56c4c99225b307b3dc86a46f3af34d | [
"MIT"
] | 3,373 | 2015-01-03T21:04:40.000Z | 2022-03-30T21:11:38.000Z | deps/libffi/generate-osx-source-and-headers.py | liuqsqq/node-ffi | 169773db0d56c4c99225b307b3dc86a46f3af34d | [
"MIT"
] | 457 | 2015-01-02T10:20:25.000Z | 2022-03-09T10:39:50.000Z | deps/libffi/generate-osx-source-and-headers.py | liuqsqq/node-ffi | 169773db0d56c4c99225b307b3dc86a46f3af34d | [
"MIT"
] | 418 | 2015-01-21T12:05:23.000Z | 2022-03-23T13:44:12.000Z | #!/usr/bin/env python
import subprocess
import re
import os
import errno
import collections
import sys
class Platform(object):
pass
sdk_re = re.compile(r'.*-sdk ([a-zA-Z0-9.]*)')
def sdkinfo(sdkname):
ret = {}
for line in subprocess.Popen(['xcodebuild', '-sdk', sdkname, '-version'], stdout=subprocess.PIPE).stdout:
kv = line.strip().split(': ', 1)
if len(kv) == 2:
k,v = kv
ret[k] = v
return ret
desktop_sdk_info = sdkinfo('macosx')
def latest_sdks():
latest_desktop = None
for line in subprocess.Popen(['xcodebuild', '-showsdks'], stdout=subprocess.PIPE).stdout:
match = sdk_re.match(line)
if match:
if 'OS X' in line:
latest_desktop = match.group(1)
return latest_desktop
desktop_sdk = latest_sdks()
class desktop_platform_32(Platform):
sdk='macosx'
arch = 'i386'
name = 'mac32'
triple = 'i386-apple-darwin10'
sdkroot = desktop_sdk_info['Path']
prefix = "#if defined(__i386__) && !defined(__x86_64__)\n\n"
suffix = "\n\n#endif"
class desktop_platform_64(Platform):
sdk='macosx'
arch = 'x86_64'
name = 'mac'
triple = 'x86_64-apple-darwin10'
sdkroot = desktop_sdk_info['Path']
prefix = "#if !defined(__i386__) && defined(__x86_64__)\n\n"
suffix = "\n\n#endif"
def move_file(src_dir, dst_dir, filename, file_suffix=None, prefix='', suffix=''):
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
out_filename = filename
if file_suffix:
split_name = os.path.splitext(filename)
out_filename = "%s_%s%s" % (split_name[0], file_suffix, split_name[1])
with open(os.path.join(src_dir, filename)) as in_file:
with open(os.path.join(dst_dir, out_filename), 'w') as out_file:
if prefix:
out_file.write(prefix)
out_file.write(in_file.read())
if suffix:
out_file.write(suffix)
headers_seen = collections.defaultdict(set)
def move_source_tree(src_dir, dest_dir, dest_include_dir, arch=None, prefix=None, suffix=None):
for root, dirs, files in os.walk(src_dir, followlinks=True):
relroot = os.path.relpath(root,src_dir)
def move_dir(arch, prefix='', suffix='', files=[]):
for file in files:
file_suffix = None
if file.endswith('.h'):
if dest_include_dir:
file_suffix = arch
if arch:
headers_seen[file].add(arch)
move_file(root, dest_include_dir, file, arch, prefix=prefix, suffix=suffix)
elif dest_dir:
outroot = os.path.join(dest_dir, relroot)
move_file(root, outroot, file, prefix=prefix, suffix=suffix)
if relroot == '.':
move_dir(arch=arch,
files=files,
prefix=prefix,
suffix=suffix)
elif relroot == 'x86':
move_dir(arch='i386',
prefix="#if defined(__i386__) && !defined(__x86_64__)\n\n",
suffix="\n\n#endif",
files=files)
move_dir(arch='x86_64',
prefix="#if !defined(__i386__) && defined(__x86_64__)\n\n",
suffix="\n\n#endif",
files=files)
def build_target(platform):
def xcrun_cmd(cmd):
return subprocess.check_output(['xcrun', '-sdk', platform.sdkroot, '-find', cmd]).strip()
build_dir = 'build_' + platform.name
if not os.path.exists(build_dir):
os.makedirs(build_dir)
env = dict(CC=xcrun_cmd('clang'),
LD=xcrun_cmd('ld'),
CFLAGS='-arch %s -isysroot %s -mmacosx-version-min=10.6' % (platform.arch, platform.sdkroot))
working_dir=os.getcwd()
try:
os.chdir(build_dir)
subprocess.check_call(['../configure', '-host', platform.triple], env=env)
move_source_tree('.', None, '../osx/include',
arch=platform.arch,
prefix=platform.prefix,
suffix=platform.suffix)
move_source_tree('./include', None, '../osx/include',
arch=platform.arch,
prefix=platform.prefix,
suffix=platform.suffix)
finally:
os.chdir(working_dir)
for header_name, archs in headers_seen.iteritems():
basename, suffix = os.path.splitext(header_name)
def main():
move_source_tree('src', 'osx/src', 'osx/include')
move_source_tree('include', None, 'osx/include')
build_target(desktop_platform_32)
build_target(desktop_platform_64)
for header_name, archs in headers_seen.iteritems():
basename, suffix = os.path.splitext(header_name)
with open(os.path.join('osx/include', header_name), 'w') as header:
for arch in archs:
header.write('#include <%s_%s%s>\n' % (basename, arch, suffix))
if __name__ == '__main__':
main()
| 33.766234 | 112 | 0.564808 | 554 | 0.106538 | 0 | 0 | 0 | 0 | 0 | 0 | 763 | 0.146731 |
b3e734c6ffea6e6eebb61e519518c93ae03d2616 | 1,504 | py | Python | fst_lookup/fallback_data.py | eddieantonio/fst-lookup | 383173e906c25070fb71044318a6fe9e62ca9c13 | [
"MIT"
] | 5 | 2019-07-17T16:28:52.000Z | 2020-03-31T08:36:26.000Z | fst_lookup/fallback_data.py | eddieantonio/fst-lookup | 383173e906c25070fb71044318a6fe9e62ca9c13 | [
"MIT"
] | 15 | 2019-01-31T18:31:35.000Z | 2021-03-01T16:24:20.000Z | fst_lookup/fallback_data.py | eddieantonio/fst-lookup | 383173e906c25070fb71044318a6fe9e62ca9c13 | [
"MIT"
] | 2 | 2019-07-15T20:10:55.000Z | 2019-08-17T18:02:08.000Z | """
Fallback data types, implemented in Python, for platforms that cannot build
the C extension.
"""
from .symbol import Symbol
from .typedefs import StateID
class Arc:
"""
An arc (transition) in the FST.
"""
__slots__ = ("_state", "_upper", "_lower", "_destination")
def __init__(
self, state: StateID, upper: Symbol, lower: Symbol, destination: StateID
) -> None:
self._state = state
self._upper = upper
self._lower = lower
self._destination = destination
@property
def state(self) -> int:
return self._state
@property
def upper(self) -> Symbol:
return self._upper
@property
def lower(self) -> Symbol:
return self._lower
@property
def destination(self) -> int:
return self._destination
def __eq__(self, other) -> bool:
if not isinstance(other, Arc):
return False
return (
self._state == other._state
and self._upper == other._upper
and self._lower == other._lower
and self._destination == other._destination
)
def __hash__(self) -> int:
return self._state + (hash(self._upper) ^ hash(self._lower))
def __str__(self) -> str:
if self._upper == self._lower:
label = str(self._upper)
else:
label = str(self._upper) + ":" + str(self._lower)
return "{:d} -{:s}-> {:d}".format(self._state, label, self._destination)
| 24.655738 | 80 | 0.583112 | 1,342 | 0.892287 | 0 | 0 | 274 | 0.182181 | 0 | 0 | 207 | 0.137633 |
b3e76140bb5e62c77d460ef2b3e264eca9adea9a | 8,612 | py | Python | dashflaskapp/flaskapp/transactions_plotly/dashboard.py | NicholasGoh/real_estate_app | 01fd83ebe7dffbd42fb3cc8ce1e8c9c0d6285ac0 | [
"MIT"
] | null | null | null | dashflaskapp/flaskapp/transactions_plotly/dashboard.py | NicholasGoh/real_estate_app | 01fd83ebe7dffbd42fb3cc8ce1e8c9c0d6285ac0 | [
"MIT"
] | null | null | null | dashflaskapp/flaskapp/transactions_plotly/dashboard.py | NicholasGoh/real_estate_app | 01fd83ebe7dffbd42fb3cc8ce1e8c9c0d6285ac0 | [
"MIT"
] | null | null | null | import pandas as pd
import dash
from dash.dependencies import Input, Output, State
import plotly.express as px
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
# self packages
from .data_generator import load_transactions, comparisons_df
from .nav_bar import nav_bar_template
all_click = []
transactions = load_transactions()
filter_options = {}
cols_for_filter = ['region', 'street', 'propertyType', 'tenure', 'project']
for col in cols_for_filter:
col_options = []
unique_values = transactions[col].unique()
col_options.append({'label': 'All', 'value': 'All'})
for val in unique_values:
col_options.append({'label': val, 'value': val})
filter_options[col] = col_options
# takes in preprocessed click data from the maps and returns the html table rendered version
# note default is invisible table
def render_table(click_data = None, default=False, max_rows=26):
if default:
return html.Table(
id = 'comparison_table'
)
df = comparisons_df()
click_data = click_data[-4:]
for data in click_data:
df = df.append(data)
df.index = [[f'Property {i}' for i in range(len(df))]]
rownames = df.columns
df = df.T
df['info'] = rownames
df.drop(columns=['Property 0'], inplace=True)
columns = list(df.columns)
columns = columns[-1:] + columns[:-1]
df = df[columns]
return html.Table(
# Header
[html.Tr([html.Th(col) for col in df.columns]) ] +
# Body
[html.Tr([
html.Td(df.iloc[i][col]) for col in df.columns
]) for i in range(min(len(df), max_rows))],
id = 'comparison_table',
className = 'table table-bordered active'
)
def render_suggestion(click_data = None, default=False, max_rows=26):
if default:
return html.Table(
id = 'suggestion_table'
)
columns_to_show = ['region', 'street', 'area', 'propertyType', 'nettPrice']
transactions = load_transactions()
transactions = transactions[columns_to_show]
click_data = click_data[-1]
street = click_data['street'].item()
project = click_data['project'].item()
price = click_data['price'].item()
df = transactions.loc[(transactions['street'] == street) & (transactions['nettPrice'] != price) & (transactions['nettPrice'] != 0.0)].head(2)
if df.empty:
return [
html.H3(f'Sugeested properties in the same street: {street}'),
html.H5('There are no available properties in the same area')
]
df.index = [[f'Property {i}' for i in range(len(df))]]
rownames = df.columns
df = df.T
df['info'] = rownames
columns = list(df.columns)
columns = columns[-1:] + columns[:-1]
df = df[columns]
return [
html.H3(f'Sugeested properties in the same street: {street}'),
html.Table(
# Header
[html.Tr([html.Th(col) for col in df.columns]) ] +
# Body
[html.Tr([
html.Td(df.iloc[i][col]) for col in df.columns
]) for i in range(min(len(df), max_rows))],
id = 'suggestion_table',
className = 'table table-bordered active'
)]
# inits transactions dash app that links to flask app
def init_transactions(server):
dashApp = dash.Dash(
server=server,
routes_pathname_prefix='/transactions/',
external_stylesheets=[dbc.themes.BOOTSTRAP]
)
dashApp.index_string = nav_bar_template
# Create Layout
dashApp.layout = html.Div([
html.H1('Transactions Dashboard', style={'text-align': 'center'}),
html.Div([
html.H2(children='Transactions Map', style = {'text-align': 'left'}),
html.Div(children=''' map to visualize transactions '''),
html.Br(),
html.Div([
dcc.Dropdown(
id='regionDropdown',
options = filter_options['region'],
value = 'All',
placeholder='Select a regiion'
),
dcc.Dropdown(
id='streetDropdown',
options = filter_options['street'],
value = 'All',
placeholder='Select a street'
),
dcc.Dropdown(
id='propertyTypeDropdown',
options = filter_options['propertyType'],
value = 'All',
placeholder='Select a property type'
),
dcc.Dropdown(
id='tenureDropdown',
options = filter_options['tenure'],
value = 'All',
placeholder='Select length of tenure'
),
dcc.Dropdown(
id='projectDropdown',
options = filter_options['project'],
value = 'All',
placeholder='Select a project'
),
html.Button('Search', id='search-filter')
]),
html.Br(),
dcc.Loading(
id = 'loading-map',
type = 'default',
children = dcc.Graph(id='transactions_map', figure={})
)
]),
html.Div(
children = render_table(default=True),
id = 'comparison_table_div',
),
html.Div(
children = render_suggestion(default=True),
id = 'suggestion_table_div',
),
html.Div(id='hidden-container')
], className = 'container')
@dashApp.callback(
Output(component_id='transactions_map', component_property='figure'),
[
Input(component_id='search-filter', component_property='n_clicks'),
Input(component_id='transactions_map', component_property='figure'),
],
[
State(component_id='regionDropdown', component_property='value'),
State(component_id='streetDropdown', component_property='value'),
State(component_id='propertyTypeDropdown', component_property='value'),
State(component_id='tenureDropdown', component_property='value'),
State(component_id='projectDropdown', component_property='value'),
]
)
# debug here, add additional arguements to function
def make_map(n_clicks, figure, region, street, propertyType, tenure, project):
transactions = load_transactions()
filters = [region, street, propertyType, tenure, project]
for i in range(len(cols_for_filter)):
if filters[i] != 'All':
transactions = transactions[transactions[cols_for_filter[i]] == filters[i]]
if transactions.empty:
fig = px.scatter_mapbox(lat=['1.3521'], lon=['103.8198'])
else:
fig = px.scatter_mapbox(transactions, lat='x', lon='y', hover_name='project', hover_data=['price', 'region', 'street', 'area'],
custom_data=['noOfUnits', 'propertyType', 'floorRange', 'project', 'tenure'], zoom=12, height=450)
fig.update_layout(mapbox_style='open-street-map')
fig.update_layout(clickmode='event+select')
fig.update_layout(margin={'r':0,'t':0,'l':0,'b':0})
return fig
@dashApp.callback([
Output(component_id='comparison_table_div', component_property='children'),
Output(component_id='suggestion_table_div', component_property='children'),
],
Input(component_id='transactions_map', component_property='clickData'),
)
def display_click_data(click):
if click is None:
return render_table(default=True)
# preprocess the click data from maps
points = click['points'][0]
customdata = points['customdata']
data = {
'x': points['lat'],
'y': points['lon'],
'noOfUnits': customdata[0],
'propertyType': customdata[1],
'floorRange': customdata[2],
'project': customdata[3],
'tenure': customdata[4],
'price': customdata[5],
'region': customdata[6],
'street': customdata[7],
'area': customdata[8]
}
data = {k: [str(v)] for k, v in data.items()}
data = pd.DataFrame.from_dict(data)
all_click.append(data)
return render_table(click_data=all_click), render_suggestion(click_data=all_click)
return dashApp.server
| 37.606987 | 145 | 0.573038 | 0 | 0 | 0 | 0 | 1,221 | 0.141779 | 0 | 0 | 1,955 | 0.227009 |
b3e7a2421199d040d4bc5d2f823332a7d4215881 | 676 | py | Python | scripts/vis_mask.py | ZHUXUHAN/my_segmentation | 8e2847278e2cfe7a5b91afdb68ec68dce1a8437c | [
"MIT"
] | null | null | null | scripts/vis_mask.py | ZHUXUHAN/my_segmentation | 8e2847278e2cfe7a5b91afdb68ec68dce1a8437c | [
"MIT"
] | null | null | null | scripts/vis_mask.py | ZHUXUHAN/my_segmentation | 8e2847278e2cfe7a5b91afdb68ec68dce1a8437c | [
"MIT"
] | null | null | null | import cv2
import numpy as np
from matplotlib import pyplot as plt
plt.switch_backend('agg')
imgfile = '/home/awesome-semantic-segmentation-pytorch/0023c3c5-c0fd-4ab2-85e0-dd00fa2b5f84_1581153710699_align_0.jpg'
pngfile = '/home/awesome-semantic-segmentation-pytorch/scripts/eval/0023c3c5-c0fd-4ab2-85e0-dd00fa2b5f84_1581153710699_align_0.png'
img = cv2.imread(imgfile, 1)
mask = cv2.imread(pngfile, 0)
binary , contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 0, 255), 1)
img = img[:, :, ::-1]
img[..., 2] = np.where(mask == 1, 255, img[..., 2])
plt.imshow(img)
plt.savefig('./eval/mask.png')
| 33.8 | 131 | 0.744083 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 251 | 0.371302 |
b3e9b7dd43a10c9e4f845198db3a37db8afb2e06 | 2,203 | py | Python | src/pretix/base/templatetags/cache_large.py | Janfred/pretix | bdd9751f0e5c440d1c8b56c933db2288e4014f4c | [
"Apache-2.0"
] | 1,248 | 2015-04-24T13:32:06.000Z | 2022-03-29T07:01:36.000Z | src/pretix/base/templatetags/cache_large.py | Janfred/pretix | bdd9751f0e5c440d1c8b56c933db2288e4014f4c | [
"Apache-2.0"
] | 2,113 | 2015-02-18T18:58:16.000Z | 2022-03-31T11:12:32.000Z | src/pretix/base/templatetags/cache_large.py | thegcat/pretix | 451d3fce0575d85a0ea93fd64aa0631feaced967 | [
"Apache-2.0"
] | 453 | 2015-05-13T09:29:06.000Z | 2022-03-24T13:39:16.000Z | #
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# 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 in version 3 of the License.
#
# ADDITIONAL TERMS APPLY: Pursuant to Section 7 of the GNU Affero General Public License, additional terms are
# applicable granting you additional permissions and placing additional restrictions on your usage of this software.
# Please refer to the pretix LICENSE file to obtain the full terms applicable to this work. If you did not receive
# this file, see <https://pretix.eu/about/en/license>.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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 django.conf import settings
from django.template import Library, Node, TemplateSyntaxError, Variable
from django.templatetags.cache import CacheNode
register = Library()
class DummyNode(Node):
def __init__(self, nodelist, *args):
self.nodelist = nodelist
def render(self, context):
value = self.nodelist.render(context)
return value
@register.tag('cache_large')
def do_cache(parser, token):
nodelist = parser.parse(('endcache_large',))
parser.delete_first_token()
tokens = token.split_contents()
if len(tokens) < 3:
raise TemplateSyntaxError("'%r' tag requires at least 2 arguments." % tokens[0])
if not settings.CACHE_LARGE_VALUES_ALLOWED:
return DummyNode(
nodelist,
)
return CacheNode(
nodelist, parser.compile_filter(tokens[1]),
tokens[2], # fragment_name can't be a variable.
[parser.compile_filter(t) for t in tokens[3:]],
Variable(repr(settings.CACHE_LARGE_VALUES_ALIAS)),
)
| 38.649123 | 118 | 0.732183 | 195 | 0.088516 | 0 | 0 | 647 | 0.29369 | 0 | 0 | 1,264 | 0.573763 |
b3e9db7824ba204f9d1c238cbfe4d49fb645b682 | 3,609 | py | Python | utils/pascal_voc.py | hktxt/fasterrcnn | c7de01afd78bd99737c80035843cd6e7e483b911 | [
"MIT"
] | null | null | null | utils/pascal_voc.py | hktxt/fasterrcnn | c7de01afd78bd99737c80035843cd6e7e483b911 | [
"MIT"
] | null | null | null | utils/pascal_voc.py | hktxt/fasterrcnn | c7de01afd78bd99737c80035843cd6e7e483b911 | [
"MIT"
] | null | null | null | import os
import uuid
import numpy as np
from tqdm import tqdm
import pickle
from utils.config import opt
from .voc_eval import voc_eval
devkit_path = opt.voc_data_dir[:-8]
year = opt.year
def do_python_eval(classes, image_set, output_dir='output'):
annopath = os.path.join(
devkit_path,
'VOC' + year,
'Annotations',
'{}.xml')
imagesetfile = os.path.join(
devkit_path,
'VOC' + year,
'ImageSets',
'Main',
image_set + '.txt')
cachedir = os.path.join(devkit_path, 'annotations_cache')
aps = []
# The PASCAL VOC metric changed in 2010
use_07_metric = True if int(year) < 2010 else False
print('VOC07 metric? ' + ('Yes' if use_07_metric else 'No'))
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
for i, cls in enumerate(classes):
if cls == '__background__':
continue
filename = get_voc_results_file_template(image_set).format(cls)
rec, prec, ap = voc_eval(
filename, annopath, imagesetfile, cls, cachedir, ovthresh=0.5,
use_07_metric=use_07_metric)
aps += [ap]
print('AP for {} = {:.4f}'.format(cls, ap))
with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f:
pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f)
print('Mean AP = {:.4f}'.format(np.mean(aps)))
print('~~~~~~~~')
print('Results:')
for ap in aps:
print('{:.3f}'.format(ap))
print('{:.3f}'.format(np.mean(aps)))
print('~~~~~~~~')
print('')
print('--------------------------------------------------------------')
print('Results computed with the **unofficial** Python eval code.')
print('Results should be very close to the official MATLAB eval code.')
print('Recompute with `./tools/reval.py --matlab ...` for your paper.')
print('-- Thanks, The Management')
print('--------------------------------------------------------------')
def get_comp_id():
salt = str(uuid.uuid4())
comp_id = 'comp4'
#comp_id = (comp_id + '_' + salt if True else comp_id)
return comp_id
def get_voc_results_file_template(image_set):
# VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt
filename = get_comp_id() + '_det_' + image_set + '_{:s}.txt'
filedir = os.path.join(devkit_path, 'results', 'VOC' + year, 'Main')
if not os.path.exists(filedir):
os.makedirs(filedir)
path = os.path.join(filedir, filename)
return path
def write_voc_results_file(image_index, classes, all_boxes, image_set):
for cls_ind, cls in enumerate(classes):
if cls == '__background__':
continue
filename = get_voc_results_file_template(image_set).format(cls)
print('Writing {} VOC results file: {}'.format(cls, filename))
with open(filename, 'wt') as f:
for im_ind, index in enumerate(image_index):
dets = all_boxes[cls_ind][im_ind]
if dets == []:
continue
# the VOCdevkit expects 1-based indices
for k in range(dets.shape[0]):
f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'.
format(index, dets[k, -1],
dets[k, 0] + 1, dets[k, 1] + 1,
dets[k, 2] + 1, dets[k, 3] + 1))
def evaluate_detections(image_index, classes, all_boxes, output_dir, image_set):
write_voc_results_file(image_index, classes, all_boxes, image_set)
do_python_eval(classes, image_set, output_dir)
| 36.454545 | 80 | 0.569133 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 917 | 0.254087 |
b3e9fef97a59ba6d9d87e871a5f6cd1c0bbe6864 | 2,111 | py | Python | indicators.py | abulte/python-influxdb-alerts | 5955b99551094d24197705ec5d97373b64b338a1 | [
"MIT"
] | 2 | 2018-04-16T23:44:56.000Z | 2019-02-28T16:43:57.000Z | indicators.py | abulte/python-influxdb-alerts | 5955b99551094d24197705ec5d97373b64b338a1 | [
"MIT"
] | null | null | null | indicators.py | abulte/python-influxdb-alerts | 5955b99551094d24197705ec5d97373b64b338a1 | [
"MIT"
] | 1 | 2021-05-04T16:06:15.000Z | 2021-05-04T16:06:15.000Z | """Indicators to monitor"""
import click
from configparser import NoOptionError
from query import Query
from config import CONFIG
class BaseIndicator(object):
client = Query()
# name of the metric in influxdb
name = 'base_indicator'
# unit (displays in alerts)
unit = ''
# alert when value gt (>) than threshold or lt (<)
comparison = 'gt'
# timeframe to compute mean of indicator values on
timeframe = '10m'
# some filters to pass to the influx db query (where clause)
filters = None
# divide the raw value from influx by this (eg convert bytes to Mb, Gb...)
divider = 1
def __init__(self):
try:
self.threshold = float(CONFIG.get('thresholds', self.name))
except NoOptionError:
raise click.ClickException('No threshold configured for indicator %s' % self.name)
def get_value(self, host):
"""Get the value from influx for this indicator"""
value = self.client.query_last_mean(
self.name,
host,
timeframe=self.timeframe,
filters=self.filters
)
if value:
return value / self.divider
def is_alert(self, host, value=None):
"""Is this indicator in alert state?"""
value = self.get_value(host) if not value else value
if self.comparison == 'gt' and value > self.threshold:
return True
elif self.comparison == 'lt' and value < self.threshold:
return True
else:
return False
class LoadIndicator(BaseIndicator):
name = 'load_longterm'
unit = ''
comparison = 'gt'
timeframe = '10m'
filters = None
divider = 1
class FreeRAMIndicator(BaseIndicator):
name = 'memory_value'
unit = 'Mb'
comparison = 'lt'
timeframe = '10m'
filters = {
'type_instance': 'free'
}
divider = 1000000
class FreeDiskIndicator(BaseIndicator):
name = 'df_value'
unit = 'Mb'
comparison = 'lt'
timeframe = '10m'
filters = {
'type_instance': 'free'
}
divider = 1000000
| 24.546512 | 94 | 0.606348 | 1,967 | 0.931786 | 0 | 0 | 0 | 0 | 0 | 0 | 616 | 0.291805 |
b3eabfc5d1919b5ecce2863be161ba0e44633f43 | 5,955 | py | Python | Project-4/python_template/mogEM.py | ybhan/Machine-Learning-Projects | 80301a774247bb6ad11cccaeef54e9ec588a61b0 | [
"MIT"
] | null | null | null | Project-4/python_template/mogEM.py | ybhan/Machine-Learning-Projects | 80301a774247bb6ad11cccaeef54e9ec588a61b0 | [
"MIT"
] | null | null | null | Project-4/python_template/mogEM.py | ybhan/Machine-Learning-Projects | 80301a774247bb6ad11cccaeef54e9ec588a61b0 | [
"MIT"
] | null | null | null | from kmeans import *
import sys
import matplotlib.pyplot as plt
plt.ion()
def mogEM(x, K, iters, minVary=0):
"""
Fits a Mixture of K Gaussians on x.
Inputs:
x: data with one data vector in each column.
K: Number of Gaussians.
iters: Number of EM iterations.
minVary: minimum variance of each Gaussian.
Returns:
p : probabilities of clusters.
mu = mean of the clusters, one in each column.
vary = variances for the cth cluster, one in each column.
logProbX = log-probability of data after every iteration.
"""
N, T = x.shape
# Initialize the parameters
randConst = 1
p = randConst + np.random.rand(K, 1)
p = p / np.sum(p)
mn = np.mean(x, axis=1).reshape(-1, 1)
vr = np.var(x, axis=1).reshape(-1, 1)
# Change the initializaiton with Kmeans here
# -------------------- Add your code here --------------------
mu = mn + np.random.randn(N, K) * (np.sqrt(vr) / randConst)
# ------------------------------------------------------------
vary = vr * np.ones((1, K)) * 2
vary = (vary >= minVary) * vary + (vary < minVary) * minVary
logProbX = np.zeros((iters, 1))
# Do iters iterations of EM
for i in xrange(iters):
# Do the E step
respTot = np.zeros((K, 1))
respX = np.zeros((N, K))
respDist = np.zeros((N, K))
logProb = np.zeros((1, T))
ivary = 1 / vary
logNorm = np.log(p) - 0.5 * N * np.log(2 * np.pi) - \
0.5 * np.sum(np.log(vary), axis=0).reshape(-1, 1)
logPcAndx = np.zeros((K, T))
for k in xrange(K):
dis = (x - mu[:, k].reshape(-1, 1))**2
logPcAndx[k, :] = logNorm[k] - 0.5 * \
np.sum(ivary[:, k].reshape(-1, 1) * dis, axis=0)
mxi = np.argmax(logPcAndx, axis=1).reshape(1, -1)
mx = np.max(logPcAndx, axis=0).reshape(1, -1)
PcAndx = np.exp(logPcAndx - mx)
Px = np.sum(PcAndx, axis=0).reshape(1, -1)
PcGivenx = PcAndx / Px
logProb = np.log(Px) + mx
logProbX[i] = np.sum(logProb)
print 'Iter %d logProb %.5f' % (i, logProbX[i])
# Plot log prob of data
plt.figure(1)
plt.clf()
plt.plot(np.arange(i), logProbX[:i], 'r-')
plt.title('Log-probability of data versus # iterations of EM')
plt.xlabel('Iterations of EM')
plt.ylabel('log P(D)')
plt.draw()
respTot = np.mean(PcGivenx, axis=1).reshape(-1, 1)
respX = np.zeros((N, K))
respDist = np.zeros((N, K))
for k in xrange(K):
respX[:, k] = np.mean(x * PcGivenx[k, :].reshape(1, -1), axis=1)
respDist[:, k] = np.mean((x - mu[:, k].reshape(-1, 1))**2
* PcGivenx[k, :].reshape(1, -1), axis=1)
# Do the M step
p = respTot
mu = respX / respTot.T
vary = respDist / respTot.T
vary = (vary >= minVary) * vary + (vary < minVary) * minVary
return p, mu, vary, logProbX
def mogLogProb(p, mu, vary, x):
"""Computes logprob of each data vector in x under the MoG model
specified by p, mu and vary."""
K = p.shape[0]
N, T = x.shape
ivary = 1 / vary
logProb = np.zeros(T)
for t in xrange(T):
# Compute log P(c)p(x|c) and then log p(x)
logPcAndx = np.log(p) - 0.5 * N * np.log(2 * np.pi) \
- 0.5 * np.sum(np.log(vary), axis=0).reshape(-1, 1) \
- 0.5 * \
np.sum(ivary * (x[:, t].reshape(-1, 1) - mu)
** 2, axis=0).reshape(-1, 1)
mx = np.max(logPcAndx, axis=0)
logProb[t] = np.log(np.sum(np.exp(logPcAndx - mx))) + mx
return logProb
def q3():
iters = 10
minVary = 0.01
(inputs_train, inputs_valid, inputs_test,
target_train, target_valid, target_test) = LoadData('digits.npz')
# Train a MoG model with 20 components on all 600 training
# vectors, with both original initialization and kmeans initialization.
# ------------------- Add your code here ---------------------
raw_input('Press Enter to continue.')
def q4():
iters = 10
minVary = 0.01
errorTrain = np.zeros(4)
errorTest = np.zeros(4)
errorValidation = np.zeros(4)
print(errorTrain)
numComponents = np.array([2, 5, 15, 25])
T = numComponents.shape[0]
(inputs_train, inputs_valid, inputs_test, target_train,
target_valid, target_test) = LoadData('digits.npz')
(train2, valid2, test2, target_train2,
target_valid2, target_test2) = LoadData('digits.npz', True, False)
(train3, valid3, test3, target_train3,
target_valid3, target_test3) = LoadData('digits.npz', False, True)
for t in xrange(T):
K = numComponents[t]
# Train a MoG model with K components for digit 2
# -------------------- Add your code here --------------------
# Train a MoG model with K components for digit 3
# -------------------- Add your code here --------------------
# Caculate the probability P(d=1|x) and P(d=2|x),
# classify examples, and compute error rate
# Hints: you may want to use mogLogProb function
# -------------------- Add your code here --------------------
# Plot the error rate
plt.clf()
# -------------------- Add your code here --------------------
plt.draw()
raw_input('Press Enter to continue.')
def q5():
# Choose the best mixture of Gaussian classifier you have, compare this
# mixture of Gaussian classifier with the neural network you implemented in
# the last assignment.
# Train neural network classifier. The number of hidden units should be
# equal to the number of mixture components.
# Show the error rate comparison.
# -------------------- Add your code here --------------------
raw_input('Press Enter to continue.')
if __name__ == '__main__':
q3()
q4()
q5()
| 33.083333 | 79 | 0.538539 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,202 | 0.369773 |
b3ed72fa8fd255bd3466367b59b2f940a3c9c4e8 | 600 | py | Python | openbook_posts/migrations/0022_auto_20190311_1432.py | TamaraAbells/okuna-api | f87d8e80d2f182c01dbce68155ded0078ee707e4 | [
"MIT"
] | 164 | 2019-07-29T17:59:06.000Z | 2022-03-19T21:36:01.000Z | openbook_posts/migrations/0022_auto_20190311_1432.py | TamaraAbells/okuna-api | f87d8e80d2f182c01dbce68155ded0078ee707e4 | [
"MIT"
] | 188 | 2019-03-16T09:53:25.000Z | 2019-07-25T14:57:24.000Z | openbook_posts/migrations/0022_auto_20190311_1432.py | TamaraAbells/okuna-api | f87d8e80d2f182c01dbce68155ded0078ee707e4 | [
"MIT"
] | 80 | 2019-08-03T17:49:08.000Z | 2022-02-28T16:56:33.000Z | # Generated by Django 2.2b1 on 2019-03-11 13:32
from django.db import migrations
import imagekit.models.fields
import openbook_posts.helpers
class Migration(migrations.Migration):
dependencies = [
('openbook_posts', '0021_auto_20190309_1532'),
]
operations = [
migrations.AlterField(
model_name='postimage',
name='image',
field=imagekit.models.fields.ProcessedImageField(height_field='height', null=True, upload_to=openbook_posts.helpers.upload_to_post_image_directory, verbose_name='image', width_field='width'),
),
]
| 28.571429 | 203 | 0.698333 | 455 | 0.758333 | 0 | 0 | 0 | 0 | 0 | 0 | 128 | 0.213333 |
b3eeb3b273ced737afa9c583f2c895e42540c161 | 617 | py | Python | setup.py | AndersenLab/liftover-utils | 17041d8b84ba79e9b3105267040bec4ade437a5c | [
"MIT"
] | 7 | 2015-04-29T22:53:46.000Z | 2022-03-11T02:24:32.000Z | setup.py | AndersenLab/liftover-utils | 17041d8b84ba79e9b3105267040bec4ade437a5c | [
"MIT"
] | 2 | 2015-05-04T23:40:00.000Z | 2015-12-01T21:17:56.000Z | setup.py | AndersenLab/liftover-utils | 17041d8b84ba79e9b3105267040bec4ade437a5c | [
"MIT"
] | 1 | 2017-07-07T05:19:12.000Z | 2017-07-07T05:19:12.000Z | from setuptools import setup
import glob
setup(name='liftover.py',
version='0.1',
packages=['liftover'],
description='C. elegans liftover utility',
url='https://github.com/AndersenLab/liftover-utils',
author='Daniel Cook',
author_email='danielecook@gmail.com',
license='MIT',
entry_points="""
[console_scripts]
liftover = liftover.liftover:main
""",
install_requires=["docopt"],
data_files=[('CHROMOSOME_DIFFERENCES', glob.glob("data/CHROMOSOME_DIFFERENCES/sequence*")),
'remap_gff_between_releases.pl'],
zip_safe=False) | 32.473684 | 97 | 0.65316 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 324 | 0.525122 |
b3ef0f6b300b19a75f79345e97a807ae11d3fb46 | 3,182 | py | Python | functions/include/serializer.py | xyclin/fluent | f1dcede5d4b7d6eab722180129dbb5aff4241621 | [
"Apache-2.0"
] | 1,164 | 2018-07-25T23:17:07.000Z | 2019-07-11T20:33:52.000Z | functions/include/serializer.py | longwutianya/fluent | c8fc9f2dd781e5ed91c34351adc6a101cc383083 | [
"Apache-2.0"
] | 126 | 2018-07-25T22:41:53.000Z | 2019-07-10T21:49:19.000Z | functions/include/serializer.py | longwutianya/fluent | c8fc9f2dd781e5ed91c34351adc6a101cc383083 | [
"Apache-2.0"
] | 178 | 2018-07-25T23:17:11.000Z | 2019-07-10T02:45:27.000Z | # Copyright 2018 U.C. Berkeley RISE Lab
#
# 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 cloudpickle as cp
import pyarrow as pa
import codecs
from io import BytesIO
import numpy as np
from .functions_pb2 import *
from . import shared
SER_FORMAT = 'raw_unicode_escape'
class Serializer():
def __init__(self):
raise NotImplementedError('Cannot instantiate abstract class.')
def _serialize(self, msg):
pass
def _deserialize(self, msg):
pass
def dump(self, msg):
pass
def load(self, msg):
pass
class DefaultSerializer(Serializer):
def __init__(self):
pass
def _serialize(msg):
return msg
def _deserialize(self, msg):
return msg
def dump(self, msg):
return cp.dumps(msg)
def load(self, msg):
return cp.loads(msg)
class StringSerializer(Serializer):
def __init__(self):
pass
def _serialize(self, msg):
return codecs.decode(msg, SER_FORMAT)
def _deserialize(self, msg):
return codecs.encode(msg, SER_FORMAT)
def dump(self, msg):
return self._serialize(cp.dumps(msg))
def load(self, msg):
return cp.loads(self._deserialize(msg))
# TODO: how can we make serializers pluggable?
class NumpySerializer(DefaultSerializer):
def __init__(self):
pass
def dump(self, msg):
return pa.serialize(msg).to_buffer().to_pybytes()
def load(self, msg):
return pa.deserialize(msg)
numpy_ser = NumpySerializer()
default_ser = DefaultSerializer()
string_ser = StringSerializer()
function_ser = default_ser
def get_serializer(kind):
global numpy_ser, default_ser, string_ser
if kind == NUMPY:
return numpy_ser
elif kind == STRING:
return string_ser
elif kind == DEFAULT:
return default_ser
else:
return default_ser
def serialize_val(val, valobj=None, serialize=True):
if not valobj:
valobj = Value()
if isinstance(val, shared.FluentFuture):
valobj.body = default_ser.dump(shared.FluentReference(val.obj_id,
True, LWW))
elif isinstance(val, np.ndarray):
valobj.body = numpy_ser.dump(val)
valobj.type = NUMPY
else:
valobj.body = default_ser.dump(val)
if not serialize:
return valobj
return valobj.SerializeToString()
def deserialize_val(val):
v = Value()
v.ParseFromString(val)
if v.type == DEFAULT:
return default_ser.load(v.body)
elif v.type == STRING:
return string_ser.load(v.body)
elif v.type == NUMPY:
return numpy_ser.load(v.body)
| 22.892086 | 75 | 0.660905 | 1,165 | 0.366122 | 0 | 0 | 0 | 0 | 0 | 0 | 685 | 0.215273 |
b3ef8ee3fd80d4e7439e46e105cfd252de319dd7 | 2,610 | py | Python | tests/test_atom.py | mkowiel/restraintlib | 32de01d67ae290a45f3199e90c729acc258a6249 | [
"BSD-3-Clause"
] | null | null | null | tests/test_atom.py | mkowiel/restraintlib | 32de01d67ae290a45f3199e90c729acc258a6249 | [
"BSD-3-Clause"
] | 1 | 2021-11-11T18:45:10.000Z | 2021-11-11T18:45:10.000Z | tests/test_atom.py | mkowiel/restraintlib | 32de01d67ae290a45f3199e90c729acc258a6249 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
import math
from unittest import TestCase
from restraintlib.atom import Atom
class AtomTestCase(TestCase):
def setUp(self):
self.atom = Atom('A', '100', 'DT', 'C2', ' ', (1.0, 0.2, 0.3), 1)
self.atom2 = Atom('A', '100', 'DT', 'C3', ' ', (1.0, 1.0, 1.0), 2)
def test_str(self):
expected = "chain: A res: 100 monomer: DT atom: C2 alt loc: xyz: (1.0, 0.2, 0.3)"
self.assertEqual(expected, str(self.atom))
def test_cross(self):
cross = Atom.cross(self.atom.atom_xyz, self.atom2.atom_xyz)
self.assertEqual((0.2 - 0.3, 0.3 - 1.0, 1.0 - 0.2), cross)
def test_sub(self):
sub = Atom.sub(self.atom.atom_xyz, self.atom2.atom_xyz)
self.assertEqual((0.0, -0.8, -0.7), sub)
def test_dot(self):
dot = Atom.dot(self.atom.atom_xyz, self.atom2.atom_xyz)
self.assertEqual(1.5, dot)
def test_lenght(self):
length = Atom.lenght(self.atom.atom_xyz)
self.assertAlmostEqual(math.sqrt(1.13), length, 5)
length = Atom.lenght(self.atom2.atom_xyz)
self.assertAlmostEqual(math.sqrt(3.0), length, 5)
def test_mul_sca(self):
vec = Atom.mul_sca(3, self.atom2.atom_xyz)
self.assertEqual((3.0, 3.0, 3.0), vec)
def test_normalize(self):
vec = Atom.normalize(self.atom2.atom_xyz)
self.assertEqual(1.0, Atom.lenght(vec))
def test_det(self):
det = Atom.det(self.atom.atom_xyz, self.atom2.atom_xyz, self.atom2.atom_xyz)
self.assertAlmostEqual(0, det, 6)
det = Atom.det(self.atom.atom_xyz, self.atom2.atom_xyz, (1, 1, 0.5))
self.assertAlmostEqual(-0.4, det, 6)
def test_dist(self):
dist = self.atom.dist(self.atom2)
self.assertAlmostEqual(math.sqrt(1.13), dist, 6)
def test_angle(self):
zero = Atom('', '1', '', '', '', (0.0, 0.0, 0.0), 1)
one = Atom('', '2', '', '', '', (1.0, 0.0, 0.0), 2)
diag = Atom('', '3', '', '', '', (1.0, 1.0, 0.0), 3)
one_one_one = Atom('', '3', '', '', '', (1.0, 1.0, 1.0), 4)
angle = one.angle(zero, diag)
self.assertAlmostEqual(45, angle, 6)
angle = diag.angle(zero, one_one_one)
self.assertAlmostEqual(35.26, angle, 2)
def test_torsion(self):
a1 = Atom('', '1', '', '', '', (-1.0, -1.0, 0.0), 1)
a2 = Atom('', '2', '', '', '', (-1.0, 0.0, 0.0), 2)
a3 = Atom('', '3', '', '', '', (1.0, 0.0, 0.0), 3)
a4 = Atom('', '3', '', '', '', (1.0, 1.0, 0.0), 4)
torsion = a1.torsion(a2, a3, a4)
self.assertAlmostEqual(180, torsion, 6)
| 34.8 | 90 | 0.544444 | 2,505 | 0.95977 | 0 | 0 | 0 | 0 | 0 | 0 | 220 | 0.084291 |
b3efed275b239800b25c7e1dd58abe57758234de | 1,757 | py | Python | QRARRAY.py | k205045/GreenTransAGV | 4ad8634578e59be7d4568822adf69e061a1403af | [
"MIT"
] | null | null | null | QRARRAY.py | k205045/GreenTransAGV | 4ad8634578e59be7d4568822adf69e061a1403af | [
"MIT"
] | null | null | null | QRARRAY.py | k205045/GreenTransAGV | 4ad8634578e59be7d4568822adf69e061a1403af | [
"MIT"
] | null | null | null | from PIL import Image, ImageDraw, ImageFilter
from PIL import ImageFont
from os import listdir
from os.path import isfile, join
#QRcode拼貼
mypath = "QRcodefloder"
# im = Image.open("advanceduse.png")
list = []
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
print(onlyfiles)
for onlyfile in onlyfiles:
list.append(Image.open("QRcodefloder\\"+onlyfile))
squard = list[0].size[0]
num = 0
for i in range(1,15):
a4im = Image.new('RGB',
(595, 842), # A4 at 72dpi
(255, 255, 255)) # White
image2 = Image.new('RGB', (squard, squard), (0, 0, 0))
draw = ImageDraw.Draw(a4im)
font = ImageFont.truetype('arial.ttf', 7)
width, height = image2.size
print(list[0].size)
crop_width, crop_height = a4im.size
for left in range(0, crop_width, width):
for top in range(0, crop_height, height):
print(num)
if num == len(list):
break
print(left,top)
if left+squard > 595:
break
if top+squard > 842:
break
# print(left // 165)
a4im.paste(image2, (left - left // squard, top - top // squard))
print(left - left // squard, top - top // squard)
a4im.paste(list[num], (left+1 - left // squard, top+1 - top // squard))
draw.text((left + 20 - left // squard, top - top // squard), onlyfiles[num][:7], font=font, fill="#000000")
# print(onlyfiles[num])
num += 1
# a4im.paste(im, im.getbbox()) # Not centered, top-left corner
a4im.filter(ImageFilter.EDGE_ENHANCE)
a4im.save("QR"+str(i)+".jpg", quality=100)
a4im.show()
if num == len(list):
break
| 29.283333 | 119 | 0.56346 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 245 | 0.139125 |
b3f06db8d0fc5811f66b9bac54d4e0a653b8b217 | 2,703 | py | Python | vaksina/person.py | Guiorgy/vaksina | 917de581a8fe1b77fa69484d1a88cbf2724c0610 | [
"MIT"
] | 39 | 2022-01-01T19:01:52.000Z | 2022-01-25T03:05:19.000Z | vaksina/person.py | Guiorgy/vaksina | 917de581a8fe1b77fa69484d1a88cbf2724c0610 | [
"MIT"
] | 10 | 2022-01-01T19:17:34.000Z | 2022-01-21T16:35:31.000Z | vaksina/person.py | Guiorgy/vaksina | 917de581a8fe1b77fa69484d1a88cbf2724c0610 | [
"MIT"
] | 14 | 2022-01-02T11:43:02.000Z | 2022-01-17T20:17:03.000Z | # Copyright (c) 2022 Michael Casadevall
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
from datetime import datetime
class Person(object):
def __init__(self):
self.names = []
"""name is a list of names from the vaccination card
At least in theory, it is possible for a SMART Heart Card, or
others to list multiple names, as that is part of the FHIR standard
As this was explained to me, this is primary intended for cases of people
with multiple legal aliases. I am not certain if SHC other card would be
*issued* like that, but its also a possibility, so in the hope to avoid
a future refactor, this is handled as a list (unfortunately)
"""
self.dob = None
"""Handles the date of birth for a given person
Object held in Python DateTime format"""
self.immunizations = []
"""Immunizations are vaksina.Immunization objects, formed as a list.
Only completed vaccitions (that is status = "completed" in SHC, or similar
in other cards) is included, since this is not intended as a general purpose
health record tool, merely a validator for COVID-19 QR codes
"""
def to_dict(self):
"""Serializes data to a dictionary for use in JSON, etc."""
person_dict = {}
person_dict["name"] = []
for name in self.names:
person_dict["name"].append(name)
person_dict["dob"] = self.dob.strftime("%Y-%m-%d")
person_dict["immunizations"] = []
for immunization in self.immunizations:
person_dict["immunizations"].append(immunization.to_dict())
return person_dict
| 41.584615 | 84 | 0.697003 | 1,570 | 0.580836 | 0 | 0 | 0 | 0 | 0 | 0 | 2,134 | 0.789493 |
b3f16b9175ddbc53aed5519784666123e0d55491 | 6,964 | py | Python | tests/integration/test_breakpoint_step.py | benjamintemitope/SublimeTextXdebug | 7b62975aed85f4bc839d908d7a696d1ca2b794d9 | [
"MIT"
] | 344 | 2015-01-03T01:55:52.000Z | 2022-01-11T08:52:55.000Z | tests/integration/test_breakpoint_step.py | benjamintemitope/SublimeTextXdebug | 7b62975aed85f4bc839d908d7a696d1ca2b794d9 | [
"MIT"
] | 107 | 2015-01-05T12:46:39.000Z | 2021-03-25T04:56:16.000Z | tests/integration/test_breakpoint_step.py | benjamintemitope/SublimeTextXdebug | 7b62975aed85f4bc839d908d7a696d1ca2b794d9 | [
"MIT"
] | 82 | 2015-01-10T16:02:50.000Z | 2022-01-18T19:25:58.000Z | import os
try:
from xdebug.unittesting import XdebugDeferrableTestCase
except:
from SublimeTextXdebug.xdebug.unittesting import XdebugDeferrableTestCase
class TestBreakpointStep(XdebugDeferrableTestCase):
breakpoint_step_file = 'breakpoint_step.php'
breakpoint_step_file_local_path = os.path.join(XdebugDeferrableTestCase.local_path, breakpoint_step_file)
def test_step_into(self):
self.set_breakpoint(self.breakpoint_step_file_local_path, 11)
self.run_command('xdebug_session_start')
yield self.window_has_debug_layout
breakpoint_view = self.get_view_by_title('Xdebug Breakpoint')
context_view = self.get_view_by_title('Xdebug Context')
stack_view = self.get_view_by_title('Xdebug Stack')
self.assertViewContains(breakpoint_view, '=> {file_local_path}\n\t|+| 11'.format(file_local_path=self.breakpoint_step_file_local_path))
self.assertViewIsEmpty(context_view)
self.assertViewIsEmpty(stack_view)
self.send_server_request(path=self.breakpoint_step_file)
def context_and_stack_have_content():
return not self.view_is_empty(context_view) and not self.view_is_empty(stack_view)
yield context_and_stack_have_content
self.assertViewContains(context_view, '$greeting = <uninitialized>')
self.assertViewContains(stack_view, '[0] file://{remote_path}/{file}:11, {{main}}()'.format(remote_path=self.remote_path, file=self.breakpoint_step_file))
context_view_contents = self.get_contents_of_view(context_view)
stack_view_contents = self.get_contents_of_view(stack_view)
def context_and_stack_have_different_content():
return self.get_contents_of_view(context_view) != context_view_contents and self.get_contents_of_view(stack_view) != stack_view_contents
self.run_command('xdebug_execute', {'command': 'step_into'})
yield context_and_stack_have_different_content
yield context_and_stack_have_content
self.assertViewContains(context_view, '$greet = <uninitialized>')
self.assertViewContains(context_view, '$name = (string) Stranger')
self.assertViewContains(stack_view, '[0] file://{remote_path}/{file}:4, greet()'.format(remote_path=self.remote_path, file=self.breakpoint_step_file))
context_view_contents = self.get_contents_of_view(context_view)
stack_view_contents = self.get_contents_of_view(stack_view)
def context_and_stack_have_different_content():
return self.get_contents_of_view(context_view) != context_view_contents and self.get_contents_of_view(stack_view) != stack_view_contents
self.run_command('xdebug_execute', {'command': 'step_into'})
yield context_and_stack_have_different_content
yield context_and_stack_have_content
self.assertViewContains(context_view, '$greet = (string) Hi')
self.assertViewContains(context_view, '$name = (string) Stranger')
self.assertViewContains(stack_view, '[0] file://{remote_path}/{file}:5, greet()'.format(remote_path=self.remote_path, file=self.breakpoint_step_file))
def test_step_out(self):
self.set_breakpoint(self.breakpoint_step_file_local_path, 5)
self.run_command('xdebug_session_start')
yield self.window_has_debug_layout
breakpoint_view = self.get_view_by_title('Xdebug Breakpoint')
context_view = self.get_view_by_title('Xdebug Context')
stack_view = self.get_view_by_title('Xdebug Stack')
self.assertViewContains(breakpoint_view, '=> {file_local_path}\n\t|+| 5'.format(file_local_path=self.breakpoint_step_file_local_path))
self.assertViewIsEmpty(context_view)
self.assertViewIsEmpty(stack_view)
self.send_server_request(path=self.breakpoint_step_file)
def context_and_stack_have_content():
return not self.view_is_empty(context_view) and not self.view_is_empty(stack_view)
yield context_and_stack_have_content
self.assertViewContains(context_view, '$greet = (string) Hi')
self.assertViewContains(context_view, '$name = (string) Stranger')
self.assertViewContains(stack_view, '[0] file://{remote_path}/{file}:5, greet()'.format(remote_path=self.remote_path, file=self.breakpoint_step_file))
context_view_contents = self.get_contents_of_view(context_view)
stack_view_contents = self.get_contents_of_view(stack_view)
def context_and_stack_have_different_content():
return self.get_contents_of_view(context_view) != context_view_contents and self.get_contents_of_view(stack_view) != stack_view_contents
self.run_command('xdebug_execute', {'command': 'step_out'})
yield context_and_stack_have_different_content
yield context_and_stack_have_content
self.assertViewContains(context_view, '$greeting = (string) Hello Stranger!')
self.assertViewContains(stack_view, '[0] file://{remote_path}/{file}:12, {{main}}()'.format(remote_path=self.remote_path, file=self.breakpoint_step_file))
def test_step_over(self):
self.set_breakpoint(self.breakpoint_step_file_local_path, 11)
self.run_command('xdebug_session_start')
yield self.window_has_debug_layout
breakpoint_view = self.get_view_by_title('Xdebug Breakpoint')
context_view = self.get_view_by_title('Xdebug Context')
stack_view = self.get_view_by_title('Xdebug Stack')
self.assertViewContains(breakpoint_view, '=> {file_local_path}\n\t|+| 11'.format(file_local_path=self.breakpoint_step_file_local_path))
self.assertViewIsEmpty(context_view)
self.assertViewIsEmpty(stack_view)
self.send_server_request(path=self.breakpoint_step_file)
def context_and_stack_have_content():
return not self.view_is_empty(context_view) and not self.view_is_empty(stack_view)
yield context_and_stack_have_content
self.assertViewContains(context_view, '$greeting = <uninitialized>')
self.assertViewContains(stack_view, '[0] file://{remote_path}/{file}:11, {{main}}()'.format(remote_path=self.remote_path, file=self.breakpoint_step_file))
context_view_contents = self.get_contents_of_view(context_view)
stack_view_contents = self.get_contents_of_view(stack_view)
def context_and_stack_have_different_content():
return self.get_contents_of_view(context_view) != context_view_contents and self.get_contents_of_view(stack_view) != stack_view_contents
self.run_command('xdebug_execute', {'command': 'step_over'})
yield context_and_stack_have_different_content
yield context_and_stack_have_content
self.assertViewContains(context_view, '$greeting = (string) Hello Stranger!')
self.assertViewContains(stack_view, '[0] file://{remote_path}/{file}:12, {{main}}()'.format(remote_path=self.remote_path, file=self.breakpoint_step_file))
| 51.585185 | 162 | 0.747702 | 6,800 | 0.97645 | 6,572 | 0.943711 | 0 | 0 | 0 | 0 | 1,081 | 0.155227 |
b3f2836bffc8bb0fbc4cbeb37e50f7145fc48bd5 | 1,099 | py | Python | tests/test_settings.py | wegostudio/wegq | 391cdf7e6a345079c20d9c517bff89cd440dd35c | [
"Apache-2.0"
] | null | null | null | tests/test_settings.py | wegostudio/wegq | 391cdf7e6a345079c20d9c517bff89cd440dd35c | [
"Apache-2.0"
] | null | null | null | tests/test_settings.py | wegostudio/wegq | 391cdf7e6a345079c20d9c517bff89cd440dd35c | [
"Apache-2.0"
] | null | null | null | import unittest
from wework import settings, wechat
class TestSettings(unittest.TestCase):
def test_init(self):
t = settings.init(
CROP_ID='a',
PROVIDER_SECRET='a',
REGISTER_URL='www.quseit.com/',
HELPER='wegq.DjangoHelper'
)
self.assertTrue(isinstance(t, wechat.WorkWechatApi))
def test_error(self):
with self.assertRaises(settings.InitError):
settings.init(
CROP_ID='a',
PROVIDER_SECRET='a',
HELPER='wegq.DjangoHelper'
)
with self.assertRaises(settings.InitError):
settings.init(
CROP_ID='a',
PROVIDER_SECRET='a',
REGISTER_URL='www.quseit.com',
HELPER='wegq.DjangoHelper'
)
with self.assertRaises(settings.InitError):
settings.init(
CROP_ID='a',
PROVIDER_SECRET='a',
REGISTER_URL='www.quseit.com',
HELPER=type('MyHelper', (object, ), {}),
) | 29.702703 | 60 | 0.520473 | 1,045 | 0.950864 | 0 | 0 | 0 | 0 | 0 | 0 | 140 | 0.127389 |
b3f2957d39e42867207d8d036622748d178e9739 | 1,608 | py | Python | icevision/models/ultralytics/yolov5/fastai/learner.py | ai-fast-track/mantisshrimp | cc6d6a4a048f6ddda2782b6593dcd6b083a673e4 | [
"Apache-2.0"
] | 580 | 2020-09-10T06:29:57.000Z | 2022-03-29T19:34:54.000Z | icevision/models/ultralytics/yolov5/fastai/learner.py | ai-fast-track/mantisshrimp | cc6d6a4a048f6ddda2782b6593dcd6b083a673e4 | [
"Apache-2.0"
] | 691 | 2020-09-05T03:08:34.000Z | 2022-03-31T23:47:06.000Z | icevision/models/ultralytics/yolov5/fastai/learner.py | lgvaz/mantisshrimp2 | 743cb7df0dae7eb1331fc2bb66fc9ca09db496cd | [
"Apache-2.0"
] | 105 | 2020-09-09T10:41:35.000Z | 2022-03-25T17:16:49.000Z | __all__ = ["learner"]
from icevision.imports import *
from icevision.engines.fastai import *
from icevision.models.ultralytics.yolov5.fastai.callbacks import Yolov5Callback
from yolov5.utils.loss import ComputeLoss
def learner(
dls: List[Union[DataLoader, fastai.DataLoader]],
model: nn.Module,
cbs=None,
**learner_kwargs,
):
"""Fastai `Learner` adapted for Yolov5.
# Arguments
dls: `Sequence` of `DataLoaders` passed to the `Learner`.
The first one will be used for training and the second for validation.
model: The model to train.
cbs: Optional `Sequence` of callbacks.
**learner_kwargs: Keyword arguments that will be internally passed to `Learner`.
# Returns
A fastai `Learner`.
"""
cbs = [Yolov5Callback()] + L(cbs)
compute_loss = ComputeLoss(model)
def loss_fn(preds, targets) -> Tensor:
return compute_loss(preds, targets)[0]
learn = adapted_fastai_learner(
dls=dls,
model=model,
cbs=cbs,
loss_func=loss_fn,
**learner_kwargs,
)
# HACK: patch AvgLoss (in original, find_bs looks at learn.yb which has shape (N, 6) - with N being number_of_objects_in_image * batch_size. So impossible to retrieve BS)
class Yolov5AvgLoss(fastai.AvgLoss):
def accumulate(self, learn):
bs = len(learn.xb[0])
self.total += learn.to_detach(learn.loss.mean()) * bs
self.count += bs
recorder = [cb for cb in learn.cbs if isinstance(cb, fastai.Recorder)][0]
recorder.loss = Yolov5AvgLoss()
return learn
| 30.339623 | 174 | 0.65796 | 202 | 0.125622 | 0 | 0 | 0 | 0 | 0 | 0 | 602 | 0.374378 |
b3f30dc9a0925d6b62e87bf5f2f77956c0674d4f | 6,191 | py | Python | v0.5/training/image_classification/train.py | PhilippvK/tiny | 0b04bcd402ee28f84e79fa86d8bb8e731d9497b8 | [
"Apache-2.0"
] | 148 | 2020-11-30T19:27:25.000Z | 2022-03-31T18:12:35.000Z | v0.5/training/image_classification/train.py | PhilippvK/tiny | 0b04bcd402ee28f84e79fa86d8bb8e731d9497b8 | [
"Apache-2.0"
] | 113 | 2021-01-08T16:59:04.000Z | 2022-03-12T01:04:51.000Z | v0.5/training/image_classification/train.py | PhilippvK/tiny | 0b04bcd402ee28f84e79fa86d8bb8e731d9497b8 | [
"Apache-2.0"
] | 41 | 2020-11-25T01:32:43.000Z | 2022-03-28T18:10:22.000Z | '''
MLCommons
group: TinyMLPerf (https://github.com/mlcommons/tiny)
image classification on cifar10
train.py desc: loads data, trains and saves model, plots training metrics
'''
import numpy as np
import matplotlib.pyplot as plt
import pickle
import tensorflow as tf
from keras.callbacks import LearningRateScheduler
from keras.utils import to_categorical
import keras_model
import datetime
EPOCHS = 500
BS = 32
# get date ant time to save model
dt = datetime.datetime.today()
year = dt.year
month = dt.month
day = dt.day
hour = dt.hour
minute = dt.minute
"""
The CIFAR-10 dataset consists of 60000 32x32 colour images in 10 classes, with 6000 images per class. There are 50000
training images and 10000 test images.
The dataset is divided into five training batches and one test batch, each with 10000 images. The test batch contains
exactly 1000 randomly-selected images from each class. The training batches contain the remaining images in random
order, but some training batches may contain more images from one class than another. Between them, the training
batches contain exactly 5000 images from each class.
"""
#learning rate schedule
def lr_schedule(epoch):
initial_learning_rate = 0.001
decay_per_epoch = 0.99
lrate = initial_learning_rate * (decay_per_epoch ** epoch)
print('Learning rate = %f'%lrate)
return lrate
lr_scheduler = LearningRateScheduler(lr_schedule)
#optimizer
optimizer = tf.keras.optimizers.Adam()
#define data generator
datagen = tf.keras.preprocessing.image.ImageDataGenerator(
rotation_range=15,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=True,
#brightness_range=(0.9, 1.2),
#contrast_range=(0.9, 1.2),
validation_split=0.2
)
def unpickle(file):
"""load the cifar-10 data"""
with open(file, 'rb') as fo:
data = pickle.load(fo, encoding='bytes')
return data
def load_cifar_10_data(data_dir, negatives=False):
"""
Return train_data, train_filenames, train_labels, test_data, test_filenames, test_labels
"""
# get the meta_data_dict
# num_cases_per_batch: 1000
# label_names: ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
# num_vis: :3072
meta_data_dict = unpickle(data_dir + "/batches.meta")
cifar_label_names = meta_data_dict[b'label_names']
cifar_label_names = np.array(cifar_label_names)
# training data
cifar_train_data = None
cifar_train_filenames = []
cifar_train_labels = []
for i in range(1, 6):
cifar_train_data_dict = unpickle(data_dir + "/data_batch_{}".format(i))
if i == 1:
cifar_train_data = cifar_train_data_dict[b'data']
else:
cifar_train_data = np.vstack((cifar_train_data, cifar_train_data_dict[b'data']))
cifar_train_filenames += cifar_train_data_dict[b'filenames']
cifar_train_labels += cifar_train_data_dict[b'labels']
cifar_train_data = cifar_train_data.reshape((len(cifar_train_data), 3, 32, 32))
if negatives:
cifar_train_data = cifar_train_data.transpose(0, 2, 3, 1).astype(np.float32)
else:
cifar_train_data = np.rollaxis(cifar_train_data, 1, 4)
cifar_train_filenames = np.array(cifar_train_filenames)
cifar_train_labels = np.array(cifar_train_labels)
cifar_test_data_dict = unpickle(data_dir + "/test_batch")
cifar_test_data = cifar_test_data_dict[b'data']
cifar_test_filenames = cifar_test_data_dict[b'filenames']
cifar_test_labels = cifar_test_data_dict[b'labels']
cifar_test_data = cifar_test_data.reshape((len(cifar_test_data), 3, 32, 32))
if negatives:
cifar_test_data = cifar_test_data.transpose(0, 2, 3, 1).astype(np.float32)
else:
cifar_test_data = np.rollaxis(cifar_test_data, 1, 4)
cifar_test_filenames = np.array(cifar_test_filenames)
cifar_test_labels = np.array(cifar_test_labels)
return cifar_train_data, cifar_train_filenames, to_categorical(cifar_train_labels), \
cifar_test_data, cifar_test_filenames, to_categorical(cifar_test_labels), cifar_label_names
if __name__ == "__main__":
"""load cifar10 data and trains model"""
cifar_10_dir = 'cifar-10-batches-py'
train_data, train_filenames, train_labels, test_data, test_filenames, test_labels, label_names = \
load_cifar_10_data(cifar_10_dir)
print("Train data: ", train_data.shape)
print("Train filenames: ", train_filenames.shape)
print("Train labels: ", train_labels.shape)
print("Test data: ", test_data.shape)
print("Test filenames: ", test_filenames.shape)
print("Test labels: ", test_labels.shape)
print("Label names: ", label_names.shape)
# Don't forget that the label_names and filesnames are in binary and need conversion if used.
# display some random training images in a 25x25 grid
num_plot = 5
f, ax = plt.subplots(num_plot, num_plot)
for m in range(num_plot):
for n in range(num_plot):
idx = np.random.randint(0, train_data.shape[0])
ax[m, n].imshow(train_data[idx])
ax[m, n].get_xaxis().set_visible(False)
ax[m, n].get_yaxis().set_visible(False)
f.subplots_adjust(hspace=0.1)
f.subplots_adjust(wspace=0)
plt.show()
new_model = keras_model.resnet_v1_eembc()
new_model.summary()
# compute quantities required for featurewise normalization
# (std, mean, and principal components if ZCA whitening is applied)
datagen.fit(train_data)
new_model.compile(
optimizer=optimizer, loss='categorical_crossentropy', metrics='accuracy', loss_weights=None,
weighted_metrics=None, run_eagerly=None )
# fits the model on batches with real-time data augmentation:
History = new_model.fit(datagen.flow(train_data, train_labels, batch_size=BS),
steps_per_epoch=len(train_data) / BS, epochs=EPOCHS, callbacks=[lr_scheduler])
plt.plot(np.array(range(EPOCHS)), History.history['loss'])
plt.plot(np.array(range(EPOCHS)), History.history['accuracy'])
plt.savefig('train_loss_acc.png')
model_name = "trainedResnet.h5"
new_model.save("trained_models/" + model_name)
| 35.176136 | 118 | 0.719108 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,982 | 0.320142 |
b3f538d52ae1e6ef588876efeb6394fbd75aad99 | 435 | py | Python | setup.py | mchalek/timetools | 347d71c5b1b61b2e7f51b55b78717d046df0eac9 | [
"MIT"
] | null | null | null | setup.py | mchalek/timetools | 347d71c5b1b61b2e7f51b55b78717d046df0eac9 | [
"MIT"
] | null | null | null | setup.py | mchalek/timetools | 347d71c5b1b61b2e7f51b55b78717d046df0eac9 | [
"MIT"
] | null | null | null | from distutils.core import setup
setup(
name = 'timetools',
version = '1.0.0',
description = 'CL tools for timestamps',
author = 'Kevin McHale',
author_email = 'mchalek@gmail.com',
url = 'https://github.com/mchalek/timetools',
scripts = [
'bin/now',
'bin/when',
'bin/ts',
'bin/daysago',
'bin/hoursago',
])
| 25.588235 | 53 | 0.482759 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 168 | 0.386207 |
b3f6ce75fce86c23d25fbd7afbc4444019de0a95 | 2,601 | py | Python | src/tests/web/web_auth_utils_test.py | tomgilbertson/script-server-v1 | bbdf289d3d993a0c81f20c36bce5f3eb064b0261 | [
"Apache-2.0",
"CC0-1.0"
] | 833 | 2016-09-08T13:27:36.000Z | 2022-03-27T07:10:48.000Z | src/tests/web/web_auth_utils_test.py | tomgilbertson/script-server-v1 | bbdf289d3d993a0c81f20c36bce5f3eb064b0261 | [
"Apache-2.0",
"CC0-1.0"
] | 528 | 2016-05-23T09:17:04.000Z | 2022-03-30T12:45:50.000Z | src/tests/web/web_auth_utils_test.py | tomgilbertson/script-server-v1 | bbdf289d3d993a0c81f20c36bce5f3eb064b0261 | [
"Apache-2.0",
"CC0-1.0"
] | 214 | 2016-09-08T14:46:41.000Z | 2022-03-25T01:04:14.000Z | from unittest import TestCase
from parameterized import parameterized
from tests.test_utils import mock_request_handler
from web.web_auth_utils import remove_webpack_suffixes, is_allowed_during_login
class WebpackSuffixesTest(TestCase):
def test_remove_webpack_suffixes_when_css(self):
normalized = remove_webpack_suffixes('js/chunk-login-vendors.59040343.css')
self.assertEqual('js/chunk-login-vendors.css', normalized)
def test_remove_webpack_suffixes_when_js(self):
normalized = remove_webpack_suffixes('js/login.be16f278.js')
self.assertEqual('js/login.js', normalized)
def test_remove_webpack_suffixes_when_js_map(self):
normalized = remove_webpack_suffixes('js/login.be16f278.js.map')
self.assertEqual('js/login.js.map', normalized)
def test_remove_webpack_suffixes_when_favicon(self):
normalized = remove_webpack_suffixes('favicon.123.ico')
self.assertEqual('favicon.123.ico', normalized)
def test_remove_webpack_suffixes_when_no_suffixes(self):
normalized = remove_webpack_suffixes('css/chunk-login-vendors.css')
self.assertEqual('css/chunk-login-vendors.css', normalized)
def test_remove_webpack_suffixes_when_no_extension(self):
normalized = remove_webpack_suffixes('data/some_file')
self.assertEqual('data/some_file', normalized)
class LoginResourcesTest(TestCase):
@parameterized.expand([
('/favicon.ico'),
('login.html'),
('/js/login.be16f278.js'),
('/js/login.be16f278.js.map'),
('/js/chunk-login-vendors.18e22e7f.js'),
('/js/chunk-login-vendors.18e22e7f.js.map'),
('/img/titleBackground_login.a6c36d4c.jpg'),
('/css/login.8e74be0f.css'),
('/fonts/roboto-latin-400.60fa3c06.woff'),
('/fonts/roboto-latin-400.479970ff.woff2'),
('/fonts/roboto-latin-500.020c97dc.woff2'),
('/fonts/roboto-latin-500.87284894.woff')
])
def test_is_allowed_during_login_when_allowed(self, resource):
request_handler = mock_request_handler(method='GET')
allowed = is_allowed_during_login(resource, 'login.html', request_handler)
self.assertTrue(allowed, 'Resource ' + resource + ' should be allowed, but was not')
def test_is_allowed_during_login_when_prohibited(self):
request_handler = mock_request_handler(method='GET')
resource = 'admin.html'
allowed = is_allowed_during_login(resource, 'login.html', request_handler)
self.assertFalse(allowed, 'Resource ' + resource + ' should NOT be allowed, but WAS')
| 41.951613 | 93 | 0.715494 | 2,393 | 0.920031 | 0 | 0 | 856 | 0.329104 | 0 | 0 | 779 | 0.2995 |
b3f7e6c22b6c9794a41aee33552f02308c3e5c81 | 334 | py | Python | home/migrations/0020_remove_comment_content_type.py | yys534640040/blog | 5489506593a4c496856cb197c6eeee0b9d0c7422 | [
"MIT"
] | null | null | null | home/migrations/0020_remove_comment_content_type.py | yys534640040/blog | 5489506593a4c496856cb197c6eeee0b9d0c7422 | [
"MIT"
] | 1 | 2020-07-12T11:36:06.000Z | 2020-07-16T22:58:18.000Z | home/migrations/0020_remove_comment_content_type.py | yys534640040/blog | 5489506593a4c496856cb197c6eeee0b9d0c7422 | [
"MIT"
] | null | null | null | # Generated by Django 3.0.5 on 2020-07-03 20:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('home', '0019_comment_content_type'),
]
operations = [
migrations.RemoveField(
model_name='comment',
name='content_type',
),
]
| 18.555556 | 47 | 0.598802 | 249 | 0.745509 | 0 | 0 | 0 | 0 | 0 | 0 | 103 | 0.308383 |
b3f8cd4ae912dbdd73c9929061b57c0026f34e20 | 394 | py | Python | maldives/bot/models/price.py | filipecn/maldives | f20f17d817fc3dcad7f9674753744716d1d4c821 | [
"MIT"
] | 1 | 2021-09-17T18:04:33.000Z | 2021-09-17T18:04:33.000Z | maldives/bot/models/price.py | filipecn/maldives | f20f17d817fc3dcad7f9674753744716d1d4c821 | [
"MIT"
] | null | null | null | maldives/bot/models/price.py | filipecn/maldives | f20f17d817fc3dcad7f9674753744716d1d4c821 | [
"MIT"
] | 3 | 2021-09-17T18:04:43.000Z | 2022-03-18T20:04:07.000Z | from datetime import datetime
class Price:
date: datetime = datetime(1, 1, 1)
currency: str = 'BRL'
symbol: str = ''
current: float = 0
open: float = 0
close: float = 0
low: float = 0
high: float = 0
volume: float = 0
interval: str = ''
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
| 20.736842 | 41 | 0.563452 | 361 | 0.916244 | 0 | 0 | 0 | 0 | 0 | 0 | 9 | 0.022843 |
b3f9ba735a60d3a089be5c0016638eb41035164c | 1,700 | py | Python | components/collector/src/source_collectors/trello/base.py | kargaranamir/quality-time | 1c427c61bee9d31c3526f0a01be2218a7e167c23 | [
"Apache-2.0"
] | 33 | 2016-01-20T07:35:48.000Z | 2022-03-14T09:20:51.000Z | components/collector/src/source_collectors/trello/base.py | kargaranamir/quality-time | 1c427c61bee9d31c3526f0a01be2218a7e167c23 | [
"Apache-2.0"
] | 2,410 | 2016-01-22T18:13:01.000Z | 2022-03-31T16:57:34.000Z | components/collector/src/source_collectors/trello/base.py | kargaranamir/quality-time | 1c427c61bee9d31c3526f0a01be2218a7e167c23 | [
"Apache-2.0"
] | 21 | 2016-01-16T11:49:23.000Z | 2022-01-14T21:53:22.000Z | """Trello metric collector base classes."""
from abc import ABC
from base_collectors import SourceCollector
from collector_utilities.type import URL
from model import SourceResponses
class TrelloBase(SourceCollector, ABC): # pylint: disable=abstract-method
"""Base class for Trello collectors."""
async def _landing_url(self, responses: SourceResponses) -> URL:
"""Override to get the landing URL from the response."""
return URL((await responses[0].json())["url"] if responses else "https://trello.com")
async def _get_source_responses(self, *urls: URL, **kwargs) -> SourceResponses:
"""Extend to add authentication and field parameters to the URL."""
api = (
f"1/boards/{await self.__board_id()}?fields=id,url,dateLastActivity&lists=open&"
"list_fields=name&cards=visible&card_fields=name,dateLastActivity,due,idList,url"
)
return await super()._get_source_responses(await self.__url_with_auth(api), **kwargs)
async def __board_id(self) -> str:
"""Return the id of the board specified by the user."""
url = await self.__url_with_auth("1/members/me/boards?fields=name")
boards = await (await super()._get_source_responses(url))[0].json()
return str([board for board in boards if self._parameter("board") in board.values()][0]["id"])
async def __url_with_auth(self, api_part: str) -> URL:
"""Return the authentication URL parameters."""
sep = "&" if "?" in api_part else "?"
api_key = self._parameter("api_key")
token = self._parameter("token")
return URL(f"{await self._api_url()}/{api_part}{sep}key={api_key}&token={token}")
| 45.945946 | 102 | 0.677647 | 1,512 | 0.889412 | 0 | 0 | 0 | 0 | 1,370 | 0.805882 | 664 | 0.390588 |
b3f9bcec38c9a72781e8e70499e37a556328642c | 3,248 | py | Python | keylib/private_key.py | Wealize/keylib-py | c7021771449b8f983d6731e8bbf23ca657ba0ff8 | [
"MIT"
] | 10 | 2016-03-20T10:41:27.000Z | 2020-11-12T11:10:15.000Z | keylib/private_key.py | Wealize/keylib-py | c7021771449b8f983d6731e8bbf23ca657ba0ff8 | [
"MIT"
] | 4 | 2016-12-21T00:53:22.000Z | 2020-03-08T06:22:24.000Z | keylib/private_key.py | Wealize/keylib-py | c7021771449b8f983d6731e8bbf23ca657ba0ff8 | [
"MIT"
] | 16 | 2016-06-01T19:42:35.000Z | 2021-11-24T07:35:25.000Z | # -*- coding: utf-8 -*-
"""
pybitcoin
~~~~~
:copyright: (c) 2014 by Halfmoon Labs
:license: MIT, see LICENSE for more details.
"""
import os
import json
import hashlib
import ecdsa
from binascii import hexlify, unhexlify
from ecdsa.keys import SigningKey
from .key_formatting import compress, encode_privkey, get_privkey_format
from .b58check import b58check_encode, b58check_decode
from .public_key import ECPublicKey
from .utils import (
random_secret_exponent, is_secret_exponent, PUBLIC_KEY_MAGIC_BYTE
)
class ECPrivateKey():
_curve = ecdsa.curves.SECP256k1
_hash_function = hashlib.sha256
_pubkeyhash_version_byte = 0
def __init__(self, private_key=None, compressed=True):
""" Takes in a private key/secret exponent.
"""
self._compressed = compressed
if not private_key:
secret_exponent = random_secret_exponent(self._curve.order)
else:
secret_exponent = encode_privkey(private_key, 'decimal')
# make sure that: 1 <= secret_exponent < curve_order
if not is_secret_exponent(secret_exponent, self._curve.order):
raise IndexError(
("Secret exponent is outside of the valid range."
"Must be >= 1 and < the curve order."))
self._ecdsa_private_key = ecdsa.keys.SigningKey.from_secret_exponent(
secret_exponent, self._curve, self._hash_function
)
@classmethod
def wif_version_byte(cls):
if hasattr(cls, '_wif_version_byte'):
return cls._wif_version_byte
return (cls._pubkeyhash_version_byte + 128) % 256
def to_bin(self):
if self._compressed:
return encode_privkey(
self._ecdsa_private_key.to_string(), 'bin_compressed')
else:
return self._ecdsa_private_key.to_string()
def to_hex(self):
if self._compressed:
return encode_privkey(
self._ecdsa_private_key.to_string(), 'hex_compressed')
else:
return hexlify(self.to_bin())
def to_wif(self):
if self._compressed:
return encode_privkey(
self._ecdsa_private_key.to_string(), 'wif_compressed', vbyte=self._pubkeyhash_version_byte)
else:
return b58check_encode(
self.to_bin(), version_byte=self.wif_version_byte())
def to_pem(self):
return self._ecdsa_private_key.to_pem()
def to_der(self):
return hexlify(self._ecdsa_private_key.to_der())
def public_key(self):
# lazily calculate and set the public key
if not hasattr(self, '_public_key'):
ecdsa_public_key = self._ecdsa_private_key.get_verifying_key()
bin_public_key_string = "%s%s" % (
PUBLIC_KEY_MAGIC_BYTE, ecdsa_public_key.to_string())
if self._compressed:
bin_public_key_string = compress(bin_public_key_string)
# create the public key object from the public key string
self._public_key = ECPublicKey(
bin_public_key_string,
version_byte=self._pubkeyhash_version_byte)
# return the public key object
return self._public_key
| 32.158416 | 107 | 0.652401 | 2,714 | 0.835591 | 0 | 0 | 188 | 0.057882 | 0 | 0 | 561 | 0.172722 |
b3fa02a8b8024f77ab62c64666d2d920b50e4c95 | 2,087 | py | Python | testcase/T_requests.py | jacktan1016/InnerAutoTest_W | d8b6304223c71d23cf093cba28060b4a2a838e2b | [
"MIT"
] | null | null | null | testcase/T_requests.py | jacktan1016/InnerAutoTest_W | d8b6304223c71d23cf093cba28060b4a2a838e2b | [
"MIT"
] | null | null | null | testcase/T_requests.py | jacktan1016/InnerAutoTest_W | d8b6304223c71d23cf093cba28060b4a2a838e2b | [
"MIT"
] | null | null | null | import json
import requests
from utils.RequestsUtil import RequestsUtil
from config.Conf import ConfYaml
import os
request_util = RequestsUtil()
conf = ConfYaml()
def login():
url = os.path.join(conf.get_yaml_data(),"authorizations/")
# url = "http://211.103.136.242:8064/authorizations/"
data = {"username": "python", "password": "12345678"}
# r = requests.post(url, data=data)
r = request_util.requests_api(url,method="post",json=data)
return r
def info(token):
url = os.path.join(conf.get_yaml_data(),"user/")
# url = "http://211.103.136.242:8064/user/"
headers = {
"Authorization":"JWT "+token
}
return request_util.requests_api(url,headers=headers)
# r = requests.get(url,headers=headers)
# print(r.json())
def cate():
url = os.path.join(conf.get_yaml_data(),"categories/115/skus/")
# url = "http://211.103.136.242:8064/categories/115/skus/"
data = {"page":"1","page_size":"10","ording":"create_time"}
return request_util.requests_api(url,json=data)
# r = requests.get(url,params=data)
# print(r.json())
def cart(token):
url = os.path.join(conf.get_yaml_data(),"cart/")
# url = "http://211.103.136.242:8064/cart/"
data = {"sku_id":"3","count":"1","selected":"true"}
headers = {
"Authorization": "JWT " + token
}
return request_util.requests_api(url,method="post",headers=headers,json=data)
# r = requests.post(url,data=data,headers=headers)
# print(r.json())
def order(token):
url = "http://211.103.136.242:8064/orders/"
data = {"address":"1","pay_method":"1"}
headers = {
"Authorization": "JWT " + token
}
r = requests.post(url,data=data,headers=headers)
print(r.json())
if __name__=="__main__":
# 首先登录,获取token
r = login()
print(r)
# # 获取token
str_token = r['body']['token']
info_data = info(str_token)
print(info_data)
cate = cate()
print("cate接口相关数据:{}".format(cate))
# # 拿着token到用户中心
cart = cart(str_token)
print("cart接口相关数据:{}".format(cart))
# order(str_token) | 29.394366 | 81 | 0.631049 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 887 | 0.413906 |
b3fab383b142152824ae9a6267327c0e43da466f | 1,340 | py | Python | pluto_navigation/scripts/wait_for_goal.py | SabrinaFrohn/mesh_navigation | 6949a62e4656f99f5d0dcda7419e269dbbe9058e | [
"BSD-3-Clause"
] | null | null | null | pluto_navigation/scripts/wait_for_goal.py | SabrinaFrohn/mesh_navigation | 6949a62e4656f99f5d0dcda7419e269dbbe9058e | [
"BSD-3-Clause"
] | null | null | null | pluto_navigation/scripts/wait_for_goal.py | SabrinaFrohn/mesh_navigation | 6949a62e4656f99f5d0dcda7419e269dbbe9058e | [
"BSD-3-Clause"
] | null | null | null | import rospy
import smach
import threading
from geometry_msgs.msg import PoseStamped
class WaitForGoal(smach.State):
def __init__(self):
smach.State.__init__(self, outcomes=['received_goal', 'preempted'], input_keys=[], output_keys=['target_pose'])
self.target_pose = PoseStamped()
self.signal = threading.Event()
self.subscriber = None
def execute(self, user_data):
rospy.loginfo("Waiting for a goal...")
self.signal.clear()
self.subscriber = rospy.Subscriber('/goal', PoseStamped, self.goal_callback)
while not rospy.is_shutdown() and not self.signal.is_set() and not self.preempt_requested():
rospy.logdebug("Waiting for a goal...")
self.signal.wait(1)
if self.preempt_requested() or rospy.is_shutdown():
self.service_preempt()
return 'preempted'
user_data.target_pose = self.target_pose
pos = self.target_pose.pose.position
rospy.loginfo("Received goal pose: (%s, %s, %s)", pos.x, pos.y, pos.z)
return 'received_goal'
def goal_callback(self, msg):
rospy.logdebug("Received goal pose: %s", str(msg))
self.target_pose = msg
self.signal.set()
def request_preempt(self):
smach.State.request_preempt(self)
self.signal.set() | 32.682927 | 119 | 0.645522 | 1,253 | 0.935075 | 0 | 0 | 0 | 0 | 0 | 0 | 176 | 0.131343 |
b3fbdad4ed64cfcecd3fb0cb6ae4bd8c65572b8e | 348 | py | Python | filesystems/click.py | Julian/Filesystems | 8c758c8dbbe1263b2ad574ccb8e2c81c865c0a61 | [
"MIT"
] | 2 | 2017-04-17T18:30:15.000Z | 2018-05-05T23:11:06.000Z | filesystems/click.py | Julian/Filesystems | 8c758c8dbbe1263b2ad574ccb8e2c81c865c0a61 | [
"MIT"
] | 46 | 2016-09-11T19:40:49.000Z | 2020-02-05T01:49:34.000Z | filesystems/click.py | Julian/Filesystems | 8c758c8dbbe1263b2ad574ccb8e2c81c865c0a61 | [
"MIT"
] | 4 | 2017-01-13T14:47:00.000Z | 2020-01-17T00:45:49.000Z | """
Click support for `filesystems.Path`.
"""
from __future__ import absolute_import
import click
import filesystems
class Path(click.ParamType):
name = "path"
def convert(self, value, param, context):
if not isinstance(value, str):
return value
return filesystems.Path.from_string(value)
PATH = Path()
| 15.130435 | 50 | 0.672414 | 209 | 0.600575 | 0 | 0 | 0 | 0 | 0 | 0 | 51 | 0.146552 |
b6029e5c3de03586995e695f33d08198c6b3bcec | 4,639 | py | Python | equilibrium-propagation/numpy_one_layer.py | jiangdaniel/dl-papers | ca85708b5629dc1ba22ec1dfc023d3a6267b0d34 | [
"MIT"
] | 1 | 2019-03-26T12:19:59.000Z | 2019-03-26T12:19:59.000Z | equilibrium-propagation/numpy_one_layer.py | jiangdaniel/ml-implementations | ca85708b5629dc1ba22ec1dfc023d3a6267b0d34 | [
"MIT"
] | 5 | 2018-11-26T05:48:52.000Z | 2018-11-26T05:50:45.000Z | equilibrium-propagation/numpy_one_layer.py | jiangdaniel/ml-implementations | ca85708b5629dc1ba22ec1dfc023d3a6267b0d34 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import numpy as np
import torch as th
import torchvision
from tqdm import tqdm
def main(args):
trainloader, testloader = get_loaders(args.batch_size, args.fashion)
epsilon = 0.5
beta = 1.0
alpha1 = 0.1
alpha2 = 0.05
a = np.sqrt(2.0 / (784 + 500))
W1 = np.random.uniform(-a, a, (784, 500))
b1 = np.random.uniform(-a, a, 500)
a = np.sqrt(2.0 / (500 + 10))
W2 = np.random.uniform(-a, a, (500, 10))
b2 = np.random.uniform(-a, a, 10)
states = [(np.random.uniform(0, 1., (args.batch_size, 500)), \
np.random.uniform(0, 1., (args.batch_size, 10))) for _ in range(len(trainloader))]
for epoch in range(args.epochs):
running_loss = running_energy = running_true_positive = 0.
for i, (x, labels) in enumerate(tqdm(trainloader, desc=f"Epoch {epoch}")):
x, labels = x.view(-1, 784).numpy(), labels.numpy()
h, y = states[i]
# Free phase
for j in range(20):
dh = d_rho(h) * (x @ W1 + y @ W2.T + b1) - h
dy = d_rho(y) * (h @ W2 + b2) - y
h = rho(h + epsilon * dh)
y = rho(y + epsilon * dy)
'''
energy = (np.square(h).sum() + np.square(y).sum() \
- (W1 * (x.T @ h)).sum() - (W2 * (h.T @ y)).sum()) / 2 \
- (h @ b1).sum() - (y @ b2).sum())
print(np.round(energy, 4), np.round(np.linalg.norm(dh), 4))
'''
h_free, y_free = np.copy(h), np.copy(y)
states[i] = h_free, y_free
t = np.zeros((x.shape[0], 10))
t[np.arange(t.shape[0]), labels] = 1
# Weakly clamped phase
for j in range(4):
dh = d_rho(h) * (x @ W1 + y @ W2.T + b1) - h
dy = d_rho(y) * (h @ W2 + b2) - y + beta * (t - y)
h = rho(h + epsilon * dh)
y = rho(y + epsilon * dy)
'''
energy = (np.square(h).sum() + np.square(y).sum() \
- (W1 * (x.T @ h)).sum() - (W2 * (h.T @ y)).sum()) / 2 \
- (h @ b1).sum() - (y @ b2).sum()
print(np.round(energy, 4), np.round(np.linalg.norm(dh), 4))
'''
h_clamped = np.copy(h)
y_clamped = np.copy(y)
W1 += alpha1 / beta * (rho(x.T) @ rho(h_clamped) - rho(x.T) @ rho(h_free)) / args.batch_size
W2 += alpha2 / beta * (rho(h_clamped.T) @ rho(y_clamped) - rho(h_free.T) @ rho(y_free)) / args.batch_size
b1 += alpha1 / beta * (rho(h_clamped) - rho(h_free)).mean(0)
b2 += alpha2 / beta * (rho(y_clamped) - rho(y_free)).mean(0)
running_energy += (np.square(h_free).sum() + np.square(y_free).sum() \
- (W1 * (x.T @ h_free)).sum() - (W2 * (h_free.T @ y_free)).sum()) / 2 \
- (h_free @ b1).sum() - (y_free @ b2).sum()
running_loss += np.square(t - y_free).sum()
running_true_positive += np.count_nonzero(np.argmax(y_free, 1) == labels)
energy_avg = running_energy / (len(trainloader) * args.batch_size)
accuracy_avg = running_true_positive / (len(trainloader) * args.batch_size)
loss_avg = running_loss / (len(trainloader) * args.batch_size)
print(f"Energy: {energy_avg}, Accuracy: {accuracy_avg}, Loss: {loss_avg}")
def rho(x):
return np.copy(np.clip(x, 0., 1.))
def d_rho(x):
return (x >= 0.) * (x <= 1.)
def get_loaders(batch_size, fashion=False):
mnist = torchvision.datasets.MNIST
if fashion:
mnist = torchvision.datasets.FashionMNIST
transform = torchvision.transforms.Compose(
[torchvision.transforms.ToTensor(),])
trainloader = th.utils.data.DataLoader(
mnist(root="./data", train=True, download=True, transform=transform),
batch_size=batch_size,
shuffle=True,
num_workers=2)
testloader = th.utils.data.DataLoader(
mnist(root="./data", train=False, download=True, transform=transform),
batch_size=batch_size,
shuffle=False,
num_workers=2)
return trainloader, testloader
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--epochs", type=int, default=1000)
parser.add_argument("--batch-size", type=int, default=20)
parser.add_argument("--fashion", action="store_true", default=False)
args = parser.parse_args()
main(args)
| 36.527559 | 117 | 0.538047 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 809 | 0.174391 |
b602a5e9115de37b8d2d657582d79704b2d23cd3 | 605 | py | Python | atc53/rule/weighted.py | cloudtools/atc53 | 1c7b9a0f52a18adab3cc32deff42b4b4ec6276fd | [
"BSD-2-Clause"
] | 3 | 2018-11-13T21:54:57.000Z | 2019-04-16T08:04:58.000Z | atc53/rule/weighted.py | cloudtools/atc53 | 1c7b9a0f52a18adab3cc32deff42b4b4ec6276fd | [
"BSD-2-Clause"
] | 1 | 2018-07-17T13:56:40.000Z | 2018-07-17T15:14:29.000Z | atc53/rule/weighted.py | cloudtools/atc53 | 1c7b9a0f52a18adab3cc32deff42b4b4ec6276fd | [
"BSD-2-Clause"
] | 2 | 2020-11-21T19:02:22.000Z | 2021-02-11T11:33:43.000Z | from atc53 import BaseAWSObject, AWSProperty
class WeightedItem(AWSProperty):
props = {
'EndpointReference': (basestring, False),
'RuleReference': (basestring, False),
'Weight': (basestring, True),
'EvaluateTargetHealth': (bool, False),
'HealthCheck': (basestring, False)
}
def validate(self):
if not self.properties.get('Weight') in range(0, 255):
raise ValueError('Weighted value not in range of 0-255')
class WeightedRule(BaseAWSObject):
rule_type = 'weighted'
props = {
'Items': ([WeightedItem], True)
}
| 26.304348 | 68 | 0.624793 | 554 | 0.915702 | 0 | 0 | 0 | 0 | 0 | 0 | 140 | 0.231405 |
b60351063710a533911517acf4f3365c7b83f4ec | 4,621 | py | Python | radiation/python/scripts/record_random_walk.py | dfridovi/exploration | 5e66115178988bd264a920041dfeab6d3539caec | [
"BSD-3-Clause"
] | 5 | 2018-07-08T08:32:49.000Z | 2022-03-13T10:17:09.000Z | radiation/python/scripts/record_random_walk.py | dfridovi/exploration | 5e66115178988bd264a920041dfeab6d3539caec | [
"BSD-3-Clause"
] | 5 | 2016-11-30T02:52:58.000Z | 2018-05-24T04:46:49.000Z | radiation/python/scripts/record_random_walk.py | dfridovi/exploration | 5e66115178988bd264a920041dfeab6d3539caec | [
"BSD-3-Clause"
] | 2 | 2016-12-01T04:06:40.000Z | 2019-06-19T16:32:28.000Z | """
Copyright (c) 2015, The Regents of the University of California (Regents).
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Please contact the author(s) of this library if you have any questions.
Authors: David Fridovich-Keil ( dfk@eecs.berkeley.edu )
"""
###########################################################################
#
# Record a dataset of map, successive poses, and corresponding measurements.
# The dataset will contain many such groups.
#
###########################################################################
from grid_pose_2d import GridPose2D
from source_2d import Source2D
from sensor_2d import Sensor2D
from encoding import *
import numpy as np
import math
# File to save to.
maps_file = "maps.csv"
trajectories_file = "trajectories.csv"
measurements_file = "measurements.csv"
# Define hyperparameters.
kNumSimulations = 100000
kNumRows = 5
kNumCols = 5
kNumSources = 3
kNumSteps = 10
kNumAngles = 8
kAngularStep = 2.0 * math.pi / float(kNumAngles)
kSensorParams = {"x" : kNumRows/2,
"y" : kNumCols/2,
"angle" : 0.0,
"fov" : 0.5 * math.pi}
delta_xs = [-1, 0, 1]
delta_ys = [-1, 0, 1]
delta_as = [-kAngularStep, 0, kAngularStep]
# Run the specified number of simulations.
maps = np.zeros(kNumSimulations)
trajectories = np.zeros((kNumSimulations, kNumSteps))
measurements = np.zeros((kNumSimulations, kNumSteps))
for ii in range(kNumSimulations):
# Generate random sources on the grid.
sources = []
for jj in range(kNumSources):
x = float(np.random.random_integers(0, kNumRows-1)) + 0.5
y = float(np.random.random_integers(0, kNumCols-1)) + 0.5
sources.append(Source2D(x, y))
sensor = Sensor2D(kSensorParams, sources)
maps[ii] = EncodeMap(kNumRows, kNumCols, sources)
# Generate a valid trajectory of the given length.
step_counter = 0
current_pose = GridPose2D(kNumRows, kNumCols,
int(np.random.uniform(0.0, kNumRows)) + 0.5,
int(np.random.uniform(0.0, kNumCols)) + 0.5,
np.random.uniform(0.0, 2.0 * math.pi))
while step_counter < kNumSteps:
dx = np.random.choice(delta_xs)
dy = np.random.choice(delta_ys)
da = np.random.choice(delta_as)
next_pose = GridPose2D.Copy(current_pose)
if next_pose.MoveBy(dx, dy, da):
# If a valid move, append to list.
trajectories[ii, step_counter] = (int(next_pose.x_) +
int(next_pose.y_) * kNumRows +
(int(next_pose.angle_ / kAngularStep)
% kNumAngles) * kNumRows * kNumAngles)
current_pose = next_pose
# Get a measurement.
sensor.ResetPose(current_pose)
measurements[ii, step_counter] = sensor.Sense()
step_counter += 1
# Save to disk.
np.savetxt(maps_file, maps, delimiter=",")
np.savetxt(trajectories_file, trajectories, delimiter=",")
np.savetxt(measurements_file, measurements, delimiter=",")
print "Successfully saved to disk."
| 39.161017 | 85 | 0.662194 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,322 | 0.502489 |
b60438c61cd249fe3929938054963bdf3af1ba35 | 2,149 | py | Python | setup.py | nokx5/speedo | 23d42bd6148eef845d7f11c992b17ae1bc2fbd6d | [
"MIT"
] | null | null | null | setup.py | nokx5/speedo | 23d42bd6148eef845d7f11c992b17ae1bc2fbd6d | [
"MIT"
] | null | null | null | setup.py | nokx5/speedo | 23d42bd6148eef845d7f11c992b17ae1bc2fbd6d | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# mypy: ignore-errors
#
#
# Speedo
#
#
import os
from setuptools import setup, find_namespace_packages
from speedo_common.version import speedo_version as __version__
def get_requirements(filename: str):
"""Build the requirements list from the filename"""
requirements_list = []
with open(filename, "r") as reqs:
for install in reqs:
requirements_list.append(install.strip())
return requirements_list
if os.getenv("SPEEDO_TARGET", "") == "client":
setup(
name="Speedo - python client library",
version=__version__,
description="Speedo - python client library",
url="https://www.nokx.ch",
author="nokx",
author_email="info@nokx.ch",
packages=find_namespace_packages(include=["speedo_client.*"])
+ find_namespace_packages(include=["speedo_common.*"])
+ ["speedo_client", "speedo_common"],
install_requires=get_requirements("requirements_client.txt"),
python_requires=">=3",
)
elif os.getenv("SPEEDO_TARGET", "") == "server":
setup(
name="Speedo - server",
version=__version__,
description="Speedo - a fast RESTful web API",
url="https://www.nokx.ch",
author="nokx",
author_email="info@nokx.ch",
scripts=["scripts/speedo"],
package_data={"": ["alembic.ini"]},
packages=find_namespace_packages(include=["speedo_server.*"])
+ find_namespace_packages(include=["speedo_common.*"])
+ ["speedo_server", "speedo_common"],
install_requires=get_requirements("requirements_server.txt"),
python_requires=">=3",
)
else:
raise EnvironmentError(
"Please target the following environment variable"
"\n\n\t"
"$ export SPEEDO_TARGET=server # or"
"\n\t"
"$ export SPEEDO_TARGET=client"
"\n\n"
"before running the installation"
"\n\n\t"
"$ python setup.py install --prefix=/tmp/destination"
"\n\t"
"$ # you can use pip instead (use a virtualenv)"
"\n\t"
"$ pip install ."
"\n"
)
| 30.267606 | 69 | 0.614705 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 885 | 0.411819 |
b604cff0636c7f5ed2000c437822c2e55deb7a04 | 5,307 | py | Python | model.py | NerdToMars/Fringe-pattern-denoising-based-on-deep-learning | 23dea6bcd4d43568d458cb3ac748dbd5cd7d0cf2 | [
"BSD-2-Clause"
] | 5 | 2019-03-01T07:42:29.000Z | 2021-04-18T16:47:06.000Z | model.py | NerdToMars/Fringe-pattern-denoising-based-on-deep-learning | 23dea6bcd4d43568d458cb3ac748dbd5cd7d0cf2 | [
"BSD-2-Clause"
] | null | null | null | model.py | NerdToMars/Fringe-pattern-denoising-based-on-deep-learning | 23dea6bcd4d43568d458cb3ac748dbd5cd7d0cf2 | [
"BSD-2-Clause"
] | 5 | 2019-01-10T20:59:14.000Z | 2020-09-15T01:33:19.000Z | """ This script demonstrates the use of a convolutional LSTM network.
This network is used to predict the next frame of an artificially
generated movie which contains moving squares.
"""
from keras.models import Sequential
from keras.layers.convolutional import Conv3D
from keras.layers.convolutional_recurrent import ConvLSTM2D
from keras.layers.normalization import BatchNormalization
import numpy as np
import pylab as plt
import skimage.transform
import tensorflow as tf
import keras
import keras.backend as K
import keras.layers as KL
import keras.engine as KE
import keras.models as KM
from keras.models import *
from keras.layers import *
from keras.optimizers import *
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras import backend as keras
def getBiConvLSTM2d(input_image,filters,kernel_size,name):
L1 = KL.Bidirectional(KL.ConvLSTM2D(filters=filters, kernel_size=kernel_size,activation='relu', padding='same', return_sequences=True))(input_image)
L1 = KL.BatchNormalization(name="batchNormL_"+name)(L1)
return L1
def unet(inputs):
conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)
conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1)
conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2)
conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3)
pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3)
conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4)
drop4 = Dropout(0.5)(conv4)
print(conv4)
pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)
conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4)
conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5)
drop5 = Dropout(0.5)(conv5)
up6 = Conv2D(512, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5))
print(drop4)
print(up6)
merge6 = concatenate([drop4,up6], axis = 3)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6)
up7 = Conv2D(256, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6))
merge7 = concatenate([conv3,up7], axis = 3)
conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7)
conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7)
up8 = Conv2D(128, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7))
merge8 = concatenate([conv2,up8], axis = 3)
conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8)
conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8)
up9 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8))
merge9 = concatenate([conv1,up9], axis = 3)
conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9)
conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)
conv9 = Conv2D(2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)
conv10 = Conv2D(1, 1, activation = 'sigmoid')(conv9)
return conv10
def LSTMUnet():
'''
Input frame, with size 8*256*256*1 numpy array
'''
row = 256
col = 256
input_image = KL.Input(shape=[8, row,col,1], name="input_image")
L4 = input_image
for i in range(3):
L4 = getBiConvLSTM2d(L4,filters=20, kernel_size=(3, 3),name='top'+str(i))
L5 = KL.Conv3D(filters=8, kernel_size=(3, 3, 8),
activation='relu',
padding='same', data_format='channels_last')(L4)
# L5 = KL.BatchNormalization(name="batchNormL_sel5")(L5)
L6 = KL.Conv3D(filters=1, kernel_size=(3, 3, 4),
activation='relu',
padding='same', data_format='channels_last')(L5)
L6 = KL.BatchNormalization(name="batchNormL_sel5")(L6)
L7 = KL.Conv3D(filters=1, kernel_size=(3, 3, 8),
activation='relu',
padding='same', data_format='channels_first')(L6)
L7 = Reshape((row,col,1))(L7)
seg = unet(L7)
model = KM.Model(input_image,seg)
model.compile(loss='mean_squared_error', optimizer='adadelta')
return model
| 50.066038 | 152 | 0.679292 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,014 | 0.191068 |
b60524371592fc13a90a092bd41622fae9b2911d | 5,795 | py | Python | Advent2019/14.py | SSteve/AdventOfCode | aed16209381ccd292fc02008f1f2da5d16ff1a05 | [
"MIT"
] | null | null | null | Advent2019/14.py | SSteve/AdventOfCode | aed16209381ccd292fc02008f1f2da5d16ff1a05 | [
"MIT"
] | null | null | null | Advent2019/14.py | SSteve/AdventOfCode | aed16209381ccd292fc02008f1f2da5d16ff1a05 | [
"MIT"
] | null | null | null | #I couldn't figure this one out so I copied the solution from https://github.com/joelgrus/advent2019/blob/master/day14/day14.py
from __future__ import annotations
import math
import re
from collections import defaultdict
from typing import Iterable, List, NamedTuple, Dict
REACTIONS1 = """10 ORE => 10 A
1 ORE => 1 B
7 A, 1 B => 1 C
7 A, 1 C => 1 D
7 A, 1 D => 1 E
7 A, 1 E => 1 FUEL"""
REACTIONS2 = """9 ORE => 2 A
8 ORE => 3 B
7 ORE => 5 C
3 A, 4 B => 1 AB
5 B, 7 C => 1 BC
4 C, 1 A => 1 CA
2 AB, 3 BC, 4 CA => 1 FUEL"""
REACTIONS3 = """157 ORE => 5 NZVS
165 ORE => 6 DCFZ
44 XJWVT, 5 KHKGT, 1 QDVJ, 29 NZVS, 9 GPVTF, 48 HKGWZ => 1 FUEL
12 HKGWZ, 1 GPVTF, 8 PSHF => 9 QDVJ
179 ORE => 7 PSHF
177 ORE => 5 HKGWZ
7 DCFZ, 7 PSHF => 2 XJWVT
165 ORE => 2 GPVTF
3 DCFZ, 7 NZVS, 5 HKGWZ, 10 PSHF => 8 KHKGT"""
REACTIONS4 = """2 VPVL, 7 FWMGM, 2 CXFTF, 11 MNCFX => 1 STKFG
17 NVRVD, 3 JNWZP => 8 VPVL
53 STKFG, 6 MNCFX, 46 VJHF, 81 HVMC, 68 CXFTF, 25 GNMV => 1 FUEL
22 VJHF, 37 MNCFX => 5 FWMGM
139 ORE => 4 NVRVD
144 ORE => 7 JNWZP
5 MNCFX, 7 RFSQX, 2 FWMGM, 2 VPVL, 19 CXFTF => 3 HVMC
5 VJHF, 7 MNCFX, 9 VPVL, 37 CXFTF => 6 GNMV
145 ORE => 6 MNCFX
1 NVRVD => 8 CXFTF
1 VJHF, 6 MNCFX => 4 RFSQX
176 ORE => 6 VJHF"""
REACTIONS5 = """171 ORE => 8 CNZTR
7 ZLQW, 3 BMBT, 9 XCVML, 26 XMNCP, 1 WPTQ, 2 MZWV, 1 RJRHP => 4 PLWSL
114 ORE => 4 BHXH
14 VRPVC => 6 BMBT
6 BHXH, 18 KTJDG, 12 WPTQ, 7 PLWSL, 31 FHTLT, 37 ZDVW => 1 FUEL
6 WPTQ, 2 BMBT, 8 ZLQW, 18 KTJDG, 1 XMNCP, 6 MZWV, 1 RJRHP => 6 FHTLT
15 XDBXC, 2 LTCX, 1 VRPVC => 6 ZLQW
13 WPTQ, 10 LTCX, 3 RJRHP, 14 XMNCP, 2 MZWV, 1 ZLQW => 1 ZDVW
5 BMBT => 4 WPTQ
189 ORE => 9 KTJDG
1 MZWV, 17 XDBXC, 3 XCVML => 2 XMNCP
12 VRPVC, 27 CNZTR => 2 XDBXC
15 KTJDG, 12 BHXH => 5 XCVML
3 BHXH, 2 VRPVC => 7 MZWV
121 ORE => 7 VRPVC
7 XCVML => 6 RJRHP
5 BHXH, 4 VRPVC => 5 LTCX"""
class Ingredient(NamedTuple):
quantity: int
compound: str
@staticmethod
def from_string(raw: str) -> Ingredient:
qty, compound = raw.strip().split(" ")
return Ingredient(int(qty), compound)
class Reaction:
"""Describes an individual reaction in a NanoFactory"""
def __init__(self, reaction_inputs: Iterable[str], output: str):
self.reaction_inputs = [Ingredient.from_string(inp) for inp in reaction_inputs]
self.reaction_output = Ingredient.from_string(output)
def __repr__(self) -> str:
string_builder: List[str] = []
for (index, reaction_input) in enumerate(self.reaction_inputs):
string_builder.append(f"{reaction_input.quantity} {reaction_input.compound}")
if index < len(self.reaction_inputs) - 1:
string_builder.append(", ")
string_builder.append(f" => {self.reaction_output.quantity} {self.reaction_output.compound}")
return ''.join(string_builder)
class NanoFactory:
def __init__(self, reaction_strings: Iterable[str]):
# Sample reaction_string:
# 10 NXZXH, 7 ZFXP, 7 ZCBM, 7 MHNLM, 1 BDKZM, 3 VQKM => 5 RMZS
self.reactions: Dict[str, Reaction] = {}
for reaction in reaction_strings:
lhs, rhs = reaction.strip().split(" => ")
inputs = lhs.split(", ")
reaction = Reaction(inputs, rhs)
self.reactions[reaction.reaction_output.compound] = reaction
def least_ore(self, fuel_needed: int = 1):
requirements = {'FUEL': fuel_needed}
ore_needed = 0
def done() -> bool:
return all(qty <= 0 for qty in requirements.values())
while not done():
key = next(iter(chemical for chemical, qty in requirements.items() if qty > 0))
qty_needed = requirements[key]
reaction = self.reactions[key]
num_times = math.ceil(qty_needed / reaction.reaction_output.quantity)
requirements[key] -= num_times * reaction.reaction_output.quantity
for ingredient in reaction.reaction_inputs:
if ingredient.compound == "ORE":
ore_needed += ingredient.quantity * num_times
else:
requirements[ingredient.compound] = requirements.get(ingredient.compound, 0) + num_times * ingredient.quantity
return ore_needed
def fuel_from_ore(self, available_ore: int = 1_000_000_000_000):
fuel_lo = 10
fuel_hi = 1_000_000_000
while fuel_lo < fuel_hi - 1:
fuel_mid = (fuel_lo + fuel_hi) // 2
ore_mid = self.least_ore(fuel_mid)
if ore_mid <= available_ore:
fuel_lo = fuel_mid
else:
fuel_hi = fuel_mid
# We've bracketed the fuel amount. Now we need to figure out which one is correct.
return fuel_hi if self.least_ore(fuel_hi) < available_ore else fuel_lo
factory = NanoFactory(REACTIONS1.split("\n"))
assert(factory.reactions['C'].reaction_inputs) == [Ingredient(7, 'A'), Ingredient(1, 'B')]
assert(factory.reactions['D'].reaction_inputs) == [Ingredient(7, 'A'), Ingredient(1, 'C')]
assert(factory.least_ore() == 31)
factory = NanoFactory(REACTIONS2.split("\n"))
assert(factory.least_ore() == 165)
factory = NanoFactory(REACTIONS3.split("\n"))
assert(factory.least_ore() == 13312)
assert(factory.fuel_from_ore() == 82892753)
factory = NanoFactory(REACTIONS4.split("\n"))
assert(factory.least_ore() == 180697)
assert(factory.fuel_from_ore() == 5586022)
factory = NanoFactory(REACTIONS5.split("\n"))
assert(factory.least_ore() == 2210736)
assert(factory.fuel_from_ore() == 460664)
with open("14.txt") as infile:
factory = NanoFactory(infile)
print(f"Part one: minimum ore required: {factory.least_ore()}")
fuel_from_ore = factory.fuel_from_ore()
print(f"Part two: can make {fuel_from_ore} fuel from a trillion ore")
print(factory.least_ore(fuel_from_ore)) | 34.700599 | 130 | 0.645384 | 2,954 | 0.50975 | 0 | 0 | 151 | 0.026057 | 0 | 0 | 2,135 | 0.368421 |
b6052eab54e50a74d3981082007e9fd6ed2ddca3 | 4,790 | py | Python | crawler/views.py | kuna/twfavcrawler | 8173fbedfbf23e291fea18c40aaa29c0db3cbe28 | [
"MIT"
] | null | null | null | crawler/views.py | kuna/twfavcrawler | 8173fbedfbf23e291fea18c40aaa29c0db3cbe28 | [
"MIT"
] | null | null | null | crawler/views.py | kuna/twfavcrawler | 8173fbedfbf23e291fea18c40aaa29c0db3cbe28 | [
"MIT"
] | null | null | null | from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from models import *
import twitter
# -------------------------------
def main(request):
return render(request, "main.htm")
# if not logined, then go to auth page first
def dashboard(request):
token = request.session.get('access_token')
if (token == None):
return redirect('/auth/')
try:
user_obj = User.objects.get(token=token[0])
return render(request, "dashboard.htm", {
"userid": user_obj.id,
"username": user_obj.screen_name,
})
except Exception as e:
raise e
# return HttpResponse('user cannot found', status=500)
# -------------------------------
# if not logined, send to twitter auth page
# otherwise, send to dashboard page
def auth(request):
auth = twitter.CreateBasicAuth()
verifier = request.GET.get('oauth_verifier')
if (verifier == None):
redirect_url = auth.get_authorization_url()
request.session['request_token'] = auth.request_token
return redirect(redirect_url)
else:
token = request.session.get('request_token')
auth.request_token = token
try:
token = auth.get_access_token(verifier)
except tweepy.TweepError:
return HttpResponse('auth error', status=500)
# save access token
access_token = (auth.access_token, auth.access_token_secret)
request.session['access_token'] = access_token
# save user id, name, tokens to DB
api = twitter.CreateApi(auth, access_token)
user_obj = api.me()
request.session['twitter_id'] = user_obj.id
User.objects.update_or_create(
id=user_obj.id,
screen_name=user_obj.screen_name,
name=user_obj.name,
token=access_token[0],
token_secret=access_token[1]
)
return redirect('/dashboard/')
# just remove token and redirect to home
def logout(request):
request.session.pop('access_token')
return redirect('/')
# ------------------------------------------------
# get current status of archive processing
def api_getstatus(request, userid):
try:
userobj = User.objects.get(id=userid)
task = Task.objects.filter(user=userobj, status=0)
if (task):
task = task.latest('date')
return JsonResponse({'success': 1,
'message': task.message,
'value': task.current / task.total})
else:
return JsonResponse({'success': 0,
'message': 'No task exists.'})
except Exception as e:
return JsonResponse({'success': 0,
'message': 'invalid user'})
# make test tweet
def api_testtwit(request, userid):
token = request.session.get('access_token')
if (token == None):
return JsonResponse({'success': 0,
'message': 'login please'})
api = twitter.CreateApi(token)
api.update_status('test - http://tw.insane.pe.kr')
return JsonResponse({'success': 1,
'message': 'ok'})
# just make task stop
# TODO what task? - currently most recent one.
def api_taskstop(request, userid):
token = request.session.get('access_token')
if (token == None):
return JsonResponse({'success': 0,
'message': 'login please'})
try:
userobj = User.objects.get(id=userid)
task = Task.objects.filter(user=userobj, status=0)
if (task.count() > 0):
task = task.latest('date')
task.status = 2
task.message = "Stopped"
task.save()
return JsonResponse({'success': 1,
'message': 'Stopped task successfully'})
else:
return JsonResponse({'success': 0,
'message': 'No task exists.'})
except Exception as e:
raise e
# return JsonResponse({'success': 0,
# 'message': 'invalid user'})
# make job
def api_favcrawler(request, userid):
token = request.session.get('access_token')
if (token == None):
return JsonResponse({'success': 0,
'message': 'login please'})
api = twitter.CreateApi(token)
try:
userobj = User.objects.get(id=userid)
task = Task.objects.filter(user=userobj, status=0)
if (task.count() == 0 and twitter.Task_CrawlFavTweet(api)):
return JsonResponse({'success': 1,
'message': 'Started task successfully'})
else:
return JsonResponse({'success': 0,
'message': 'Currently running task exists!'})
except Exception as e:
raise e
# return JsonResponse({'success': 0,
# 'message': 'under construction'})
| 33.263889 | 72 | 0.589979 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,361 | 0.284134 |
b605e2b8a8084f71c91e33d2351a943a53e715a5 | 1,447 | py | Python | Test/test.py | ed-chin-git/Utils_edchin | 44a6cd8ff9a3c3ffd9976eae53f3b3edd2cca18e | [
"MIT"
] | null | null | null | Test/test.py | ed-chin-git/Utils_edchin | 44a6cd8ff9a3c3ffd9976eae53f3b3edd2cca18e | [
"MIT"
] | null | null | null | Test/test.py | ed-chin-git/Utils_edchin | 44a6cd8ff9a3c3ffd9976eae53f3b3edd2cca18e | [
"MIT"
] | null | null | null | # ======================================================
# Packaging Python Projects Tutorial : https://packaging.python.org/tutorials/packaging-projects/
#
# Installation : # pip install -i https://test.pypi.org/simple/ utils-edchin
#
#
# ===================================================================
# Importing
if __name__ == "__main__":
''' -- Run tests --
'''
import numpy as np
import utils_edchin.pyxlib as edc_xlib # import class
pyx = edc_xlib() # create instance
num_list = [-10, 2, 5, 3, 8, 4, 7, 5, 10, 99, 1000]
qSet = pyx.quartileSet(num_list)
print('\nList :', num_list)
print('Quartile limit-Lower:', qSet[0])
print(' Upper:',qSet[1])
print(' Outliers :', pyx.listOutliers(num_list))
print('w/o Outliers :', pyx.removeOutliers(num_list))
print(' my Var :', pyx.variance_edc(pyx.removeOutliers(num_list)))
print(' Numpy.Var :', np.var(pyx.removeOutliers(num_list)))
str_ing = 'Pennsylvania'
print('\n', str_ing,'string reversed =', pyx.str_reverse(str_ing))
import pandas
import utils_edchin.DataProcessor as edc_dp # import class
dp = edc_dp() # create instance
df_in = pandas.DataFrame({"zip":[45763, 73627, 78632, 22374, 31455], "abbrev": ["OH", "MI", "SD", "PR", "PA"]})
df_out = dp.add_state_names(df_in) # use it
print('\nInput:\n', df_in.head())
print('Output:\n', df_out.head())
| 38.078947 | 115 | 0.572218 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 637 | 0.440221 |
b60662b19a9b9704df07da76b3e45c7b1d60fff5 | 6,913 | py | Python | app/api/api_test.py | optimuspaul/sensei | 4d7a89194fc4014fb5b0de6ffc3a099f083c64d7 | [
"MIT"
] | null | null | null | app/api/api_test.py | optimuspaul/sensei | 4d7a89194fc4014fb5b0de6ffc3a099f083c64d7 | [
"MIT"
] | null | null | null | app/api/api_test.py | optimuspaul/sensei | 4d7a89194fc4014fb5b0de6ffc3a099f083c64d7 | [
"MIT"
] | null | null | null | import unittest
from datetime import datetime, timedelta
import json
from ..main import create_app
from base64 import b64encode
from ..models import *
class ApiTestCase(unittest.TestCase):
def setUp(self):
# Configure app and create a test_client
app = create_app('app.config.TestConfig')
app.app_context().push()
self.app = app.test_client()
# propagate the exceptions to the test client
self.app.testing = True
app.config['DEBUG'] = True
# Authorization header to use when authorized
self.authorized_headers = {
'Authorization': 'Basic ' + b64encode("testuser:testpass")
}
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def api_post_json(self, path, data, auth=False):
if auth:
headers = self.authorized_headers
else:
headers = None
return self.app.post('/api/v1/' + path,
data=data, follow_redirects=True,
content_type='application/json',
headers = headers)
def test_upload_without_auth(self):
radio_ob = dict(
classroom_id=1,
local_id=1,
remote_id=2,
observed_at=datetime.now().isoformat(),
)
event_data = json.dumps([radio_ob])
result = self.api_post_json('radio_observations', event_data)
self.assertEqual(result.status_code, 401)
def test_upload_with_auth(self):
m = SensorMapping(1, 1, datetime.now(), None, MappingType.child, 1)
db.session.add(m)
m = SensorMapping(1, 2, datetime.now(), None, MappingType.child, 2)
db.session.add(m)
db.session.commit()
radio_ob = dict(
classroom_id=1,
local_id=1,
remote_id=2,
observed_at=datetime.now().isoformat(),
)
event_data = json.dumps([radio_ob])
result = self.api_post_json('radio_observations', event_data, True)
self.assertEqual(result.status_code, 201)
events = RadioObservation.query.all()
self.assertEqual(len(events), 1)
def test_upload_duplicate(self):
m = SensorMapping(1, 1, datetime.now(), None, MappingType.child, 1)
db.session.add(m)
m = SensorMapping(1, 2, datetime.now(), None, MappingType.child, 2)
db.session.add(m)
db.session.commit()
now = datetime.now()
radio_ob = dict(
classroom_id=1,
local_id=1,
remote_id=2,
observed_at=now.isoformat(),
)
event_data = json.dumps([radio_ob])
result = self.api_post_json('radio_observations', event_data, True)
one_hour_ago = now - timedelta(hours=1)
radio_ob2 = dict(
classroom_id=1,
local_id=2,
remote_id=1,
observed_at=now.isoformat(),
)
event_data = json.dumps([radio_ob, radio_ob2])
result = self.api_post_json('radio_observations', event_data, True)
self.assertEqual(result.status_code, 201)
events = RadioObservation.query.all()
self.assertEqual(len(events), 2)
def test_mapping_create(self):
mapping_item = dict(
classroom_id=1,
sensor_id=1,
entity_type='child',
entity_id=5, # child_id
)
result = self.api_post_json('sensor_mappings', json.dumps([mapping_item]), True)
self.assertEqual(result.status_code, 201)
mappings = SensorMapping.query.all()
self.assertEqual(len(mappings), 1)
def test_mapping_update_same_sensor_id(self):
# When updating the mapping of a sensor, existing mappings to that
# sensor should be ended
mappings = [
dict(
classroom_id=1,
sensor_id=1,
entity_type='child',
entity_id=5),
dict(
classroom_id=1,
sensor_id=1,
entity_type='child',
entity_id=6)]
result = self.api_post_json('sensor_mappings', json.dumps(mappings), True)
self.assertEqual(result.status_code, 201)
mappings = SensorMapping.query.all()
self.assertEqual(len(mappings), 2)
mappings = SensorMapping.query.filter_by(end_time=None).all()
self.assertEqual(len(mappings), 1)
self.assertEqual(mappings[0].entity_id, 6)
def test_mapping_update_same_entity(self):
# When updating a mapping to an entity, existing mappings to that
# entity should be ended
mappings = [
dict(
classroom_id=1,
sensor_id=1,
entity_type='child',
entity_id=5),
dict(
classroom_id=1,
sensor_id=2,
entity_type='child',
entity_id=5)]
result = self.api_post_json('sensor_mappings', json.dumps(mappings), True)
self.assertEqual(result.status_code, 201)
mappings = SensorMapping.query.all()
self.assertEqual(len(mappings), 2)
mappings = SensorMapping.query.filter_by(end_time=None).all()
self.assertEqual(len(mappings), 1)
self.assertEqual(mappings[0].sensor_id, 2)
def test_get_mappings(self):
m = SensorMapping(1, 1, datetime.now(), None, MappingType.child, 1)
db.session.add(m)
db.session.commit()
result = self.app.get('/api/v1/sensor_mappings?classroom_id=1', headers=self.authorized_headers)
self.assertEqual(result.status_code, 200)
mappings = json.loads(result.data)
self.assertEqual(len(mappings), 1)
def test_area_create(self):
area = dict(
classroom_id=1,
name='test',
)
result = self.api_post_json('areas', json.dumps(area), True)
self.assertEqual(result.status_code, 201)
areas = Area.query.all()
self.assertEqual(len(areas), 1)
self.assertEqual(areas[0].name, "test")
def test_material_create(self):
material = dict(
classroom_id=1,
name='red rods',
lesson_id=5
)
result = self.api_post_json('materials', json.dumps(material), True)
self.assertEqual(result.status_code, 201)
materials = Material.query.all()
self.assertEqual(len(materials), 1)
self.assertEqual(materials[0].name, "red rods")
def test_classrooms_index(self):
result = self.app.get('/api/v1/classrooms', headers=self.authorized_headers)
self.assertEqual(result.status_code, 200)
classrooms = json.loads(result.data)
self.assertEqual(len(classrooms), 1)
self.assertEqual(classrooms[0].get('name'), "test classroom")
if __name__ == '__main__':
unittest.main()
| 33.721951 | 104 | 0.596123 | 6,711 | 0.97078 | 0 | 0 | 0 | 0 | 0 | 0 | 727 | 0.105164 |
b606c6f7d46c35659ab485c2ddd396a75dda115b | 831 | py | Python | reqlog/__main__.py | JFF-Bohdan/reqlog | a7ba7b6e12609d736b3cd8cd8bc2913d511848ee | [
"MIT"
] | null | null | null | reqlog/__main__.py | JFF-Bohdan/reqlog | a7ba7b6e12609d736b3cd8cd8bc2913d511848ee | [
"MIT"
] | null | null | null | reqlog/__main__.py | JFF-Bohdan/reqlog | a7ba7b6e12609d736b3cd8cd8bc2913d511848ee | [
"MIT"
] | null | null | null | import os
import sys
import bottle
base_module_dir = os.path.dirname(sys.modules[__name__].__file__)
try:
import reqlog # noqa: F401 # need to check import possibility
except ImportError:
path = base_module_dir
path = os.path.join(path, "..")
sys.path.insert(0, path)
import reqlog # noqa # testing that we able to import package
from reqlog.support.bottle_tools import log_all_routes # noqa
config = reqlog.get_config()
reqlog.setup_app(config)
log_all_routes(reqlog.logger, reqlog.application)
bottle.run(
app=reqlog.application,
host=config.get("main", "host"),
port=config.getint("main", "port"),
debug=config.getboolean("main", "debug"),
reloader=config.getboolean("main", "reloader"),
interval=config.getint("main", "reloader_interval")
)
| 25.96875 | 67 | 0.690734 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 185 | 0.222623 |
b606c803ecdab8796c233d6f0b74f5656877113c | 23,410 | py | Python | insertData.py | lunious/scggzy | 250094212a650db583ad38cec9644fdd449afdab | [
"Apache-2.0"
] | null | null | null | insertData.py | lunious/scggzy | 250094212a650db583ad38cec9644fdd449afdab | [
"Apache-2.0"
] | null | null | null | insertData.py | lunious/scggzy | 250094212a650db583ad38cec9644fdd449afdab | [
"Apache-2.0"
] | null | null | null | import time
from qgggzy import settings
import pymysql
import logging
connect = pymysql.connect(
host=settings.MYSQL_HOST,
db=settings.MYSQL_DBNAME,
user=settings.MYSQL_USER,
passwd=settings.MYSQL_PASSWD,
port=settings.MYSQL_PORT,
charset='utf8',
use_unicode=False
)
cursor = connect.cursor()
while True:
print('开始插入数据>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
try:
# 公告
cursor.execute(
"insert into bjentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '北京' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from bjentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into tjentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '天津' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from tjentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into hbentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '河北' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from hbentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into sxentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '山西' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from sxentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into nmgentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '内蒙古' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from nmgentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into lnentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '辽宁' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from lnentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into jlentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '吉林' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from jlentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into hljentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '黑龙江' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from hljentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into shentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '上海' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from shentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into jsentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '江苏' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from jsentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into zjentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '浙江' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from zjentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into ahentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '安徽' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from ahentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into fjentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '福建' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from fjentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into jxentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '江西' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from jxentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into sdentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '山东' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from sdentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into hnentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '山东' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from sdentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into hubeientrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '湖北' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from hubeientrylist where entity='qgggjy')",
)
cursor.execute(
"insert into hunanentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '湖南' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from hunanentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into gdentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '广东' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from gdentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into gxentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '广西' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from gxentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into hainanentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '海南' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from hainanentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into gzentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '贵州' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from gzentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into ynentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '云南' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from ynentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into xzentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '西藏' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from xzentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into shanxientrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '陕西' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from shanxientrylist where entity='qgggjy')",
)
cursor.execute(
"insert into gsentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '甘肃' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from gsentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into qhentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '青海' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from qhentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into nxentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '宁夏' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from nxentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into xjentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '新疆' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from xjentrylist where entity='qgggjy')",
)
cursor.execute(
"insert into btentrylist (entryName,sysTime,deadTime,type,entity,entityid,signstauts,labelExplain,lypt,entrynum,address) select entryName,sysTime,deadTime,type,'qgggjy',id,signStauts,tempLabelName,lypt,entryNum,city from qgggjy where area = '兵团' and entryType in ('采购/资审公告', '招标/资审公告', '交易公告') and id not in (select entityid from btentrylist where entity='qgggjy')",
)
# 公示
cursor.execute(
"insert into bjentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '北京' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from bjentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into tjentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '天津' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from tjentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into hbentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '河北' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from hbentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into ynentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '云南' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from ynentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into sxentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '山西' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from sxentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into nmgentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '内蒙古' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from nmgentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into lnentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '辽宁' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from lnentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into jlentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '吉林' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from jlentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into hljentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '黑龙江' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from hljentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into shentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '上海' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from shentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into jsentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '江苏' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from jsentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into zjentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '浙江' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from zjentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into ahentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '安徽' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from ahentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into fjentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '福建' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from fjentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into jxentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '江西' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from jxentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into sdentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '山东' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from sdentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into hnentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '河南' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from hnentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into hubeientryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '湖北' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from hubeientryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into hunanentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '湖南' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from hunanentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into gdentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '广东' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from gdentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into gxentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '广西' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from gxentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into hainanentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '海南' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from hainanentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into gzentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '贵州' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from gzentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into xzentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '西藏' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from xzentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into shanxientryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '陕西' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from shanxientryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into gsentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '甘肃' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from gsentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into qhentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '青海' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from qhentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into nxentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '宁夏' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from nxentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into xjentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '新疆' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from xjentryjglist where entity='qgggjy')"
)
cursor.execute(
"insert into btentryjglist (entryName,sysTime,type,entity,entityid,lypt,entrynum) select entryName,sysTime,type,'qgggjy',id,lypt,entryNum from qgggjy where area = '兵团' and entryType in ('交易结果公示', '中标公告', '成交公示', '交易结果') and id not in (select entityid from btentryjglist where entity='qgggjy')"
)
connect.commit()
print('数据插入成功>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
except Exception as error:
print('数据插入失败>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
logging.log(error)
time.sleep(2)
| 111.47619 | 386 | 0.714994 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 22,389 | 0.869746 |
b608402c0e8072771b347f2c3ecc7549b510eb7d | 327 | py | Python | bchscript/__init__.py | gandrewstone/bchscript | c73a69f259b4cfb71546903c736e4a94fd0680d7 | [
"MIT"
] | 7 | 2018-05-31T18:21:37.000Z | 2020-07-13T05:20:05.000Z | bchscript/__init__.py | gandrewstone/bchscript | c73a69f259b4cfb71546903c736e4a94fd0680d7 | [
"MIT"
] | 1 | 2018-06-19T18:14:48.000Z | 2018-06-19T18:14:48.000Z | bchscript/__init__.py | gandrewstone/bchscript | c73a69f259b4cfb71546903c736e4a94fd0680d7 | [
"MIT"
] | 4 | 2018-06-01T00:29:32.000Z | 2020-07-13T05:19:30.000Z | from bchscript.bchutil import BCH_TESTNET, BCH_MAINNET, BCH_REGTEST, bitcoinAddress2bin
from bchscript.bchscript import compile, script2hex, script2bin, prettyPrint
def mode(m):
global BCH_ADDRESS_PREFIX
BCH_ADDRESS_PREFIX = m
# print("setting bch network to '%s'" % BCH_ADDRESS_PREFIX)
__all__ = ["bchscript"]
| 27.25 | 87 | 0.7737 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 70 | 0.214067 |
b6086a825ed85a12a4788f76ef961e39f102218a | 43,116 | py | Python | djangobbs/uploads/exif.py | JuanbingTeam/djangobbs | 2d52d83b80758e153b0604e71fb0cef4e6528275 | [
"Apache-2.0"
] | null | null | null | djangobbs/uploads/exif.py | JuanbingTeam/djangobbs | 2d52d83b80758e153b0604e71fb0cef4e6528275 | [
"Apache-2.0"
] | null | null | null | djangobbs/uploads/exif.py | JuanbingTeam/djangobbs | 2d52d83b80758e153b0604e71fb0cef4e6528275 | [
"Apache-2.0"
] | null | null | null | # Library to extract EXIF information in digital camera image files
#
# To use this library call with:
# f=open(path_name, 'rb')
# tags=EXIF.process_file(f)
# tags will now be a dictionary mapping names of EXIF tags to their
# values in the file named by path_name. You can process the tags
# as you wish. In particular, you can iterate through all the tags with:
# for tag in tags.keys():
# if tag not in ('JPEGThumbnail', 'TIFFThumbnail', 'Filename',
# 'EXIF MakerNote'):
# print "Key: %s, value %s" % (tag, tags[tag])
# (This code uses the if statement to avoid printing out a few of the
# tags that tend to be long or boring.)
#
# The tags dictionary will include keys for all of the usual EXIF
# tags, and will also include keys for Makernotes used by some
# cameras, for which we have a good specification.
#
# Contains code from "exifdump.py" originally written by Thierry Bousch
# <bousch@topo.math.u-psud.fr> and released into the public domain.
#
# Updated and turned into general-purpose library by Gene Cash
#
# This copyright license is intended to be similar to the FreeBSD license.
#
# Copyright 2002 Gene Cash All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY GENE CASH ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# This means you may do anything you want with this code, except claim you
# wrote it. Also, if it breaks you get to keep both pieces.
#
# Patch Contributors:
# * Simon J. Gerraty <sjg@crufty.net>
# s2n fix & orientation decode
# * John T. Riedl <riedl@cs.umn.edu>
# Added support for newer Nikon type 3 Makernote format for D70 and some
# other Nikon cameras.
# * Joerg Schaefer <schaeferj@gmx.net>
# Fixed subtle bug when faking an EXIF header, which affected maker notes
# using relative offsets, and a fix for Nikon D100.
#
# 21-AUG-99 TB Last update by Thierry Bousch to his code.
# 17-JAN-02 CEC Discovered code on web.
# Commented everything.
# Made small code improvements.
# Reformatted for readability.
# 19-JAN-02 CEC Added ability to read TIFFs and JFIF-format JPEGs.
# Added ability to extract JPEG formatted thumbnail.
# Added ability to read GPS IFD (not tested).
# Converted IFD data structure to dictionaries indexed by
# tag name.
# Factored into library returning dictionary of IFDs plus
# thumbnail, if any.
# 20-JAN-02 CEC Added MakerNote processing logic.
# Added Olympus MakerNote.
# Converted data structure to single-level dictionary, avoiding
# tag name collisions by prefixing with IFD name. This makes
# it much easier to use.
# 23-JAN-02 CEC Trimmed nulls from end of string values.
# 25-JAN-02 CEC Discovered JPEG thumbnail in Olympus TIFF MakerNote.
# 26-JAN-02 CEC Added ability to extract TIFF thumbnails.
# Added Nikon, Fujifilm, Casio MakerNotes.
# 30-NOV-03 CEC Fixed problem with canon_decode_tag() not creating an
# IFD_Tag() object.
# 15-FEB-04 CEC Finally fixed bit shift warning by converting Y to 0L.
#
# field type descriptions as (length, abbreviation, full name) tuples
FIELD_TYPES=(
(0, 'X', 'Proprietary'), # no such type
(1, 'B', 'Byte'),
(1, 'A', 'ASCII'),
(2, 'S', 'Short'),
(4, 'L', 'Long'),
(8, 'R', 'Ratio'),
(1, 'SB', 'Signed Byte'),
(1, 'U', 'Undefined'),
(2, 'SS', 'Signed Short'),
(4, 'SL', 'Signed Long'),
(8, 'SR', 'Signed Ratio')
)
# dictionary of main EXIF tag names
# first element of tuple is tag name, optional second element is
# another dictionary giving names to values
EXIF_TAGS={
0x0100: ('ImageWidth', ),
0x0101: ('ImageLength', ),
0x0102: ('BitsPerSample', ),
0x0103: ('Compression',
{1: 'Uncompressed TIFF',
6: 'JPEG Compressed'}),
0x0106: ('PhotometricInterpretation', ),
0x010A: ('FillOrder', ),
0x010D: ('DocumentName', ),
0x010E: ('ImageDescription', ),
0x010F: ('Make', ),
0x0110: ('Model', ),
0x0111: ('StripOffsets', ),
0x0112: ('Orientation',
{1: 'Horizontal (normal)',
2: 'Mirrored horizontal',
3: 'Rotated 180',
4: 'Mirrored vertical',
5: 'Mirrored horizontal then rotated 90 CCW',
6: 'Rotated 90 CW',
7: 'Mirrored horizontal then rotated 90 CW',
8: 'Rotated 90 CCW'}),
0x0115: ('SamplesPerPixel', ),
0x0116: ('RowsPerStrip', ),
0x0117: ('StripByteCounts', ),
0x011A: ('XResolution', ),
0x011B: ('YResolution', ),
0x011C: ('PlanarConfiguration', ),
0x0128: ('ResolutionUnit',
{1: 'Not Absolute',
2: 'Pixels/Inch',
3: 'Pixels/Centimeter'}),
0x012D: ('TransferFunction', ),
0x0131: ('Software', ),
0x0132: ('DateTime', ),
0x013B: ('Artist', ),
0x013E: ('WhitePoint', ),
0x013F: ('PrimaryChromaticities', ),
0x0156: ('TransferRange', ),
0x0200: ('JPEGProc', ),
0x0201: ('JPEGInterchangeFormat', ),
0x0202: ('JPEGInterchangeFormatLength', ),
0x0211: ('YCbCrCoefficients', ),
0x0212: ('YCbCrSubSampling', ),
0x0213: ('YCbCrPositioning', ),
0x0214: ('ReferenceBlackWhite', ),
0x828D: ('CFARepeatPatternDim', ),
0x828E: ('CFAPattern', ),
0x828F: ('BatteryLevel', ),
0x8298: ('Copyright', ),
0x829A: ('ExposureTime', ),
0x829D: ('FNumber', ),
0x83BB: ('IPTC/NAA', ),
0x8769: ('ExifOffset', ),
0x8773: ('InterColorProfile', ),
0x8822: ('ExposureProgram',
{0: 'Unidentified',
1: 'Manual',
2: 'Program Normal',
3: 'Aperture Priority',
4: 'Shutter Priority',
5: 'Program Creative',
6: 'Program Action',
7: 'Portrait Mode',
8: 'Landscape Mode'}),
0x8824: ('SpectralSensitivity', ),
0x8825: ('GPSInfo', ),
0x8827: ('ISOSpeedRatings', ),
0x8828: ('OECF', ),
# print as string
0x9000: ('ExifVersion', lambda x: ''.join(map(chr, x))),
0x9003: ('DateTimeOriginal', ),
0x9004: ('DateTimeDigitized', ),
0x9101: ('ComponentsConfiguration',
{0: '',
1: 'Y',
2: 'Cb',
3: 'Cr',
4: 'Red',
5: 'Green',
6: 'Blue'}),
0x9102: ('CompressedBitsPerPixel', ),
0x9201: ('ShutterSpeedValue', ),
0x9202: ('ApertureValue', ),
0x9203: ('BrightnessValue', ),
0x9204: ('ExposureBiasValue', ),
0x9205: ('MaxApertureValue', ),
0x9206: ('SubjectDistance', ),
0x9207: ('MeteringMode',
{0: 'Unidentified',
1: 'Average',
2: 'CenterWeightedAverage',
3: 'Spot',
4: 'MultiSpot'}),
0x9208: ('LightSource',
{0: 'Unknown',
1: 'Daylight',
2: 'Fluorescent',
3: 'Tungsten',
10: 'Flash',
17: 'Standard Light A',
18: 'Standard Light B',
19: 'Standard Light C',
20: 'D55',
21: 'D65',
22: 'D75',
255: 'Other'}),
0x9209: ('Flash', {0: 'No',
1: 'Fired',
5: 'Fired (?)', # no return sensed
7: 'Fired (!)', # return sensed
9: 'Fill Fired',
13: 'Fill Fired (?)',
15: 'Fill Fired (!)',
16: 'Off',
24: 'Auto Off',
25: 'Auto Fired',
29: 'Auto Fired (?)',
31: 'Auto Fired (!)',
32: 'Not Available'}),
0x920A: ('FocalLength', ),
0x927C: ('MakerNote', ),
# print as string
0x9286: ('UserComment', lambda x: ''.join(map(chr, x))),
0x9290: ('SubSecTime', ),
0x9291: ('SubSecTimeOriginal', ),
0x9292: ('SubSecTimeDigitized', ),
# print as string
0xA000: ('FlashPixVersion', lambda x: ''.join(map(chr, x))),
0xA001: ('ColorSpace', ),
0xA002: ('ExifImageWidth', ),
0xA003: ('ExifImageLength', ),
0xA005: ('InteroperabilityOffset', ),
0xA20B: ('FlashEnergy', ), # 0x920B in TIFF/EP
0xA20C: ('SpatialFrequencyResponse', ), # 0x920C - -
0xA20E: ('FocalPlaneXResolution', ), # 0x920E - -
0xA20F: ('FocalPlaneYResolution', ), # 0x920F - -
0xA210: ('FocalPlaneResolutionUnit', ), # 0x9210 - -
0xA214: ('SubjectLocation', ), # 0x9214 - -
0xA215: ('ExposureIndex', ), # 0x9215 - -
0xA217: ('SensingMethod', ), # 0x9217 - -
0xA300: ('FileSource',
{3: 'Digital Camera'}),
0xA301: ('SceneType',
{1: 'Directly Photographed'}),
0xA302: ('CVAPattern',),
}
# interoperability tags
INTR_TAGS={
0x0001: ('InteroperabilityIndex', ),
0x0002: ('InteroperabilityVersion', ),
0x1000: ('RelatedImageFileFormat', ),
0x1001: ('RelatedImageWidth', ),
0x1002: ('RelatedImageLength', ),
}
# GPS tags (not used yet, haven't seen camera with GPS)
GPS_TAGS={
0x0000: ('GPSVersionID', ),
0x0001: ('GPSLatitudeRef', ),
0x0002: ('GPSLatitude', ),
0x0003: ('GPSLongitudeRef', ),
0x0004: ('GPSLongitude', ),
0x0005: ('GPSAltitudeRef', ),
0x0006: ('GPSAltitude', ),
0x0007: ('GPSTimeStamp', ),
0x0008: ('GPSSatellites', ),
0x0009: ('GPSStatus', ),
0x000A: ('GPSMeasureMode', ),
0x000B: ('GPSDOP', ),
0x000C: ('GPSSpeedRef', ),
0x000D: ('GPSSpeed', ),
0x000E: ('GPSTrackRef', ),
0x000F: ('GPSTrack', ),
0x0010: ('GPSImgDirectionRef', ),
0x0011: ('GPSImgDirection', ),
0x0012: ('GPSMapDatum', ),
0x0013: ('GPSDestLatitudeRef', ),
0x0014: ('GPSDestLatitude', ),
0x0015: ('GPSDestLongitudeRef', ),
0x0016: ('GPSDestLongitude', ),
0x0017: ('GPSDestBearingRef', ),
0x0018: ('GPSDestBearing', ),
0x0019: ('GPSDestDistanceRef', ),
0x001A: ('GPSDestDistance', )
}
# Nikon E99x MakerNote Tags
# http://members.tripod.com/~tawba/990exif.htm
MAKERNOTE_NIKON_NEWER_TAGS={
0x0002: ('ISOSetting', ),
0x0003: ('ColorMode', ),
0x0004: ('Quality', ),
0x0005: ('Whitebalance', ),
0x0006: ('ImageSharpening', ),
0x0007: ('FocusMode', ),
0x0008: ('FlashSetting', ),
0x0009: ('AutoFlashMode', ),
0x000B: ('WhiteBalanceBias', ),
0x000C: ('WhiteBalanceRBCoeff', ),
0x000F: ('ISOSelection', ),
0x0012: ('FlashCompensation', ),
0x0013: ('ISOSpeedRequested', ),
0x0016: ('PhotoCornerCoordinates', ),
0x0018: ('FlashBracketCompensationApplied', ),
0x0019: ('AEBracketCompensationApplied', ),
0x0080: ('ImageAdjustment', ),
0x0081: ('ToneCompensation', ),
0x0082: ('AuxiliaryLens', ),
0x0083: ('LensType', ),
0x0084: ('LensMinMaxFocalMaxAperture', ),
0x0085: ('ManualFocusDistance', ),
0x0086: ('DigitalZoomFactor', ),
0x0088: ('AFFocusPosition',
{0x0000: 'Center',
0x0100: 'Top',
0x0200: 'Bottom',
0x0300: 'Left',
0x0400: 'Right'}),
0x0089: ('BracketingMode',
{0x00: 'Single frame, no bracketing',
0x01: 'Continuous, no bracketing',
0x02: 'Timer, no bracketing',
0x10: 'Single frame, exposure bracketing',
0x11: 'Continuous, exposure bracketing',
0x12: 'Timer, exposure bracketing',
0x40: 'Single frame, white balance bracketing',
0x41: 'Continuous, white balance bracketing',
0x42: 'Timer, white balance bracketing'}),
0x008D: ('ColorMode', ),
0x008F: ('SceneMode?', ),
0x0090: ('LightingType', ),
0x0092: ('HueAdjustment', ),
0x0094: ('Saturation',
{-3: 'B&W',
-2: '-2',
-1: '-1',
0: '0',
1: '1',
2: '2'}),
0x0095: ('NoiseReduction', ),
0x00A7: ('TotalShutterReleases', ),
0x00A9: ('ImageOptimization', ),
0x00AA: ('Saturation', ),
0x00AB: ('DigitalVariProgram', ),
0x0010: ('DataDump', )
}
MAKERNOTE_NIKON_OLDER_TAGS={
0x0003: ('Quality',
{1: 'VGA Basic',
2: 'VGA Normal',
3: 'VGA Fine',
4: 'SXGA Basic',
5: 'SXGA Normal',
6: 'SXGA Fine'}),
0x0004: ('ColorMode',
{1: 'Color',
2: 'Monochrome'}),
0x0005: ('ImageAdjustment',
{0: 'Normal',
1: 'Bright+',
2: 'Bright-',
3: 'Contrast+',
4: 'Contrast-'}),
0x0006: ('CCDSpeed',
{0: 'ISO 80',
2: 'ISO 160',
4: 'ISO 320',
5: 'ISO 100'}),
0x0007: ('WhiteBalance',
{0: 'Auto',
1: 'Preset',
2: 'Daylight',
3: 'Incandescent',
4: 'Fluorescent',
5: 'Cloudy',
6: 'Speed Light'})
}
# decode Olympus SpecialMode tag in MakerNote
def olympus_special_mode(v):
a={
0: 'Normal',
1: 'Unknown',
2: 'Fast',
3: 'Panorama'}
b={
0: 'Non-panoramic',
1: 'Left to right',
2: 'Right to left',
3: 'Bottom to top',
4: 'Top to bottom'}
return '%s - sequence %d - %s' % (a[v[0]], v[1], b[v[2]])
MAKERNOTE_OLYMPUS_TAGS={
# ah HAH! those sneeeeeaky bastids! this is how they get past the fact
# that a JPEG thumbnail is not allowed in an uncompressed TIFF file
0x0100: ('JPEGThumbnail', ),
0x0200: ('SpecialMode', olympus_special_mode),
0x0201: ('JPEGQual',
{1: 'SQ',
2: 'HQ',
3: 'SHQ'}),
0x0202: ('Macro',
{0: 'Normal',
1: 'Macro'}),
0x0204: ('DigitalZoom', ),
0x0207: ('SoftwareRelease', ),
0x0208: ('PictureInfo', ),
# print as string
0x0209: ('CameraID', lambda x: ''.join(map(chr, x))),
0x0F00: ('DataDump', )
}
MAKERNOTE_CASIO_TAGS={
0x0001: ('RecordingMode',
{1: 'Single Shutter',
2: 'Panorama',
3: 'Night Scene',
4: 'Portrait',
5: 'Landscape'}),
0x0002: ('Quality',
{1: 'Economy',
2: 'Normal',
3: 'Fine'}),
0x0003: ('FocusingMode',
{2: 'Macro',
3: 'Auto Focus',
4: 'Manual Focus',
5: 'Infinity'}),
0x0004: ('FlashMode',
{1: 'Auto',
2: 'On',
3: 'Off',
4: 'Red Eye Reduction'}),
0x0005: ('FlashIntensity',
{11: 'Weak',
13: 'Normal',
15: 'Strong'}),
0x0006: ('Object Distance', ),
0x0007: ('WhiteBalance',
{1: 'Auto',
2: 'Tungsten',
3: 'Daylight',
4: 'Fluorescent',
5: 'Shade',
129: 'Manual'}),
0x000B: ('Sharpness',
{0: 'Normal',
1: 'Soft',
2: 'Hard'}),
0x000C: ('Contrast',
{0: 'Normal',
1: 'Low',
2: 'High'}),
0x000D: ('Saturation',
{0: 'Normal',
1: 'Low',
2: 'High'}),
0x0014: ('CCDSpeed',
{64: 'Normal',
80: 'Normal',
100: 'High',
125: '+1.0',
244: '+3.0',
250: '+2.0',})
}
MAKERNOTE_FUJIFILM_TAGS={
0x0000: ('NoteVersion', lambda x: ''.join(map(chr, x))),
0x1000: ('Quality', ),
0x1001: ('Sharpness',
{1: 'Soft',
2: 'Soft',
3: 'Normal',
4: 'Hard',
5: 'Hard'}),
0x1002: ('WhiteBalance',
{0: 'Auto',
256: 'Daylight',
512: 'Cloudy',
768: 'DaylightColor-Fluorescent',
769: 'DaywhiteColor-Fluorescent',
770: 'White-Fluorescent',
1024: 'Incandescent',
3840: 'Custom'}),
0x1003: ('Color',
{0: 'Normal',
256: 'High',
512: 'Low'}),
0x1004: ('Tone',
{0: 'Normal',
256: 'High',
512: 'Low'}),
0x1010: ('FlashMode',
{0: 'Auto',
1: 'On',
2: 'Off',
3: 'Red Eye Reduction'}),
0x1011: ('FlashStrength', ),
0x1020: ('Macro',
{0: 'Off',
1: 'On'}),
0x1021: ('FocusMode',
{0: 'Auto',
1: 'Manual'}),
0x1030: ('SlowSync',
{0: 'Off',
1: 'On'}),
0x1031: ('PictureMode',
{0: 'Auto',
1: 'Portrait',
2: 'Landscape',
4: 'Sports',
5: 'Night',
6: 'Program AE',
256: 'Aperture Priority AE',
512: 'Shutter Priority AE',
768: 'Manual Exposure'}),
0x1100: ('MotorOrBracket',
{0: 'Off',
1: 'On'}),
0x1300: ('BlurWarning',
{0: 'Off',
1: 'On'}),
0x1301: ('FocusWarning',
{0: 'Off',
1: 'On'}),
0x1302: ('AEWarning',
{0: 'Off',
1: 'On'})
}
MAKERNOTE_CANON_TAGS={
0x0006: ('ImageType', ),
0x0007: ('FirmwareVersion', ),
0x0008: ('ImageNumber', ),
0x0009: ('OwnerName', )
}
# see http://www.burren.cx/david/canon.html by David Burren
# this is in element offset, name, optional value dictionary format
MAKERNOTE_CANON_TAG_0x001={
1: ('Macromode',
{1: 'Macro',
2: 'Normal'}),
2: ('SelfTimer', ),
3: ('Quality',
{2: 'Normal',
3: 'Fine',
5: 'Superfine'}),
4: ('FlashMode',
{0: 'Flash Not Fired',
1: 'Auto',
2: 'On',
3: 'Red-Eye Reduction',
4: 'Slow Synchro',
5: 'Auto + Red-Eye Reduction',
6: 'On + Red-Eye Reduction',
16: 'external flash'}),
5: ('ContinuousDriveMode',
{0: 'Single Or Timer',
1: 'Continuous'}),
7: ('FocusMode',
{0: 'One-Shot',
1: 'AI Servo',
2: 'AI Focus',
3: 'MF',
4: 'Single',
5: 'Continuous',
6: 'MF'}),
10: ('ImageSize',
{0: 'Large',
1: 'Medium',
2: 'Small'}),
11: ('EasyShootingMode',
{0: 'Full Auto',
1: 'Manual',
2: 'Landscape',
3: 'Fast Shutter',
4: 'Slow Shutter',
5: 'Night',
6: 'B&W',
7: 'Sepia',
8: 'Portrait',
9: 'Sports',
10: 'Macro/Close-Up',
11: 'Pan Focus'}),
12: ('DigitalZoom',
{0: 'None',
1: '2x',
2: '4x'}),
13: ('Contrast',
{0xFFFF: 'Low',
0: 'Normal',
1: 'High'}),
14: ('Saturation',
{0xFFFF: 'Low',
0: 'Normal',
1: 'High'}),
15: ('Sharpness',
{0xFFFF: 'Low',
0: 'Normal',
1: 'High'}),
16: ('ISO',
{0: 'See ISOSpeedRatings Tag',
15: 'Auto',
16: '50',
17: '100',
18: '200',
19: '400'}),
17: ('MeteringMode',
{3: 'Evaluative',
4: 'Partial',
5: 'Center-weighted'}),
18: ('FocusType',
{0: 'Manual',
1: 'Auto',
3: 'Close-Up (Macro)',
8: 'Locked (Pan Mode)'}),
19: ('AFPointSelected',
{0x3000: 'None (MF)',
0x3001: 'Auto-Selected',
0x3002: 'Right',
0x3003: 'Center',
0x3004: 'Left'}),
20: ('ExposureMode',
{0: 'Easy Shooting',
1: 'Program',
2: 'Tv-priority',
3: 'Av-priority',
4: 'Manual',
5: 'A-DEP'}),
23: ('LongFocalLengthOfLensInFocalUnits', ),
24: ('ShortFocalLengthOfLensInFocalUnits', ),
25: ('FocalUnitsPerMM', ),
28: ('FlashActivity',
{0: 'Did Not Fire',
1: 'Fired'}),
29: ('FlashDetails',
{14: 'External E-TTL',
13: 'Internal Flash',
11: 'FP Sync Used',
7: '2nd("Rear")-Curtain Sync Used',
4: 'FP Sync Enabled'}),
32: ('FocusMode',
{0: 'Single',
1: 'Continuous'})
}
MAKERNOTE_CANON_TAG_0x004={
7: ('WhiteBalance',
{0: 'Auto',
1: 'Sunny',
2: 'Cloudy',
3: 'Tungsten',
4: 'Fluorescent',
5: 'Flash',
6: 'Custom'}),
9: ('SequenceNumber', ),
14: ('AFPointUsed', ),
15: ('FlashBias',
{0XFFC0: '-2 EV',
0XFFCC: '-1.67 EV',
0XFFD0: '-1.50 EV',
0XFFD4: '-1.33 EV',
0XFFE0: '-1 EV',
0XFFEC: '-0.67 EV',
0XFFF0: '-0.50 EV',
0XFFF4: '-0.33 EV',
0X0000: '0 EV',
0X000C: '0.33 EV',
0X0010: '0.50 EV',
0X0014: '0.67 EV',
0X0020: '1 EV',
0X002C: '1.33 EV',
0X0030: '1.50 EV',
0X0034: '1.67 EV',
0X0040: '2 EV'}),
19: ('SubjectDistance', )
}
# extract multibyte integer in Motorola format (little endian)
def s2n_motorola(str):
x=0
for c in str:
x=(x << 8) | ord(c)
return x
# extract multibyte integer in Intel format (big endian)
def s2n_intel(str):
x=0
y=0L
for c in str:
x=x | (ord(c) << y)
y=y+8
return x
# ratio object that eventually will be able to reduce itself to lowest
# common denominator for printing
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
class Ratio:
def __init__(self, num, den):
self.num=num
self.den=den
def __repr__(self):
self.reduce()
if self.den == 1:
return str(self.num)
return '%d/%d' % (self.num, self.den)
def reduce(self):
div=gcd(self.num, self.den)
if div > 1:
self.num=self.num/div
self.den=self.den/div
# for ease of dealing with tags
class IFD_Tag:
def __init__(self, printable, tag, field_type, values, field_offset,
field_length):
# printable version of data
self.printable=printable
# tag ID number
self.tag=tag
# field type as index into FIELD_TYPES
self.field_type=field_type
# offset of start of field in bytes from beginning of IFD
self.field_offset=field_offset
# length of data field in bytes
self.field_length=field_length
# either a string or array of data items
self.values=values
def __str__(self):
return self.printable
def __repr__(self):
return '(0x%04X) %s=%s @ %d' % (self.tag,
FIELD_TYPES[self.field_type][2],
self.printable,
self.field_offset)
# class that handles an EXIF header
class EXIF_header:
def __init__(self, file, endian, offset, fake_exif, debug=0):
self.file=file
self.endian=endian
self.offset=offset
self.fake_exif=fake_exif
self.debug=debug
self.tags={}
# convert slice to integer, based on sign and endian flags
# usually this offset is assumed to be relative to the beginning of the
# start of the EXIF information. For some cameras that use relative tags,
# this offset may be relative to some other starting point.
def s2n(self, offset, length, signed=0):
self.file.seek(self.offset+offset)
slice=self.file.read(length)
if self.endian == 'I':
val=s2n_intel(slice)
else:
val=s2n_motorola(slice)
# Sign extension ?
if signed:
msb=1L << (8*length-1)
if val & msb:
val=val-(msb << 1)
return val
# convert offset to string
def n2s(self, offset, length):
s=''
for i in range(length):
if self.endian == 'I':
s=s+chr(offset & 0xFF)
else:
s=chr(offset & 0xFF)+s
offset=offset >> 8
return s
# return first IFD
def first_IFD(self):
return self.s2n(4, 4)
# return pointer to next IFD
def next_IFD(self, ifd):
entries=self.s2n(ifd, 2)
return self.s2n(ifd+2+12*entries, 4)
# return list of IFDs in header
def list_IFDs(self):
i=self.first_IFD()
a=[]
while i:
a.append(i)
i=self.next_IFD(i)
return a
# return list of entries in this IFD
def dump_IFD(self, ifd, ifd_name, dict=EXIF_TAGS, relative=0):
entries=self.s2n(ifd, 2)
for i in range(entries):
# entry is index of start of this IFD in the file
entry=ifd+2+12*i
tag=self.s2n(entry, 2)
# get tag name. We do it early to make debugging easier
tag_entry=dict.get(tag)
if tag_entry:
tag_name=tag_entry[0]
else:
tag_name='Tag 0x%04X' % tag
field_type=self.s2n(entry+2, 2)
if not 0 < field_type < len(FIELD_TYPES):
# unknown field type
raise ValueError, \
'unknown type %d in tag 0x%04X' % (field_type, tag)
typelen=FIELD_TYPES[field_type][0]
count=self.s2n(entry+4, 4)
offset=entry+8
if count*typelen > 4:
# offset is not the value; it's a pointer to the value
# if relative we set things up so s2n will seek to the right
# place when it adds self.offset. Note that this 'relative'
# is for the Nikon type 3 makernote. Other cameras may use
# other relative offsets, which would have to be computed here
# slightly differently.
if relative:
tmp_offset=self.s2n(offset, 4)
offset=tmp_offset+ifd-self.offset+4
if self.fake_exif:
offset=offset+18
else:
offset=self.s2n(offset, 4)
field_offset=offset
if field_type == 2:
# special case: null-terminated ASCII string
if count != 0:
self.file.seek(self.offset+offset)
values=self.file.read(count)
values=values.strip().replace('\x00','')
else:
values=''
else:
values=[]
signed=(field_type in [6, 8, 9, 10])
for j in range(count):
if field_type in (5, 10):
# a ratio
value_j=Ratio(self.s2n(offset, 4, signed),
self.s2n(offset+4, 4, signed))
else:
value_j=self.s2n(offset, typelen, signed)
values.append(value_j)
offset=offset+typelen
# now "values" is either a string or an array
if count == 1 and field_type != 2:
printable=str(values[0])
else:
printable=str(values)
# compute printable version of values
if tag_entry:
if len(tag_entry) != 1:
# optional 2nd tag element is present
if callable(tag_entry[1]):
# call mapping function
printable=tag_entry[1](values)
else:
printable=''
for i in values:
# use lookup table for this tag
printable+=tag_entry[1].get(i, repr(i))
self.tags[ifd_name+' '+tag_name]=IFD_Tag(printable, tag,
field_type,
values, field_offset,
count*typelen)
if self.debug:
print ' debug: %s: %s' % (tag_name,
repr(self.tags[ifd_name+' '+tag_name]))
# extract uncompressed TIFF thumbnail (like pulling teeth)
# we take advantage of the pre-existing layout in the thumbnail IFD as
# much as possible
def extract_TIFF_thumbnail(self, thumb_ifd):
entries=self.s2n(thumb_ifd, 2)
# this is header plus offset to IFD ...
if self.endian == 'M':
tiff='MM\x00*\x00\x00\x00\x08'
else:
tiff='II*\x00\x08\x00\x00\x00'
# ... plus thumbnail IFD data plus a null "next IFD" pointer
self.file.seek(self.offset+thumb_ifd)
tiff+=self.file.read(entries*12+2)+'\x00\x00\x00\x00'
# fix up large value offset pointers into data area
for i in range(entries):
entry=thumb_ifd+2+12*i
tag=self.s2n(entry, 2)
field_type=self.s2n(entry+2, 2)
typelen=FIELD_TYPES[field_type][0]
count=self.s2n(entry+4, 4)
oldoff=self.s2n(entry+8, 4)
# start of the 4-byte pointer area in entry
ptr=i*12+18
# remember strip offsets location
if tag == 0x0111:
strip_off=ptr
strip_len=count*typelen
# is it in the data area?
if count*typelen > 4:
# update offset pointer (nasty "strings are immutable" crap)
# should be able to say "tiff[ptr:ptr+4]=newoff"
newoff=len(tiff)
tiff=tiff[:ptr]+self.n2s(newoff, 4)+tiff[ptr+4:]
# remember strip offsets location
if tag == 0x0111:
strip_off=newoff
strip_len=4
# get original data and store it
self.file.seek(self.offset+oldoff)
tiff+=self.file.read(count*typelen)
# add pixel strips and update strip offset info
old_offsets=self.tags['Thumbnail StripOffsets'].values
old_counts=self.tags['Thumbnail StripByteCounts'].values
for i in range(len(old_offsets)):
# update offset pointer (more nasty "strings are immutable" crap)
offset=self.n2s(len(tiff), strip_len)
tiff=tiff[:strip_off]+offset+tiff[strip_off+strip_len:]
strip_off+=strip_len
# add pixel strip to end
self.file.seek(self.offset+old_offsets[i])
tiff+=self.file.read(old_counts[i])
self.tags['TIFFThumbnail']=tiff
# decode all the camera-specific MakerNote formats
# Note is the data that comprises this MakerNote. The MakerNote will
# likely have pointers in it that point to other parts of the file. We'll
# use self.offset as the starting point for most of those pointers, since
# they are relative to the beginning of the file.
#
# If the MakerNote is in a newer format, it may use relative addressing
# within the MakerNote. In that case we'll use relative addresses for the
# pointers.
#
# As an aside: it's not just to be annoying that the manufacturers use
# relative offsets. It's so that if the makernote has to be moved by the
# picture software all of the offsets don't have to be adjusted. Overall,
# this is probably the right strategy for makernotes, though the spec is
# ambiguous. (The spec does not appear to imagine that makernotes would
# follow EXIF format internally. Once they did, it's ambiguous whether
# the offsets should be from the header at the start of all the EXIF info,
# or from the header at the start of the makernote.)
def decode_maker_note(self):
note=self.tags['EXIF MakerNote']
make=self.tags['Image Make'].printable
model=self.tags['Image Model'].printable
# Nikon
# The maker note usually starts with the word Nikon, followed by the
# type of the makernote (1 or 2, as a short). If the word Nikon is
# not at the start of the makernote, it's probably type 2, since some
# cameras work that way.
if make in ('NIKON', 'NIKON CORPORATION'):
if note.values[0:7] == [78, 105, 107, 111, 110, 00, 01]:
if self.debug:
print "Looks like a type 1 Nikon MakerNote."
self.dump_IFD(note.field_offset+8, 'MakerNote',
dict=MAKERNOTE_NIKON_OLDER_TAGS)
elif note.values[0:7] == [78, 105, 107, 111, 110, 00, 02]:
if self.debug:
print "Looks like a labeled type 2 Nikon MakerNote"
if note.values[12:14] != [0, 42] and note.values[12:14] != [42L, 0L]:
raise ValueError, "Missing marker tag '42' in MakerNote."
# skip the Makernote label and the TIFF header
self.dump_IFD(note.field_offset+10+8, 'MakerNote',
dict=MAKERNOTE_NIKON_NEWER_TAGS, relative=1)
else:
# E99x or D1
if self.debug:
print "Looks like an unlabeled type 2 Nikon MakerNote"
self.dump_IFD(note.field_offset, 'MakerNote',
dict=MAKERNOTE_NIKON_NEWER_TAGS)
return
# Olympus
if make[:7] == 'OLYMPUS':
self.dump_IFD(note.field_offset+8, 'MakerNote',
dict=MAKERNOTE_OLYMPUS_TAGS)
return
# Casio
if make == 'Casio':
self.dump_IFD(note.field_offset, 'MakerNote',
dict=MAKERNOTE_CASIO_TAGS)
return
# Fujifilm
if make == 'FUJIFILM':
# bug: everything else is "Motorola" endian, but the MakerNote
# is "Intel" endian
endian=self.endian
self.endian='I'
# bug: IFD offsets are from beginning of MakerNote, not
# beginning of file header
offset=self.offset
self.offset+=note.field_offset
# process note with bogus values (note is actually at offset 12)
self.dump_IFD(12, 'MakerNote', dict=MAKERNOTE_FUJIFILM_TAGS)
# reset to correct values
self.endian=endian
self.offset=offset
return
# Canon
if make == 'Canon':
self.dump_IFD(note.field_offset, 'MakerNote',
dict=MAKERNOTE_CANON_TAGS)
for i in (('MakerNote Tag 0x0001', MAKERNOTE_CANON_TAG_0x001),
('MakerNote Tag 0x0004', MAKERNOTE_CANON_TAG_0x004)):
self.canon_decode_tag(self.tags[i[0]].values, i[1])
return
# decode Canon MakerNote tag based on offset within tag
# see http://www.burren.cx/david/canon.html by David Burren
def canon_decode_tag(self, value, dict):
for i in range(1, len(value)):
x=dict.get(i, ('Unknown', ))
if self.debug:
print i, x
name=x[0]
if len(x) > 1:
val=x[1].get(value[i], 'Unknown')
else:
val=value[i]
# it's not a real IFD Tag but we fake one to make everybody
# happy. this will have a "proprietary" type
self.tags['MakerNote '+name]=IFD_Tag(str(val), None, 0, None,
None, None)
# process an image file (expects an open file object)
# this is the function that has to deal with all the arbitrary nasty bits
# of the EXIF standard
def process_file(file, debug=0):
# determine whether it's a JPEG or TIFF
data=file.read(12)
if data[0:4] in ['II*\x00', 'MM\x00*']:
# it's a TIFF file
file.seek(0)
endian=file.read(1)
file.read(1)
offset=0
elif data[0:2] == '\xFF\xD8':
# it's a JPEG file
# skip JFIF style header(s)
fake_exif=0
while data[2] == '\xFF' and data[6:10] in ('JFIF', 'JFXX', 'OLYM'):
length=ord(data[4])*256+ord(data[5])
file.read(length-8)
# fake an EXIF beginning of file
data='\xFF\x00'+file.read(10)
fake_exif=1
if data[2] == '\xFF' and data[6:10] == 'Exif':
# detected EXIF header
offset=file.tell()
endian=file.read(1)
else:
# no EXIF information
return {}
else:
# file format not recognized
return {}
# deal with the EXIF info we found
if debug:
print {'I': 'Intel', 'M': 'Motorola'}[endian], 'format'
hdr=EXIF_header(file, endian, offset, fake_exif, debug)
ifd_list=hdr.list_IFDs()
ctr=0
for i in ifd_list:
if ctr == 0:
IFD_name='Image'
elif ctr == 1:
IFD_name='Thumbnail'
thumb_ifd=i
else:
IFD_name='IFD %d' % ctr
if debug:
print ' IFD %d (%s) at offset %d:' % (ctr, IFD_name, i)
hdr.dump_IFD(i, IFD_name)
# EXIF IFD
exif_off=hdr.tags.get(IFD_name+' ExifOffset')
if exif_off:
if debug:
print ' EXIF SubIFD at offset %d:' % exif_off.values[0]
hdr.dump_IFD(exif_off.values[0], 'EXIF')
# Interoperability IFD contained in EXIF IFD
intr_off=hdr.tags.get('EXIF SubIFD InteroperabilityOffset')
if intr_off:
if debug:
print ' EXIF Interoperability SubSubIFD at offset %d:' \
% intr_off.values[0]
hdr.dump_IFD(intr_off.values[0], 'EXIF Interoperability',
dict=INTR_TAGS)
# GPS IFD
gps_off=hdr.tags.get(IFD_name+' GPSInfo')
if gps_off:
if debug:
print ' GPS SubIFD at offset %d:' % gps_off.values[0]
hdr.dump_IFD(gps_off.values[0], 'GPS', dict=GPS_TAGS)
ctr+=1
# extract uncompressed TIFF thumbnail
thumb=hdr.tags.get('Thumbnail Compression')
if thumb and thumb.printable == 'Uncompressed TIFF':
hdr.extract_TIFF_thumbnail(thumb_ifd)
# JPEG thumbnail (thankfully the JPEG data is stored as a unit)
thumb_off=hdr.tags.get('Thumbnail JPEGInterchangeFormat')
if thumb_off:
file.seek(offset+thumb_off.values[0])
size=hdr.tags['Thumbnail JPEGInterchangeFormatLength'].values[0]
hdr.tags['JPEGThumbnail']=file.read(size)
# deal with MakerNote contained in EXIF IFD
if hdr.tags.has_key('EXIF MakerNote'):
hdr.decode_maker_note()
# Sometimes in a TIFF file, a JPEG thumbnail is hidden in the MakerNote
# since it's not allowed in a uncompressed TIFF IFD
if not hdr.tags.has_key('JPEGThumbnail'):
thumb_off=hdr.tags.get('MakerNote JPEGThumbnail')
if thumb_off:
file.seek(offset+thumb_off.values[0])
hdr.tags['JPEGThumbnail']=file.read(thumb_off.field_length)
return hdr.tags
# library test/debug function (dump given files)
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
print 'Usage: %s files...\n' % sys.argv[0]
sys.exit(0)
for filename in sys.argv[1:]:
try:
file=open(filename, 'rb')
except:
print filename, 'unreadable'
print
continue
print filename+':'
# data=process_file(file, 1) # with debug info
data=process_file(file)
if not data:
print 'No EXIF information found'
continue
x=data.keys()
x.sort()
for i in x:
if i in ('JPEGThumbnail', 'TIFFThumbnail'):
continue
try:
print ' %s (%s): %s' % \
(i, FIELD_TYPES[data[i].field_type][2], data[i].printable)
except:
print 'error', i, '"', data[i], '"'
if data.has_key('JPEGThumbnail'):
print 'File has JPEG thumbnail'
print
| 36.080335 | 86 | 0.505682 | 14,370 | 0.333287 | 0 | 0 | 0 | 0 | 0 | 0 | 18,634 | 0.432183 |
b609f4b1ffa24614e7665b9913e37d343760b745 | 341 | py | Python | Introducao python/exercicios/ex009.py | Luis12368/python | 23352d75ad13bcfd09ea85ab422fdc6ae1fcc5e7 | [
"MIT"
] | null | null | null | Introducao python/exercicios/ex009.py | Luis12368/python | 23352d75ad13bcfd09ea85ab422fdc6ae1fcc5e7 | [
"MIT"
] | null | null | null | Introducao python/exercicios/ex009.py | Luis12368/python | 23352d75ad13bcfd09ea85ab422fdc6ae1fcc5e7 | [
"MIT"
] | null | null | null | n = int(input('Insira um número: '))
print('_' * 12)
print(f'{n} X 1 = {n*1}')
print(f'{n} X 2 = {n*2}')
print(f'{n} X 3 = {n*3}')
print(f'{n} X 4 = {n*4}')
print(f'{n} X 5 = {n*5}')
print(f'{n} x 6 = {n*6}')
print(f'{n} X 7 = {n*7}')
print(f'{n} X 8 = {n*8}')
print(f'{n} X 9 = {n*9}')
print(f'{n} X 10 = {n*10}')
print('_' * 12)
| 22.733333 | 36 | 0.442815 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 218 | 0.637427 |
b60aa69f26d91dc79de24bac34658713f8d14b86 | 1,013 | py | Python | setup.py | GSri30/Disbot | 844c18470728402ddd95b956b03da3ab310fd933 | [
"MIT"
] | null | null | null | setup.py | GSri30/Disbot | 844c18470728402ddd95b956b03da3ab310fd933 | [
"MIT"
] | 2 | 2021-03-12T09:01:46.000Z | 2021-03-12T09:07:30.000Z | setup.py | GSri30/Disbot | 844c18470728402ddd95b956b03da3ab310fd933 | [
"MIT"
] | null | null | null | from setuptools import setup, find_packages
with open('README.md') as readme_file:
README=readme_file.read()
with open('HISTORY.md') as history_file:
HISTORY=history_file.read()
setup_args=dict(
name='DisBot',
version='1.0',
description='Tool to create a quick new discord.py bot',
long_description_content_type="text/markdown",
long_description=README + '\n\n' + HISTORY,
license='MIT',
packages=find_packages(),
author='Sri Harsha G',
author_email='sri_3007@hotmail.com',
keywords=['discord.py', 'discord template', 'discord bot template', 'Disbot'],
url='https://github.com/GSri30/Disbot',
download_url='https://pypi.org/project/DisBot',
include_package_data=True,
entry_points={
'console_scripts':[
'disbot-admin=Disbot.cli:Main'
]
},
)
install_requires=[
'click',
'python-dotenv',
'discord.py',
]
if __name__=="__main__":
setup(**setup_args,install_requires=install_requires) | 27.378378 | 82 | 0.663376 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 359 | 0.354393 |
b60bb95066becb48c6ff8cba134f776c7538e9c1 | 204 | py | Python | simple_help/__init__.py | DCOD-OpenSource/django-simple-help | 779ccd900adee0d0eb656dd8e676019127e5f6e2 | [
"MIT"
] | 3 | 2016-11-29T14:24:59.000Z | 2017-05-25T11:25:55.000Z | simple_help/__init__.py | DCOD-OpenSource/django-simple-help | 779ccd900adee0d0eb656dd8e676019127e5f6e2 | [
"MIT"
] | null | null | null | simple_help/__init__.py | DCOD-OpenSource/django-simple-help | 779ccd900adee0d0eb656dd8e676019127e5f6e2 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# django-simple-help
# simple_help/__init__.py
from __future__ import unicode_literals
__all__ = [
"default_app_config",
]
default_app_config = "simple_help.apps.Config"
| 13.6 | 46 | 0.720588 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 113 | 0.553922 |
b60c3bce7835af6a87ec56f47bab71db90bed1c7 | 7,517 | py | Python | avanza/avanza_socket.py | jonasoreland/avanza | e09fde24070485ddbdde7b114f366e0714f8b25a | [
"MIT"
] | null | null | null | avanza/avanza_socket.py | jonasoreland/avanza | e09fde24070485ddbdde7b114f366e0714f8b25a | [
"MIT"
] | null | null | null | avanza/avanza_socket.py | jonasoreland/avanza | e09fde24070485ddbdde7b114f366e0714f8b25a | [
"MIT"
] | null | null | null | import asyncio
import logging
import json
import websockets
from typing import Any, Callable, Sequence
from .constants import (
ChannelType
)
WEBSOCKET_URL = 'wss://www.avanza.se/_push/cometd'
logger = logging.getLogger("avanza_socket")
class AvanzaSocket:
def __init__(self, push_subscription_id, cookies):
self._socket = None
self._client_id = None
self._message_count = 1
self._push_subscription_id = push_subscription_id
self._connected = False
self._subscriptions = {}
self._cookies = cookies
self._subscribe_event = None
async def init(self):
asyncio.ensure_future(self.__create_socket())
await self.__wait_for_websocket_to_be_connected()
async def __wait_for_websocket_to_be_connected(self):
timeout_count = 40
timeout_value = 0.250
# Waits for a maximum of 10 seconds for the connection to be complete
for _ in range(0, timeout_count):
if self._connected:
return
await asyncio.sleep(timeout_value)
raise TimeoutError('\
We weren\'t able to connect \
to the websocket within the expected timeframe \
')
async def __create_socket(self):
async with websockets.connect(
WEBSOCKET_URL,
extra_headers={'Cookie': self._cookies}
) as self._socket:
await self.__send_handshake_message()
await self.__socket_message_handler()
async def __send_handshake_message(self):
await self.__send({
'advice': {
'timeout': 60000,
'interval': 0
},
'channel': '/meta/handshake',
'ext': {'subscriptionId': self._push_subscription_id},
'minimumVersion': '1.0',
'supportedConnectionTypes': [
'websocket',
'long-polling',
'callback-polling'
],
'version': '1.0'
})
async def __send_connect_message(self):
await self.__send({
'channel': '/meta/connect',
'clientId': self._client_id,
'connectionType': 'websocket',
'id': self._message_count
})
async def __socket_subscribe(
self,
subscription_string,
callback: Callable[[str, dict], Any],
wait_for_reply_timeout_seconds
):
if self._subscribe_event is None:
self._subscribe_event = asyncio.Event()
self._subscriptions[subscription_string] = {
'callback': callback
}
self._subscribe_event.clear()
await self.__send({
'channel': '/meta/subscribe',
'clientId': self._client_id,
'subscription': subscription_string
})
# Wait for subscription ack message.
if wait_for_reply_timeout_seconds is not None:
try:
await asyncio.wait_for(self._subscribe_event.wait(), timeout=wait_for_reply_timeout_seconds)
except asyncio.TimeoutError:
logger.warning('timeout waiting for subscription reply!')
async def __send(self, message):
wrapped_message = [
{
**message,
'id': str(self._message_count)
}
]
logger.info(f'Outgoing message: {wrapped_message}')
await self._socket.send(json.dumps(wrapped_message))
self._message_count = self._message_count + 1
async def __handshake(self, message: dict):
if message.get('successful', False):
self._client_id = message.get('clientId')
await self.__send({
'advice': {'timeout': 0},
'channel': '/meta/connect',
'clientId': self._client_id,
'connectionType': 'websocket'
})
return
advice = message.get('advice')
if advice and advice.get('reconnect') == 'handshake':
await self.__send_handshake_message()
async def __connect(self, message: dict):
successful = message.get('successful', False)
advice = message.get('advice', {})
reconnect = advice.get('reconnect') == 'retry'
interval = advice.get('interval')
connect_successful = successful and (
not advice or (reconnect and interval >= 0)
)
if connect_successful:
await self.__send({
'channel': '/meta/connect',
'clientId': self._client_id,
'connectionType': 'websocket'
})
if not self._connected:
self._connected = True
await self.__resubscribe_existing_subscriptions()
elif self._client_id:
await self.__send_connect_message()
async def __resubscribe_existing_subscriptions(self):
for key, value in self._subscriptions.items():
if value.get('client_id') != self._client_id:
await self.__socket_subscribe(
key,
value['callback']
)
async def __disconnect(self, message):
await self.__send_handshake_message()
async def __register_subscription(self, message):
subscription = message.get('subscription')
if subscription is None:
raise ValueError('No subscription channel found on subscription message')
self._subscriptions[subscription]['client_id'] = self._client_id
self._subscribe_event.set()
async def __socket_message_handler(self):
message_action = {
'/meta/disconnect': self.__disconnect,
'/meta/handshake': self.__handshake,
'/meta/connect': self.__connect,
'/meta/subscribe': self.__register_subscription
}
async for message in self._socket:
message = json.loads(message)[0]
message_channel = message.get('channel')
error = message.get('error')
logger.info(f'Incoming message: {message}')
if error:
logger.error(error)
action = message_action.get(message_channel)
# Use user subscribed action
if action is None:
callback = self._subscriptions[message_channel]['callback']
callback(message)
else:
await action(message)
async def subscribe_to_id(
self,
channel: ChannelType,
id: str,
callback: Callable[[str, dict], Any],
wait_for_reply_timeout_seconds,
):
return await self.subscribe_to_ids(channel, [id], callback, wait_for_reply_timeout_seconds)
async def subscribe_to_ids(
self,
channel: ChannelType,
ids: Sequence[str],
callback: Callable[[str, dict], Any],
wait_for_reply_timeout_seconds
):
valid_channels_for_multiple_ids = [
ChannelType.ORDERS,
ChannelType.DEALS,
ChannelType.POSITIONS
]
if (
len(ids) > 1 and
channel not in valid_channels_for_multiple_ids
):
raise ValueError(f'Multiple ids is not supported for channels other than {valid_channels_for_multiple_ids}')
subscription_string = f'/{channel.value}/{",".join(ids)}'
await self.__socket_subscribe(subscription_string, callback, wait_for_reply_timeout_seconds)
| 32.261803 | 120 | 0.588533 | 7,270 | 0.967141 | 0 | 0 | 0 | 0 | 6,823 | 0.907676 | 1,279 | 0.170148 |
b60ca16fa837b453b4af03e4bf6713bd39b4eeda | 1,610 | py | Python | app/auth/routes.py | oldcryptogeek/coinjerk-btcp | 76d16b6c890bf1caa155ff07bca162526db08fc7 | [
"MIT"
] | 8 | 2020-09-22T03:40:31.000Z | 2021-04-17T15:17:03.000Z | app/auth/routes.py | Zaxounette/coinjerk-btcp | 76d16b6c890bf1caa155ff07bca162526db08fc7 | [
"MIT"
] | 5 | 2021-01-10T23:36:12.000Z | 2022-02-19T06:46:18.000Z | app/auth/routes.py | Zaxounette/coinjerk-btcp | 76d16b6c890bf1caa155ff07bca162526db08fc7 | [
"MIT"
] | 2 | 2021-01-03T23:36:39.000Z | 2021-02-13T15:45:09.000Z | from flask import jsonify, request, current_app
from app import db
from app.auth import auth
from app.models import User
from datetime import datetime, timedelta
import jwt
@auth.route("/login", methods=['POST'])
def login():
data = request.get_json()
user = User.authenticate(**data)
if not user:
return jsonify({
'message': "Invalid Credentials",
'authenticated': False
}), 401
token = jwt.encode({
'sub': user.id,
'iat': datetime.utcnow(),
'exp': datetime.utcnow() + timedelta(hours=24)
}, current_app.config['SECRET_KEY'])
return jsonify({
'token': token.decode('UTF-8')
})
@auth.route("/register", methods=['POST'])
def register():
form = request.get_json()
user = User.query.filter_by(username=form['username']).first()
if user:
return jsonify({
'message': "Username Unavailable",
'authenticated': False
}), 400
else:
user = User(username=form['username'])
user.set_password(form['password'])
db.session.add(user)
db.session.commit()
token = jwt.encode({
'sub': user.id,
'iat': datetime.utcnow(),
'exp': datetime.utcnow() + timedelta(hours=24)
}, current_app.config['SECRET_KEY'])
return jsonify({
'token': token.decode('UTF-8'),
'authenticated': True
})
@auth.route("/reg_enabled", methods=['GET'])
def auth_reg_enabled():
return jsonify({
'enabled': current_app.config['ENABLE_USER_REGISTRATION']
})
| 24.393939 | 66 | 0.585093 | 0 | 0 | 0 | 0 | 1,426 | 0.885714 | 0 | 0 | 303 | 0.188199 |
b60cc6954437b801363a2acdd55d0ccb2d6e3209 | 6,313 | py | Python | event/io/dataset/richere.py | edvisees/DDSemantics | 9044e4afa6f9d6d7504de028633295f30679278d | [
"Apache-2.0"
] | null | null | null | event/io/dataset/richere.py | edvisees/DDSemantics | 9044e4afa6f9d6d7504de028633295f30679278d | [
"Apache-2.0"
] | null | null | null | event/io/dataset/richere.py | edvisees/DDSemantics | 9044e4afa6f9d6d7504de028633295f30679278d | [
"Apache-2.0"
] | null | null | null | import logging
import os
import xml.etree.ElementTree as ET
from collections import defaultdict
from event.io.dataset.base import (
Span,
DataLoader,
DEDocument,
RelationMention,
)
class RichERE(DataLoader):
def __init__(self, params, corpus, with_doc=False):
super().__init__(params, corpus, with_doc)
self.params = params
def parse_ere(self, ere_file, doc):
root = ET.parse(ere_file).getroot()
doc_info = root.attrib
doc.set_id = doc_info['doc_id']
doc.set_doc_type = doc_info['source_type']
for entity_node in root.find('entities'):
entity_ids = []
ent = doc.add_entity(entity_node.attrib['type'],
entity_node.attrib['id'])
for entity_mention in entity_node.findall('entity_mention'):
ent_info = entity_mention.attrib
entity_ids.append(ent_info['id'])
entity_text = entity_mention.find('mention_text').text
entity_span = Span(ent_info['offset'], ent_info['length'])
doc.add_entity_mention(
ent, entity_span, entity_text,
ent_info['id'],
noun_type=ent_info['noun_type'],
entity_type=ent_info.get('type', None),
)
for filler in root.find('fillers'):
filler_info = filler.attrib
b = int(filler_info['offset'])
l = int(filler_info['length'])
doc.add_filler(
Span(b, b + l), filler.text,
eid=filler_info['id'], filler_type=filler_info['type']
)
for event_node in root.find('hoppers'):
evm_ids = []
event = doc.add_hopper(event_node.attrib['id'])
for event_mention in event_node.findall('event_mention'):
evm_info = event_mention.attrib
evm_ids.append(evm_info['id'])
trigger = event_mention.find('trigger')
trigger_text = trigger.text
offset = trigger.attrib['offset']
length = trigger.attrib['length']
evm = doc.add_predicate(
event, Span(offset, offset + length), trigger_text,
eid=evm_info['id'],
frame_type=evm_info['type'] + '_' + evm_info['subtype'],
realis=evm_info['realis'])
for em_arg in event_mention.findall('em_arg'):
arg_info = em_arg.attrib
arg_ent_mention = None
if 'entity_mention_id' in arg_info:
arg_ent_mention = arg_info['entity_mention_id']
if 'filler_id' in arg_info:
arg_ent_mention = arg_info['filler_id']
role = arg_info['role']
doc.add_argument_mention(evm, arg_ent_mention, role)
for relation_node in root.find('relations'):
relation_info = relation_node.attrib
relation = doc.add_relation(
relation_info['id'],
relation_type=relation_info['type'] + '_' + relation_info[
'subtype']
)
for rel_mention_node in relation_node.findall('relation_mention'):
rel_mention_id = rel_mention_node.attrib['id']
rel_realis = rel_mention_node.attrib['realis']
args = {}
for mention_part in rel_mention_node:
if mention_part.tag.startswith('rel_arg'):
if 'entity_mention_id' in mention_part.attrib:
ent_id = mention_part.attrib['entity_mention_id']
else:
ent_id = mention_part.attrib['filler_id']
role = mention_part.attrib['role']
args[role] = ent_id
trigger = rel_mention_node.find('trigger')
if trigger is not None:
trigger_text = trigger.text
trigger_begin = trigger.attrib['offset']
trigger_len = trigger.attrib['length']
else:
trigger_text = ''
trigger_begin = None
trigger_len = None
rel_mention = RelationMention(
rel_mention_id, Span(trigger_begin, trigger_len),
trigger_text, rel_realis
)
for role, ent in args.items():
rel_mention.add_arg(role, ent)
relation.add_mention(rel_mention)
def read_rich_ere(self, corpus, source_path, l_ere_path, ranges):
with open(source_path) as source:
text = source.read()
doc = DEDocument(corpus, text, ranges, self.params.ignore_quote)
for ere_path in l_ere_path:
with open(ere_path) as ere:
logging.info("Processing: " + os.path.basename(ere_path))
self.parse_ere(ere, doc)
return doc
def get_doc(self):
super().get_doc()
sources = {}
eres = defaultdict(list)
annotate_ranges = defaultdict(list)
for fn in os.listdir(self.params.ere):
basename = fn.replace(self.params.ere_ext, '')
if self.params.ere_split:
parts = basename.split('_')
r = [int(p) for p in parts[-1].split('-')]
annotate_ranges[basename].append(r)
basename = '_'.join(parts[:-1])
ere_fn = os.path.join(self.params.ere, fn)
eres[basename].append(ere_fn)
for fn in os.listdir(self.params.source):
txt_base = fn.replace(self.params.src_ext, '')
if txt_base in eres:
sources[txt_base] = os.path.join(self.params.source, fn)
if not os.path.exists(self.params.out_dir):
os.makedirs(self.params.out_dir)
for basename, source in sources.items():
l_ere = eres[basename]
ranges = annotate_ranges[basename]
doc = self.read_rich_ere(self.corpus, source, l_ere, ranges)
yield doc
| 36.281609 | 78 | 0.534453 | 6,112 | 0.968161 | 1,130 | 0.178996 | 0 | 0 | 0 | 0 | 489 | 0.077459 |
b6105ca720ff08f32883b070b3b6eb3a689c0317 | 1,149 | py | Python | cfc-parser.py | FIFCOM/codeforces-contests-parser | 8a1bf7f4d4802be073e1f4cba8cc2962409473c5 | [
"MIT"
] | null | null | null | cfc-parser.py | FIFCOM/codeforces-contests-parser | 8a1bf7f4d4802be073e1f4cba8cc2962409473c5 | [
"MIT"
] | null | null | null | cfc-parser.py | FIFCOM/codeforces-contests-parser | 8a1bf7f4d4802be073e1f4cba8cc2962409473c5 | [
"MIT"
] | null | null | null | import os
import urllib.request
import json
import datetime
from prettytable import PrettyTable
contest_url = "https://codeforces.com/api/contest.list"
cur_timestamp = int(datetime.datetime.now().timestamp())
def get_contest_list():
response = urllib.request.urlopen(contest_url)
data = json.loads(response.read().decode())
ret = []
if data['status'] == 'OK':
for c in data['result']:
if c['phase'] == 'BEFORE':
ret.append([c['id'], c['name'], c['startTimeSeconds']])
ret.sort(key=lambda x: x[2])
return ret
def list_to_table(contest_list):
ret = PrettyTable(['ID', 'Name', 'Start At'])
for c in contest_list:
# convert timestamp to d H:M
start_time = datetime.datetime.fromtimestamp(
c[2] - cur_timestamp).strftime('%d d %Hh%Mm')
ret.add_row([c[0], c[1], start_time])
return ret
print("Please wait...")
li = get_contest_list()
# clear terminal
os.system("cls")
print(list_to_table(li))
contest_id = input("Enter the contest ID to register:")
os.system("start https://codeforces.com/contestRegistration/" + contest_id)
| 29.461538 | 75 | 0.645779 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 288 | 0.250653 |
b610963ee1293b1c7ee709e8e8b2e82ded874788 | 3,406 | py | Python | src/main/python/util/java_runner.py | gsj601/ggp-hardware | ec9f293c43f9202f480c5f5cf81cee708694425c | [
"BSD-3-Clause"
] | null | null | null | src/main/python/util/java_runner.py | gsj601/ggp-hardware | ec9f293c43f9202f480c5f5cf81cee708694425c | [
"BSD-3-Clause"
] | null | null | null | src/main/python/util/java_runner.py | gsj601/ggp-hardware | ec9f293c43f9202f480c5f5cf81cee708694425c | [
"BSD-3-Clause"
] | null | null | null | """java_runner
A module for helping you run java as an external process.
"""
# Local libraries
import config_help
# Standard Imports
import subprocess
# Setting up logging:
# https://docs.python.org/2/howto/logging.html#configuring-logging-for-a-library
import logging
LOG = logging.getLogger(__name__)
LOG.addHandler(logging.NullHandler())
class JavaProcess(object):
"""JavaProcess:
Represents an external process that happens to be a java program.
Has built-in tools for building the appropriate classpath, etc.
"""
def __init__(self, config, class_loc, args=[]):
"""JavaProcess.__init__(self, class_loc, args=[])
Initializes an external Java process.
class_loc: the location, relative to classpath, where the
compiled Java class file lives.
args: a list of strings, where each is a command-line argument
to the external Java process. (Default: no args; empty list.)
"""
JavaProcess.config = JavaProcessConfig.configFrom_dict(config)
self._cp = self._construct_classpath_str()
self.class_loc = class_loc
self.args = args
self._process = None
self._stdout = None
self._stderr = None
LOG.debug("JavaProcess constructed for %s", self.class_loc)
return
def run(self):
"""JavaProcess.run(self):
Runs the external Java process.
Takes no parameters; the object should have its fields set
as intended before calling run().
"""
command_list = ["java"]
command_list.extend(["-cp", self._cp])
command_list.append(self.class_loc)
command_list.extend(self.args)
self._process = subprocess.Popen(command_list)
#self._process = subprocess.Popen(
# command_list, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
LOG.debug("Starting to run %s,%s",self.class_loc, self.args)
(o,e) = self._process.communicate()
LOG.debug("Finished java process, output: %s", str(o))
LOG.debug("Finished java process, error: %s", str(e))
return
def _construct_classpath_str(self):
"""_construct_classpath_str:
--> string
The string returned contains a Java classpath.
Requires the absolute path of the installation of ggp-base.
"""
absolute_prepend = JavaProcess.config.ggpBaseInstall_loc
cp = absolute_prepend + JavaProcess.config.javaBin_loc
lib_str = absolute_prepend + JavaProcess.config.javaLib_loc
for lib in JavaProcess.config.java_libs:
cp = cp + ":" + lib_str + lib + "/*"
return cp
class JavaProcessConfig(config_help.Config):
for_classname = "JavaProcess"
defaults = {
'java_libs': [
"Batik",
"Clojure",
"FlyingSaucer",
"Guava",
"Htmlparser",
"JFreeChart",
"JGoodiesForms",
"JUnit",
"Jython",
"javassist",
"reflections"
],
'ggpBaseInstall_loc' :
"/Users/gsj601/git/ggp-hardware.git/",
'javaBin_loc' :
"build/classes/main/",
'javaLib_loc' :
"lib/"
}
| 30.141593 | 80 | 0.590429 | 3,048 | 0.894891 | 0 | 0 | 0 | 0 | 0 | 0 | 1,653 | 0.48532 |
b611137ed77fff3f1dc6cb533c989b3abe68b3ac | 99 | py | Python | tests/test_fill.py | NioGreek/Clashgap | 8e066de522b139fbb30f742eea64a549c57d9b00 | [
"MIT"
] | 2 | 2021-07-20T17:09:06.000Z | 2021-07-22T03:05:24.000Z | tests/test_fill.py | NioGreek/Clashgap | 8e066de522b139fbb30f742eea64a549c57d9b00 | [
"MIT"
] | 2 | 2021-07-22T12:57:33.000Z | 2021-07-24T08:28:56.000Z | tests/test_fill.py | NioGreek/Clashgap | 8e066de522b139fbb30f742eea64a549c57d9b00 | [
"MIT"
] | 1 | 2021-07-21T07:03:19.000Z | 2021-07-21T07:03:19.000Z | import clashgap as cg
def test_fill():
assert cg.fill([["sp", "h"], "am"]) == ["spam", "ham"]
| 19.8 | 58 | 0.545455 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 22 | 0.222222 |
b6124c267a7355fff279f80fee851b3b716a05f0 | 458 | py | Python | Python/stack.py | uday256071/DataStructures-and-Algorithms | d5740a27a8e4141616307ec3771bc7ad95ff9f72 | [
"MIT"
] | null | null | null | Python/stack.py | uday256071/DataStructures-and-Algorithms | d5740a27a8e4141616307ec3771bc7ad95ff9f72 | [
"MIT"
] | null | null | null | Python/stack.py | uday256071/DataStructures-and-Algorithms | d5740a27a8e4141616307ec3771bc7ad95ff9f72 | [
"MIT"
] | null | null | null | class Stack():
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items==[]
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.items)
s=Stack()
s.isEmpty()
s.push(5)
s.push(56)
s.push('sdfg')
s.push(9)
print(s.peek())
print(s.pop())
print(s.peek())
print(s.size())
| 16.357143 | 31 | 0.572052 | 322 | 0.703057 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 0.0131 |
b612ccf587f22da1d2c787ccc0805bc747eb9271 | 1,278 | py | Python | examples/util/rectangular_binner.py | CU-NESS/pylinex | b6f342595b6a154e129eb303782e5268088f34d5 | [
"Apache-2.0"
] | null | null | null | examples/util/rectangular_binner.py | CU-NESS/pylinex | b6f342595b6a154e129eb303782e5268088f34d5 | [
"Apache-2.0"
] | null | null | null | examples/util/rectangular_binner.py | CU-NESS/pylinex | b6f342595b6a154e129eb303782e5268088f34d5 | [
"Apache-2.0"
] | null | null | null | """
File: examples/util/rectangular_binner.py
Author: Keith Tauscher
Date: 22 Sep 2018
Description: Example script showing the use of the RectangularBinner class.
"""
from __future__ import division
import numpy as np
import matplotlib.pyplot as pl
from pylinex import RectangularBinner
fontsize = 24
num_old_x_values = 1000
num_new_x_values = 20
wavelength = 0.4
old_x_values = np.linspace(-1, 1, num_old_x_values)[1:-1]
old_error = np.ones_like(old_x_values)
old_y_values =\
np.sin(2 * np.pi * old_x_values / wavelength) * np.sinh(old_x_values)
new_x_bin_edges = np.linspace(-1, 1, num_new_x_values + 1)
weights = np.ones_like(old_y_values)
binner = RectangularBinner(old_x_values, new_x_bin_edges)
new_x_values = binner.binned_x_values
(new_y_values, new_weights) = binner.bin(old_y_values, weights=weights,\
return_weights=True)
new_error = binner.bin_error(old_error, weights=weights, return_weights=False)
fig = pl.figure(figsize=(12,9))
ax = fig.add_subplot(111)
ax.plot(old_x_values, old_y_values, label='unbinned')
ax.plot(new_x_values, new_y_values, label='binned')
ax.legend(fontsize=fontsize)
ax.tick_params(labelsize=fontsize, width=2.5, length=7.5, which='major')
ax.tick_params(labelsize=fontsize, width=1.5, length=4.5, which='minor')
pl.show()
| 29.72093 | 78 | 0.777778 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 199 | 0.155712 |
b6132900005efba6ceb5ca456cea3f1dc6d5ba6f | 1,115 | py | Python | setup.py | gardsted/bulmate | 1a858f29a8f89bc3eaf40c94e8716f324c4f893c | [
"MIT"
] | null | null | null | setup.py | gardsted/bulmate | 1a858f29a8f89bc3eaf40c94e8716f324c4f893c | [
"MIT"
] | null | null | null | setup.py | gardsted/bulmate | 1a858f29a8f89bc3eaf40c94e8716f324c4f893c | [
"MIT"
] | null | null | null | __license__ = open('LICENSE').read()
version = open('VERSION').read()
from setuptools import setup
long_description = open('README.md').read()
setup(
name = 'bulmate',
version = version,
author = 'gardsted',
author_email = 'gardsted@gmail.com',
license = 'MIT',
url = 'https://github.com/gardsted/bulmate/',
description = 'Bulmate is a Python library for dominating CCCP with Bulma',
long_description = long_description,
long_description_content_type='text/markdown',
keywords = 'framework templating template html xhtml python html5 css bulma',
python_requires='>=3.5.*',
classifiers = [
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Markup :: HTML',
],
packages = ['bulmate'],
requirements = ["cccp", "dominate"],
include_package_data = True,
)
| 31.857143 | 87 | 0.671749 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 616 | 0.552466 |