max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
en2an/en2an.py
kdwycz/en2an
8
6612651
<filename>en2an/en2an.py import re from typing import Union from collections import Counter from . import utils from .an2en import An2En class En2An(object): def __init__(self) -> None: self.conf = utils.get_default_conf() self.all_nums = list(self.conf["number_unit"].keys()) self.ones_nums = "|".join(["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]) self.ten_nums = "|".join(["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]) self.tens_nums = "|".join(["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]) self.all_units = "|".join(self.conf["unit_low"]) self.ae = An2En() def en2an(self, inputs: str = None, mode: str = "strict") -> int: if inputs is not None: # 检查转换模式是否有效 if mode not in ["strict", "normal", "smart"]: raise ValueError("mode 仅支持 strict normal smart 三种!") # 检查输入数据是否有效 sign, inputs, data_type = self.check_input_data_is_valid(inputs, mode) if data_type == "integer": # 不包含小数的输入 output = self.integer_convert(inputs) elif data_type == "decimal": point_index = inputs.index("point") integer_data = inputs[:point_index] decimal_data = inputs[point_index+1:] output = self.integer_convert(integer_data) + self.decimal_convert(decimal_data) elif data_type == "all_num": output = self.direct_convert(inputs) else: raise ValueError(f"输入格式错误:{inputs}!") else: raise ValueError("输入数据为空!") return sign * output def check_input_data_is_valid(self, input_check_data, mode): # 以空格切分,并转化成小写 check_data = [] for data in input_check_data.split(" "): low_data = data.lower() if "-" in low_data: check_data.extend(low_data.split("-")) else: check_data.append(low_data) # 正负号 sign = 1 if mode == "strict": strict_check_key = self.all_nums + ["minus", "and", "point"] for data in check_data: if data not in strict_check_key: raise ValueError(f"当前为{mode}模式,输入的数据不在转化范围内:{data}!") # 确定正负号 if check_data[0] == "minus": check_data = check_data[1:] sign = -1 elif mode == "normal": normal_check_key = self.all_nums + ["minus", "negative", "and", "point", "a", ",", ","] for data in check_data: if data not in normal_check_key: raise ValueError(f"当前为{mode}模式,输入的数据不在转化范围内:{data}!") # 确定正负号 if check_data[0] in ["minus", "negative"]: check_data = check_data[1:] sign = -1 elif mode == "smart": smart_check_key = self.all_nums + ["minus", "and", "a", "point", ",", ","] + [str(num) for num in range(10)] for data in check_data: if data not in smart_check_key: result = re.search(r"\d+", data) if result: if result.group() == data: break raise ValueError(f"当前为{mode}模式,输入的数据不在转化范围内:{data}!") # 确定正负号 if check_data[0] in ["minus", "negative"]: check_data = check_data[1:] sign = -1 def an2en_sub(matched): return self.ae.an2en(matched.group()).replace("-", " ") check_data = re.sub(r"\d+", an2en_sub, " ".join(check_data)).split(" ") mode = "normal" if "point" in check_data: point_number = Counter(check_data)["point"] if point_number == 1: point_index = check_data.index("point") integer_data = check_data[:point_index - 1] decimal_data = check_data[point_index:] else: raise ValueError("数据中包含不止一个 point!") else: integer_data = check_data decimal_data = None # 整数部分检查 twenty_to_hundred_list = [] for tens in self.tens_nums.split("|"): for ones in self.ones_nums.split("|"): twenty_to_hundred_list.append(tens+ones) twenty_to_hundred = "|".join(twenty_to_hundred_list) under_hundred = f"{twenty_to_hundred}|{self.tens_nums}|{self.ten_nums}|{self.ones_nums}|zero" compile_group = f"(({self.ones_nums})hundred)?(and)?({under_hundred})?" ptn_normal = re.compile(f"({compile_group}({self.all_units}))*({compile_group})?") check_str_data = "".join(integer_data) re_normal = ptn_normal.search(check_str_data) if re_normal: if re_normal.group() != check_str_data: if mode == "strict": raise ValueError(f"不符合格式的数据:{integer_data}") elif mode == "normal": # 纯数字情况 ptn_all_num = re.compile(f"({self.ones_nums})+") re_all_num = ptn_all_num.search(check_str_data) if re_all_num: if re_all_num.group() != check_str_data: raise ValueError(f"不符合格式的数据:{check_data}") else: return sign, check_data, "all_num" else: raise ValueError(f"不符合格式的数据:{integer_data}") else: if decimal_data: return sign, check_data, "decimal" else: if check_data[-1] == "point": if mode == "strict": raise ValueError(f"不符合格式的数据:{check_data}") elif mode == "normal": return sign, check_data, "decimal" else: return sign, check_data, "integer" else: if mode == "strict": raise ValueError(f"不符合格式的数据:{integer_data}") elif mode == "normal": if decimal_data: return sign, check_data, "decimal" else: raise ValueError(f"不符合格式的数据:{integer_data}") else: raise ValueError(f"不符合格式的数据:{integer_data}") def integer_convert(self, integer_data: list) -> int: unit = 1 temp_num = 0 temp_unit = 1 output_integer = 0 # 核心 for index, en_num in enumerate(reversed(integer_data)): num = self.conf["number_unit"].get(en_num) # and 转化后是 None 应该去除 if num is not None: if num % 1000 == 0 and num != 0: output_integer += temp_num * unit unit = num temp_num = 0 else: if num < unit or unit == 1: if num == 100: temp_unit = num else: temp_num += int(num) * temp_unit temp_unit = 1 output_integer += temp_num * unit return output_integer def decimal_convert(self, decimal_data: list) -> float: len_decimal_data = len(decimal_data) if len_decimal_data > 15: print("warning: 小数部分长度为{},超过15位有效精度长度,将自动截取前15位!".format( len_decimal_data)) decimal_data = decimal_data[:15] len_decimal_data = 15 output_decimal = 0 for index in range(len(decimal_data) - 1, -1, -1): unit_key = self.conf["number_unit"].get(decimal_data[index]) output_decimal += unit_key * 10 ** -(index + 1) # 处理精度溢出问题 output_decimal = round(output_decimal, len_decimal_data) return output_decimal def direct_convert(self, data: list) -> Union[int, float]: output_data = 0 if "point" in data: point_index = data.index("point") for index_integer in range(point_index - 1, -1, -1): unit_key = self.conf["number_unit"].get(data[index_integer]) output_data += unit_key * 10 ** (point_index - index_integer - 1) for index_decimal in range(len(data) - 1, point_index, -1): unit_key = self.conf["number_unit"].get(data[index_decimal]) output_data += unit_key * 10 ** -(index_decimal - point_index) # 处理精度溢出问题 output_data = round(output_data, len(data) - point_index) else: for index in range(len(data) - 1, -1, -1): unit_key = self.conf["number_unit"].get(data[index]) output_data += unit_key * 10 ** (len(data) - index - 1) return output_data
<filename>en2an/en2an.py import re from typing import Union from collections import Counter from . import utils from .an2en import An2En class En2An(object): def __init__(self) -> None: self.conf = utils.get_default_conf() self.all_nums = list(self.conf["number_unit"].keys()) self.ones_nums = "|".join(["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]) self.ten_nums = "|".join(["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]) self.tens_nums = "|".join(["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]) self.all_units = "|".join(self.conf["unit_low"]) self.ae = An2En() def en2an(self, inputs: str = None, mode: str = "strict") -> int: if inputs is not None: # 检查转换模式是否有效 if mode not in ["strict", "normal", "smart"]: raise ValueError("mode 仅支持 strict normal smart 三种!") # 检查输入数据是否有效 sign, inputs, data_type = self.check_input_data_is_valid(inputs, mode) if data_type == "integer": # 不包含小数的输入 output = self.integer_convert(inputs) elif data_type == "decimal": point_index = inputs.index("point") integer_data = inputs[:point_index] decimal_data = inputs[point_index+1:] output = self.integer_convert(integer_data) + self.decimal_convert(decimal_data) elif data_type == "all_num": output = self.direct_convert(inputs) else: raise ValueError(f"输入格式错误:{inputs}!") else: raise ValueError("输入数据为空!") return sign * output def check_input_data_is_valid(self, input_check_data, mode): # 以空格切分,并转化成小写 check_data = [] for data in input_check_data.split(" "): low_data = data.lower() if "-" in low_data: check_data.extend(low_data.split("-")) else: check_data.append(low_data) # 正负号 sign = 1 if mode == "strict": strict_check_key = self.all_nums + ["minus", "and", "point"] for data in check_data: if data not in strict_check_key: raise ValueError(f"当前为{mode}模式,输入的数据不在转化范围内:{data}!") # 确定正负号 if check_data[0] == "minus": check_data = check_data[1:] sign = -1 elif mode == "normal": normal_check_key = self.all_nums + ["minus", "negative", "and", "point", "a", ",", ","] for data in check_data: if data not in normal_check_key: raise ValueError(f"当前为{mode}模式,输入的数据不在转化范围内:{data}!") # 确定正负号 if check_data[0] in ["minus", "negative"]: check_data = check_data[1:] sign = -1 elif mode == "smart": smart_check_key = self.all_nums + ["minus", "and", "a", "point", ",", ","] + [str(num) for num in range(10)] for data in check_data: if data not in smart_check_key: result = re.search(r"\d+", data) if result: if result.group() == data: break raise ValueError(f"当前为{mode}模式,输入的数据不在转化范围内:{data}!") # 确定正负号 if check_data[0] in ["minus", "negative"]: check_data = check_data[1:] sign = -1 def an2en_sub(matched): return self.ae.an2en(matched.group()).replace("-", " ") check_data = re.sub(r"\d+", an2en_sub, " ".join(check_data)).split(" ") mode = "normal" if "point" in check_data: point_number = Counter(check_data)["point"] if point_number == 1: point_index = check_data.index("point") integer_data = check_data[:point_index - 1] decimal_data = check_data[point_index:] else: raise ValueError("数据中包含不止一个 point!") else: integer_data = check_data decimal_data = None # 整数部分检查 twenty_to_hundred_list = [] for tens in self.tens_nums.split("|"): for ones in self.ones_nums.split("|"): twenty_to_hundred_list.append(tens+ones) twenty_to_hundred = "|".join(twenty_to_hundred_list) under_hundred = f"{twenty_to_hundred}|{self.tens_nums}|{self.ten_nums}|{self.ones_nums}|zero" compile_group = f"(({self.ones_nums})hundred)?(and)?({under_hundred})?" ptn_normal = re.compile(f"({compile_group}({self.all_units}))*({compile_group})?") check_str_data = "".join(integer_data) re_normal = ptn_normal.search(check_str_data) if re_normal: if re_normal.group() != check_str_data: if mode == "strict": raise ValueError(f"不符合格式的数据:{integer_data}") elif mode == "normal": # 纯数字情况 ptn_all_num = re.compile(f"({self.ones_nums})+") re_all_num = ptn_all_num.search(check_str_data) if re_all_num: if re_all_num.group() != check_str_data: raise ValueError(f"不符合格式的数据:{check_data}") else: return sign, check_data, "all_num" else: raise ValueError(f"不符合格式的数据:{integer_data}") else: if decimal_data: return sign, check_data, "decimal" else: if check_data[-1] == "point": if mode == "strict": raise ValueError(f"不符合格式的数据:{check_data}") elif mode == "normal": return sign, check_data, "decimal" else: return sign, check_data, "integer" else: if mode == "strict": raise ValueError(f"不符合格式的数据:{integer_data}") elif mode == "normal": if decimal_data: return sign, check_data, "decimal" else: raise ValueError(f"不符合格式的数据:{integer_data}") else: raise ValueError(f"不符合格式的数据:{integer_data}") def integer_convert(self, integer_data: list) -> int: unit = 1 temp_num = 0 temp_unit = 1 output_integer = 0 # 核心 for index, en_num in enumerate(reversed(integer_data)): num = self.conf["number_unit"].get(en_num) # and 转化后是 None 应该去除 if num is not None: if num % 1000 == 0 and num != 0: output_integer += temp_num * unit unit = num temp_num = 0 else: if num < unit or unit == 1: if num == 100: temp_unit = num else: temp_num += int(num) * temp_unit temp_unit = 1 output_integer += temp_num * unit return output_integer def decimal_convert(self, decimal_data: list) -> float: len_decimal_data = len(decimal_data) if len_decimal_data > 15: print("warning: 小数部分长度为{},超过15位有效精度长度,将自动截取前15位!".format( len_decimal_data)) decimal_data = decimal_data[:15] len_decimal_data = 15 output_decimal = 0 for index in range(len(decimal_data) - 1, -1, -1): unit_key = self.conf["number_unit"].get(decimal_data[index]) output_decimal += unit_key * 10 ** -(index + 1) # 处理精度溢出问题 output_decimal = round(output_decimal, len_decimal_data) return output_decimal def direct_convert(self, data: list) -> Union[int, float]: output_data = 0 if "point" in data: point_index = data.index("point") for index_integer in range(point_index - 1, -1, -1): unit_key = self.conf["number_unit"].get(data[index_integer]) output_data += unit_key * 10 ** (point_index - index_integer - 1) for index_decimal in range(len(data) - 1, point_index, -1): unit_key = self.conf["number_unit"].get(data[index_decimal]) output_data += unit_key * 10 ** -(index_decimal - point_index) # 处理精度溢出问题 output_data = round(output_data, len(data) - point_index) else: for index in range(len(data) - 1, -1, -1): unit_key = self.conf["number_unit"].get(data[index]) output_data += unit_key * 10 ** (len(data) - index - 1) return output_data
zh
0.978102
# 检查转换模式是否有效 # 检查输入数据是否有效 # 不包含小数的输入 # 以空格切分,并转化成小写 # 正负号 # 确定正负号 # 确定正负号 # 确定正负号 # 整数部分检查 # 纯数字情况 # 核心 # and 转化后是 None 应该去除 # 处理精度溢出问题 # 处理精度溢出问题
2.86961
3
src/backend/utils/__init__.py
tonyLyx1/CSC4001-Better-SIS
2
6612652
<reponame>tonyLyx1/CSC4001-Better-SIS from .time_utils import * from .printing import *
from .time_utils import * from .printing import *
none
1
1.089068
1
generator.py
armstrtw/py.misc
0
6612653
def odd(start: int): n = start while True: if n % 2 == 1: yield n n += 1 def even_sq(start: int): n = start while True: if n % 2 == 0: yield n ** 2 n += 1 if __name__ == "__main__": print("odd gen:") odd_gen = odd(2) print(next(odd_gen)) print(next(odd_gen)) print(next(odd_gen)) print(next(odd_gen)) print("even_sq gen:") even_sqg = even_sq(5) print(next(even_sqg)) print(next(even_sqg)) print(next(even_sqg)) print(next(even_sqg)) ## generator comprehension esqg = (i ** 2 for i in range(1_000_000) if i % 2 == 0)
def odd(start: int): n = start while True: if n % 2 == 1: yield n n += 1 def even_sq(start: int): n = start while True: if n % 2 == 0: yield n ** 2 n += 1 if __name__ == "__main__": print("odd gen:") odd_gen = odd(2) print(next(odd_gen)) print(next(odd_gen)) print(next(odd_gen)) print(next(odd_gen)) print("even_sq gen:") even_sqg = even_sq(5) print(next(even_sqg)) print(next(even_sqg)) print(next(even_sqg)) print(next(even_sqg)) ## generator comprehension esqg = (i ** 2 for i in range(1_000_000) if i % 2 == 0)
en
0.207276
## generator comprehension
4.164669
4
recipes/migrations/0006_auto_20200411_0309.py
ggetzie/nnr
0
6612654
# Generated by Django 3.0.1 on 2020-04-11 03:09 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('recipes', '0005_auto_20200411_0249'), ] migration = """ CREATE FUNCTION recipes_trigger() RETURNS trigger AS $$ begin new.search_vector := setweight(to_tsvector('pg_catalog.english', coalesce(new.title,'')), 'A') || setweight(to_tsvector('pg_catalog.english', coalesce(new.ingredients_text,'')), 'B') || setweight(to_tsvector('pg_catalog.english', coalesce(new.instructions_text,'')), 'B'); return new; end $$ LANGUAGE plpgsql; CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE ON recipes_recipe FOR EACH ROW EXECUTE PROCEDURE recipes_trigger(); """ reverse_migration = ''' DROP TRIGGER tsvectorupdate ON recipes_recipe; ''' operations = [ migrations.RunSQL(migration, reverse_migration) ]
# Generated by Django 3.0.1 on 2020-04-11 03:09 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('recipes', '0005_auto_20200411_0249'), ] migration = """ CREATE FUNCTION recipes_trigger() RETURNS trigger AS $$ begin new.search_vector := setweight(to_tsvector('pg_catalog.english', coalesce(new.title,'')), 'A') || setweight(to_tsvector('pg_catalog.english', coalesce(new.ingredients_text,'')), 'B') || setweight(to_tsvector('pg_catalog.english', coalesce(new.instructions_text,'')), 'B'); return new; end $$ LANGUAGE plpgsql; CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE ON recipes_recipe FOR EACH ROW EXECUTE PROCEDURE recipes_trigger(); """ reverse_migration = ''' DROP TRIGGER tsvectorupdate ON recipes_recipe; ''' operations = [ migrations.RunSQL(migration, reverse_migration) ]
en
0.416318
# Generated by Django 3.0.1 on 2020-04-11 03:09 CREATE FUNCTION recipes_trigger() RETURNS trigger AS $$ begin new.search_vector := setweight(to_tsvector('pg_catalog.english', coalesce(new.title,'')), 'A') || setweight(to_tsvector('pg_catalog.english', coalesce(new.ingredients_text,'')), 'B') || setweight(to_tsvector('pg_catalog.english', coalesce(new.instructions_text,'')), 'B'); return new; end $$ LANGUAGE plpgsql; CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE ON recipes_recipe FOR EACH ROW EXECUTE PROCEDURE recipes_trigger(); DROP TRIGGER tsvectorupdate ON recipes_recipe;
1.755624
2
app/models/match.py
ninoseki/uzen
76
6612655
<gh_stars>10-100 from typing import TYPE_CHECKING from tortoise.fields.base import CASCADE from tortoise.fields.data import JSONField from tortoise.fields.relational import ( ForeignKeyField, ForeignKeyNullableRelation, ForeignKeyRelation, ) from app import schemas from app.models.base import AbstractBaseModel from app.models.mixin import TimestampMixin if TYPE_CHECKING: from app.models import Rule, Script, Snapshot class Match(TimestampMixin, AbstractBaseModel): matches = JSONField() snapshot: ForeignKeyRelation["Snapshot"] = ForeignKeyField( "models.Snapshot", on_delete=CASCADE ) rule: ForeignKeyRelation["Rule"] = ForeignKeyField("models.Rule", on_delete=CASCADE) script: ForeignKeyNullableRelation["Script"] = ForeignKeyField( "models.Script", null=True, on_delete=CASCADE ) def to_model(self) -> schemas.Match: return schemas.Match.from_orm(self) class Meta: table = "matches" ordering = ["-created_at"]
from typing import TYPE_CHECKING from tortoise.fields.base import CASCADE from tortoise.fields.data import JSONField from tortoise.fields.relational import ( ForeignKeyField, ForeignKeyNullableRelation, ForeignKeyRelation, ) from app import schemas from app.models.base import AbstractBaseModel from app.models.mixin import TimestampMixin if TYPE_CHECKING: from app.models import Rule, Script, Snapshot class Match(TimestampMixin, AbstractBaseModel): matches = JSONField() snapshot: ForeignKeyRelation["Snapshot"] = ForeignKeyField( "models.Snapshot", on_delete=CASCADE ) rule: ForeignKeyRelation["Rule"] = ForeignKeyField("models.Rule", on_delete=CASCADE) script: ForeignKeyNullableRelation["Script"] = ForeignKeyField( "models.Script", null=True, on_delete=CASCADE ) def to_model(self) -> schemas.Match: return schemas.Match.from_orm(self) class Meta: table = "matches" ordering = ["-created_at"]
none
1
2.161698
2
tests/test_objectdef.py
Penlect/emqxlwm2m
2
6612656
<reponame>Penlect/emqxlwm2m # pylint: disable=maybe-no-member # Built-in import logging import unittest from unittest.mock import MagicMock, AsyncMock # Package from emqxlwm2m import lwm2m from emqxlwm2m.oma import Device from emqxlwm2m.engines.emqx import EMQxEngine from emqxlwm2m.engines.async_emqx import EMQxEngine as AsyncEMQxEngine logging.basicConfig(level=logging.DEBUG) EP = "my:endpoint" class TestDevice(unittest.TestCase): def setUp(self): print() c = MagicMock() self.engine = EMQxEngine(c) self.engine.send = MagicMock() self.engine.on_connect(None, None, None, None) self.engine.__enter__() self.ep = self.engine.endpoint(EP) def test_attributes(self): self.assertEqual(Device.oid, 3) self.assertTrue(Device.mandatory) self.assertFalse(Device.multiple) def test_path(self): self.assertEqual(self.ep[Device].path, "/3") self.assertEqual(self.ep[Device][0].path, "/3/0") self.assertEqual(self.ep[Device][1].path, "/3/1") self.assertEqual(self.ep[Device][2].model_number.path, "/3/2/1") def test_read_obj(self): self.ep[Device].read() req = lwm2m.ReadRequest(EP, "/3") self.engine.send.assert_called_once_with(req, None) def test_read_instance(self): self.ep[Device][0].read() req = lwm2m.ReadRequest(EP, "/3/0") self.engine.send.assert_called_once_with(req, None) def test_read(self): self.ep[Device].manufacturer.read() req = lwm2m.ReadRequest(EP, "/3/0/0") self.engine.send.assert_called_once_with(req, None) def test_discover(self): self.ep[Device].model_number.discover() req = lwm2m.DiscoverRequest(EP, "/3/0/1") self.engine.send.assert_called_once_with(req, None) def test_write(self): self.ep[Device][1].current_time.write(123) req = lwm2m.WriteRequest(EP, {"/3/1/13": 123}) self.engine.send.assert_called_once_with(req, None) def test_write_batch(self): self.ep[Device][0].write({"13": 123, "14": "+2"}) req = lwm2m.WriteRequest(EP, {"/3/0/13": 123, "/3/0/14": "+2"}) self.engine.send.assert_called_once_with(req, None) def test_write_attr(self): self.ep[Device][0].battery_level.write_attr(pmin=10, gt=123) req = lwm2m.WriteAttrRequest(EP, "/3/0/9", pmin=10, gt=123) self.engine.send.assert_called_once_with(req, None) def test_execute(self): self.ep[Device].reset_error_code.execute("") req = lwm2m.ExecuteRequest(EP, "/3/0/12", "") self.engine.send.assert_called_once_with(req, None) def test_create(self): self.ep[Device][2].create({"13": 123, "14": "+2"}) req = lwm2m.CreateRequest(EP, {"/3/2/13": 123, "/3/2/14": "+2"}) self.engine.send.assert_called_once_with(req, None) def test_delete(self): self.ep[Device][2].delete() req = lwm2m.DeleteRequest(EP, "/3/2") self.engine.send.assert_called_once_with(req, None) def test_observe(self): self.ep[Device].timezone.observe() req = lwm2m.ObserveRequest(EP, "/3/0/15") self.engine.send.assert_called_once_with(req, None) def test_cancel_observe(self): self.ep[Device].timezone.cancel_observe() req = lwm2m.CancelObserveRequest(EP, "/3/0/15") self.engine.send.assert_called_once_with(req, None) def test_temporary_observe(self): req1 = lwm2m.ObserveRequest(EP, "/3/0/15") with self.ep[Device].timezone.temporary_observe() as resp: self.assertTrue(hasattr(resp, "notifications")) self.engine.send.assert_called_once_with(req1, None) req2 = lwm2m.CancelObserveRequest(EP, "/3/0/15") self.engine.send.assert_called_with(req2, None) class TestAsyncDevice(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): print() c = AsyncMock() c._client = MagicMock() self.engine = AsyncEMQxEngine(c) self.engine.send = AsyncMock() self.engine.send.side_effect = MagicMock() self.ep = await self.engine.endpoint(EP) async def asyncTearDown(self): del self.ep # Make sure weakref callback is called before loop close async def test_path(self): self.assertEqual(self.ep[Device].path, "/3") self.assertEqual(self.ep[Device][0].path, "/3/0") self.assertEqual(self.ep[Device][1].path, "/3/1") self.assertEqual(self.ep[Device][2].model_number.path, "/3/2/1") async def test_read_obj(self): await self.ep[Device].read() req = lwm2m.ReadRequest(EP, "/3") self.engine.send.assert_awaited_once_with(req, None) async def test_read_instance(self): await self.ep[Device][0].read() req = lwm2m.ReadRequest(EP, "/3/0") self.engine.send.assert_awaited_once_with(req, None) async def test_read(self): await self.ep[Device].manufacturer.read() req = lwm2m.ReadRequest(EP, "/3/0/0") self.engine.send.assert_awaited_once_with(req, None) async def test_discover(self): await self.ep[Device].model_number.discover() req = lwm2m.DiscoverRequest(EP, "/3/0/1") self.engine.send.assert_awaited_once_with(req, None) async def test_write(self): await self.ep[Device][1].current_time.write(123) req = lwm2m.WriteRequest(EP, {"/3/1/13": 123}) self.engine.send.assert_awaited_once_with(req, None) async def test_write_batch(self): await self.ep[Device][0].write({"13": 123, "14": "+2"}) req = lwm2m.WriteRequest(EP, {"/3/0/13": 123, "/3/0/14": "+2"}) self.engine.send.assert_awaited_once_with(req, None) async def test_write_attr(self): await self.ep[Device][0].battery_level.write_attr(pmin=10, gt=123) req = lwm2m.WriteAttrRequest(EP, "/3/0/9", pmin=10, gt=123) self.engine.send.assert_awaited_once_with(req, None) async def test_execute(self): await self.ep[Device].reset_error_code.execute("") req = lwm2m.ExecuteRequest(EP, "/3/0/12", "") self.engine.send.assert_awaited_once_with(req, None) async def test_create(self): await self.ep[Device][2].create({"13": 123, "14": "+2"}) req = lwm2m.CreateRequest(EP, {"/3/2/13": 123, "/3/2/14": "+2"}) self.engine.send.assert_awaited_once_with(req, None) async def test_delete(self): await self.ep[Device][2].delete() req = lwm2m.DeleteRequest(EP, "/3/2") self.engine.send.assert_awaited_once_with(req, None) async def test_observe(self): await self.ep[Device].timezone.observe() req = lwm2m.ObserveRequest(EP, "/3/0/15") self.engine.send.assert_awaited_once_with(req, None) async def test_cancel_observe(self): await self.ep[Device].timezone.cancel_observe() req = lwm2m.CancelObserveRequest(EP, "/3/0/15") self.engine.send.assert_awaited_once_with(req, None) async def test_temporary_observe(self): req1 = lwm2m.ObserveRequest(EP, "/3/0/15") async with self.ep[Device].timezone.temporary_observe() as resp: self.assertTrue(hasattr(resp, "notifications")) self.engine.send.assert_awaited_once_with(req1, None) req2 = lwm2m.CancelObserveRequest(EP, "/3/0/15") self.engine.send.assert_awaited_with(req2, None)
# pylint: disable=maybe-no-member # Built-in import logging import unittest from unittest.mock import MagicMock, AsyncMock # Package from emqxlwm2m import lwm2m from emqxlwm2m.oma import Device from emqxlwm2m.engines.emqx import EMQxEngine from emqxlwm2m.engines.async_emqx import EMQxEngine as AsyncEMQxEngine logging.basicConfig(level=logging.DEBUG) EP = "my:endpoint" class TestDevice(unittest.TestCase): def setUp(self): print() c = MagicMock() self.engine = EMQxEngine(c) self.engine.send = MagicMock() self.engine.on_connect(None, None, None, None) self.engine.__enter__() self.ep = self.engine.endpoint(EP) def test_attributes(self): self.assertEqual(Device.oid, 3) self.assertTrue(Device.mandatory) self.assertFalse(Device.multiple) def test_path(self): self.assertEqual(self.ep[Device].path, "/3") self.assertEqual(self.ep[Device][0].path, "/3/0") self.assertEqual(self.ep[Device][1].path, "/3/1") self.assertEqual(self.ep[Device][2].model_number.path, "/3/2/1") def test_read_obj(self): self.ep[Device].read() req = lwm2m.ReadRequest(EP, "/3") self.engine.send.assert_called_once_with(req, None) def test_read_instance(self): self.ep[Device][0].read() req = lwm2m.ReadRequest(EP, "/3/0") self.engine.send.assert_called_once_with(req, None) def test_read(self): self.ep[Device].manufacturer.read() req = lwm2m.ReadRequest(EP, "/3/0/0") self.engine.send.assert_called_once_with(req, None) def test_discover(self): self.ep[Device].model_number.discover() req = lwm2m.DiscoverRequest(EP, "/3/0/1") self.engine.send.assert_called_once_with(req, None) def test_write(self): self.ep[Device][1].current_time.write(123) req = lwm2m.WriteRequest(EP, {"/3/1/13": 123}) self.engine.send.assert_called_once_with(req, None) def test_write_batch(self): self.ep[Device][0].write({"13": 123, "14": "+2"}) req = lwm2m.WriteRequest(EP, {"/3/0/13": 123, "/3/0/14": "+2"}) self.engine.send.assert_called_once_with(req, None) def test_write_attr(self): self.ep[Device][0].battery_level.write_attr(pmin=10, gt=123) req = lwm2m.WriteAttrRequest(EP, "/3/0/9", pmin=10, gt=123) self.engine.send.assert_called_once_with(req, None) def test_execute(self): self.ep[Device].reset_error_code.execute("") req = lwm2m.ExecuteRequest(EP, "/3/0/12", "") self.engine.send.assert_called_once_with(req, None) def test_create(self): self.ep[Device][2].create({"13": 123, "14": "+2"}) req = lwm2m.CreateRequest(EP, {"/3/2/13": 123, "/3/2/14": "+2"}) self.engine.send.assert_called_once_with(req, None) def test_delete(self): self.ep[Device][2].delete() req = lwm2m.DeleteRequest(EP, "/3/2") self.engine.send.assert_called_once_with(req, None) def test_observe(self): self.ep[Device].timezone.observe() req = lwm2m.ObserveRequest(EP, "/3/0/15") self.engine.send.assert_called_once_with(req, None) def test_cancel_observe(self): self.ep[Device].timezone.cancel_observe() req = lwm2m.CancelObserveRequest(EP, "/3/0/15") self.engine.send.assert_called_once_with(req, None) def test_temporary_observe(self): req1 = lwm2m.ObserveRequest(EP, "/3/0/15") with self.ep[Device].timezone.temporary_observe() as resp: self.assertTrue(hasattr(resp, "notifications")) self.engine.send.assert_called_once_with(req1, None) req2 = lwm2m.CancelObserveRequest(EP, "/3/0/15") self.engine.send.assert_called_with(req2, None) class TestAsyncDevice(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): print() c = AsyncMock() c._client = MagicMock() self.engine = AsyncEMQxEngine(c) self.engine.send = AsyncMock() self.engine.send.side_effect = MagicMock() self.ep = await self.engine.endpoint(EP) async def asyncTearDown(self): del self.ep # Make sure weakref callback is called before loop close async def test_path(self): self.assertEqual(self.ep[Device].path, "/3") self.assertEqual(self.ep[Device][0].path, "/3/0") self.assertEqual(self.ep[Device][1].path, "/3/1") self.assertEqual(self.ep[Device][2].model_number.path, "/3/2/1") async def test_read_obj(self): await self.ep[Device].read() req = lwm2m.ReadRequest(EP, "/3") self.engine.send.assert_awaited_once_with(req, None) async def test_read_instance(self): await self.ep[Device][0].read() req = lwm2m.ReadRequest(EP, "/3/0") self.engine.send.assert_awaited_once_with(req, None) async def test_read(self): await self.ep[Device].manufacturer.read() req = lwm2m.ReadRequest(EP, "/3/0/0") self.engine.send.assert_awaited_once_with(req, None) async def test_discover(self): await self.ep[Device].model_number.discover() req = lwm2m.DiscoverRequest(EP, "/3/0/1") self.engine.send.assert_awaited_once_with(req, None) async def test_write(self): await self.ep[Device][1].current_time.write(123) req = lwm2m.WriteRequest(EP, {"/3/1/13": 123}) self.engine.send.assert_awaited_once_with(req, None) async def test_write_batch(self): await self.ep[Device][0].write({"13": 123, "14": "+2"}) req = lwm2m.WriteRequest(EP, {"/3/0/13": 123, "/3/0/14": "+2"}) self.engine.send.assert_awaited_once_with(req, None) async def test_write_attr(self): await self.ep[Device][0].battery_level.write_attr(pmin=10, gt=123) req = lwm2m.WriteAttrRequest(EP, "/3/0/9", pmin=10, gt=123) self.engine.send.assert_awaited_once_with(req, None) async def test_execute(self): await self.ep[Device].reset_error_code.execute("") req = lwm2m.ExecuteRequest(EP, "/3/0/12", "") self.engine.send.assert_awaited_once_with(req, None) async def test_create(self): await self.ep[Device][2].create({"13": 123, "14": "+2"}) req = lwm2m.CreateRequest(EP, {"/3/2/13": 123, "/3/2/14": "+2"}) self.engine.send.assert_awaited_once_with(req, None) async def test_delete(self): await self.ep[Device][2].delete() req = lwm2m.DeleteRequest(EP, "/3/2") self.engine.send.assert_awaited_once_with(req, None) async def test_observe(self): await self.ep[Device].timezone.observe() req = lwm2m.ObserveRequest(EP, "/3/0/15") self.engine.send.assert_awaited_once_with(req, None) async def test_cancel_observe(self): await self.ep[Device].timezone.cancel_observe() req = lwm2m.CancelObserveRequest(EP, "/3/0/15") self.engine.send.assert_awaited_once_with(req, None) async def test_temporary_observe(self): req1 = lwm2m.ObserveRequest(EP, "/3/0/15") async with self.ep[Device].timezone.temporary_observe() as resp: self.assertTrue(hasattr(resp, "notifications")) self.engine.send.assert_awaited_once_with(req1, None) req2 = lwm2m.CancelObserveRequest(EP, "/3/0/15") self.engine.send.assert_awaited_with(req2, None)
en
0.916754
# pylint: disable=maybe-no-member # Built-in # Package # Make sure weakref callback is called before loop close
2.346929
2
tests/test_config.py
thecarebot/carebot
50
6612657
#!/usr/bin/env python import app_config try: import unittest2 as unittest except ImportError: import unittest from util.config import Config app_config.TEAMS = { 'default': { 'channel': 'default-channel', 'ga_org_id': 'DEFAULT-ID', }, 'viz': { 'channel': 'visuals-graphics', 'ga_org_id': 'visuals-sample-id', }, 'carebot': { 'channel': 'carebot-dev', 'ga_org_id': 'sample', }, } class TestConfig(unittest.TestCase): def test_config_get_team_for_channel(self): config = Config() team = config.get_team_for_channel('carebot-dev') self.assertEqual(team, 'carebot') def test_config_get_team_for_channel_default(self): config = Config() team = config.get_team_for_channel('doesnotexist') self.assertEqual(team, 'default') def test_config_get_default_team(self): config = Config() team = config.get_default_team() self.assertEqual(team['ga_org_id'], 'DEFAULT-ID') def test_config_get_team_for_story(self): config = Config() class FakeStory: team = 'viz' team = config.get_team_for_story(FakeStory) self.assertEqual(team['ga_org_id'], 'visuals-sample-id') def test_config_get_team_for_story_none(self): config = Config() class FakeStory: team = 'no-such-team' team = config.get_team_for_story(FakeStory) self.assertEqual(team['ga_org_id'], 'DEFAULT-ID')
#!/usr/bin/env python import app_config try: import unittest2 as unittest except ImportError: import unittest from util.config import Config app_config.TEAMS = { 'default': { 'channel': 'default-channel', 'ga_org_id': 'DEFAULT-ID', }, 'viz': { 'channel': 'visuals-graphics', 'ga_org_id': 'visuals-sample-id', }, 'carebot': { 'channel': 'carebot-dev', 'ga_org_id': 'sample', }, } class TestConfig(unittest.TestCase): def test_config_get_team_for_channel(self): config = Config() team = config.get_team_for_channel('carebot-dev') self.assertEqual(team, 'carebot') def test_config_get_team_for_channel_default(self): config = Config() team = config.get_team_for_channel('doesnotexist') self.assertEqual(team, 'default') def test_config_get_default_team(self): config = Config() team = config.get_default_team() self.assertEqual(team['ga_org_id'], 'DEFAULT-ID') def test_config_get_team_for_story(self): config = Config() class FakeStory: team = 'viz' team = config.get_team_for_story(FakeStory) self.assertEqual(team['ga_org_id'], 'visuals-sample-id') def test_config_get_team_for_story_none(self): config = Config() class FakeStory: team = 'no-such-team' team = config.get_team_for_story(FakeStory) self.assertEqual(team['ga_org_id'], 'DEFAULT-ID')
ru
0.26433
#!/usr/bin/env python
2.894359
3
tests/compare_test_data.py
ty-zhao/QGL
33
6612658
<reponame>ty-zhao/QGL<filename>tests/compare_test_data.py<gh_stars>10-100 import os import sys import glob from builtins import input from QGL import * import QGL BASE_AWG_DIR = QGL.config.AWGDir BASE_TEST_DIR = './test_data/awg/' def compare_sequences(seq_filter=""): test_subdirs = ['TestAPS1', 'TestAPS2'] for subdir in test_subdirs: testdirs = glob.glob(os.path.join(BASE_TEST_DIR, subdir, '*')) for test in testdirs: # build up subdirectory name _, name = os.path.split(test) testfiles = glob.glob(os.path.join(test, '*.aps*')) # recurse into subdirectories while len(testfiles) == 1 and os.path.isdir(testfiles[0]): _, subname = os.path.split(testfiles[0]) name = os.path.join(name, subname) testfiles = glob.glob(os.path.join(testfiles[0], '*')) newpath = os.path.join(BASE_AWG_DIR, subdir, name) newfiles = glob.glob(os.path.join(newpath, '*.aps*')) if seq_filter and any(seq_filter in seq_file for seq_file in testfiles): print("{0} comparing to {1}".format(test, newpath)) PulseSequencePlotter.plot_pulse_files_compare(testfiles, newfiles) c = input('Enter to continue (q to quit): ') if c == 'q': break def update_test_files(): raise Exception("update_test_files must be updated for new binary format") # for device in ['APS1', 'APS2']: # testdirs = glob.glob(os.path.join(BASE_TEST_DIR, 'Test' + device, '*')) # for test in testdirs: # testfiles = glob.glob(os.path.join(test, '*')) # # recurse into subdirectories # while len(testfiles) == 1 and os.path.isdir(testfiles[0]): # testfiles = glob.glob(os.path.join(testfiles[0], '*')) # for tfile in testfiles: # FID = h5py.File(tfile) # FID['/'].attrs['target hardware'] = device # FID.close() if __name__ == '__main__': # run the following line if you are comparing to older h5 files that don't # have the 'target hardware' attribute # update_test_files() output_file() compare_sequences(seq_filter="Ramsey")
import os import sys import glob from builtins import input from QGL import * import QGL BASE_AWG_DIR = QGL.config.AWGDir BASE_TEST_DIR = './test_data/awg/' def compare_sequences(seq_filter=""): test_subdirs = ['TestAPS1', 'TestAPS2'] for subdir in test_subdirs: testdirs = glob.glob(os.path.join(BASE_TEST_DIR, subdir, '*')) for test in testdirs: # build up subdirectory name _, name = os.path.split(test) testfiles = glob.glob(os.path.join(test, '*.aps*')) # recurse into subdirectories while len(testfiles) == 1 and os.path.isdir(testfiles[0]): _, subname = os.path.split(testfiles[0]) name = os.path.join(name, subname) testfiles = glob.glob(os.path.join(testfiles[0], '*')) newpath = os.path.join(BASE_AWG_DIR, subdir, name) newfiles = glob.glob(os.path.join(newpath, '*.aps*')) if seq_filter and any(seq_filter in seq_file for seq_file in testfiles): print("{0} comparing to {1}".format(test, newpath)) PulseSequencePlotter.plot_pulse_files_compare(testfiles, newfiles) c = input('Enter to continue (q to quit): ') if c == 'q': break def update_test_files(): raise Exception("update_test_files must be updated for new binary format") # for device in ['APS1', 'APS2']: # testdirs = glob.glob(os.path.join(BASE_TEST_DIR, 'Test' + device, '*')) # for test in testdirs: # testfiles = glob.glob(os.path.join(test, '*')) # # recurse into subdirectories # while len(testfiles) == 1 and os.path.isdir(testfiles[0]): # testfiles = glob.glob(os.path.join(testfiles[0], '*')) # for tfile in testfiles: # FID = h5py.File(tfile) # FID['/'].attrs['target hardware'] = device # FID.close() if __name__ == '__main__': # run the following line if you are comparing to older h5 files that don't # have the 'target hardware' attribute # update_test_files() output_file() compare_sequences(seq_filter="Ramsey")
en
0.539465
# build up subdirectory name # recurse into subdirectories # for device in ['APS1', 'APS2']: # testdirs = glob.glob(os.path.join(BASE_TEST_DIR, 'Test' + device, '*')) # for test in testdirs: # testfiles = glob.glob(os.path.join(test, '*')) # # recurse into subdirectories # while len(testfiles) == 1 and os.path.isdir(testfiles[0]): # testfiles = glob.glob(os.path.join(testfiles[0], '*')) # for tfile in testfiles: # FID = h5py.File(tfile) # FID['/'].attrs['target hardware'] = device # FID.close() # run the following line if you are comparing to older h5 files that don't # have the 'target hardware' attribute # update_test_files()
2.536019
3
module02-functional.programming.in.python/exercise01.py
deepcloudlabs/dcl162-2020-sep-09
0
6612659
<reponame>deepcloudlabs/dcl162-2020-sep-09 from functools import reduce from operator import add from banking.domain import Account, CheckingAccount accounts = [ # heterogeneous list Account("tr1", 10000), CheckingAccount("tr2", 20000, 1000), Account("tr3", 30000), CheckingAccount("tr4", 40000, 10000), Account("tr5", 50000) ] total_balance = 0 for acc in accounts: # external loop if isinstance(acc, CheckingAccount): total_balance += acc.balance print(f"Total Balance in Checking Account's: {total_balance}") x = 42 y = False name = "jack" acc = Account("tr6", 600000) if_checking_account = lambda acc: isinstance(acc, CheckingAccount) checking_accounts = list(filter(if_checking_account, accounts)) for acc in checking_accounts: print(acc) balances = list(map(lambda a: a.balance, filter(if_checking_account, accounts))) for bal in balances: print(bal) # Filter/Map/Reduce: Hadoop ( HDFS + MapReduce ) to_balance = lambda a: a.balance total_balance = reduce(add, map(to_balance, filter(if_checking_account, accounts)), 0) print(f"Total Balance: {total_balance}")
from functools import reduce from operator import add from banking.domain import Account, CheckingAccount accounts = [ # heterogeneous list Account("tr1", 10000), CheckingAccount("tr2", 20000, 1000), Account("tr3", 30000), CheckingAccount("tr4", 40000, 10000), Account("tr5", 50000) ] total_balance = 0 for acc in accounts: # external loop if isinstance(acc, CheckingAccount): total_balance += acc.balance print(f"Total Balance in Checking Account's: {total_balance}") x = 42 y = False name = "jack" acc = Account("tr6", 600000) if_checking_account = lambda acc: isinstance(acc, CheckingAccount) checking_accounts = list(filter(if_checking_account, accounts)) for acc in checking_accounts: print(acc) balances = list(map(lambda a: a.balance, filter(if_checking_account, accounts))) for bal in balances: print(bal) # Filter/Map/Reduce: Hadoop ( HDFS + MapReduce ) to_balance = lambda a: a.balance total_balance = reduce(add, map(to_balance, filter(if_checking_account, accounts)), 0) print(f"Total Balance: {total_balance}")
en
0.601596
# heterogeneous list # external loop # Filter/Map/Reduce: Hadoop ( HDFS + MapReduce )
3.241273
3
tests/test_validate_response_recursive.py
Aryabhata-Rootspring/fastapi
53,007
6612660
from typing import List from fastapi import FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() class RecursiveItem(BaseModel): sub_items: List["RecursiveItem"] = [] name: str RecursiveItem.update_forward_refs() class RecursiveSubitemInSubmodel(BaseModel): sub_items2: List["RecursiveItemViaSubmodel"] = [] name: str class RecursiveItemViaSubmodel(BaseModel): sub_items1: List[RecursiveSubitemInSubmodel] = [] name: str RecursiveSubitemInSubmodel.update_forward_refs() @app.get("/items/recursive", response_model=RecursiveItem) def get_recursive(): return {"name": "item", "sub_items": [{"name": "subitem", "sub_items": []}]} @app.get("/items/recursive-submodel", response_model=RecursiveItemViaSubmodel) def get_recursive_submodel(): return { "name": "item", "sub_items1": [ { "name": "subitem", "sub_items2": [ { "name": "subsubitem", "sub_items1": [{"name": "subsubsubitem", "sub_items2": []}], } ], } ], } client = TestClient(app) def test_recursive(): response = client.get("/items/recursive") assert response.status_code == 200, response.text assert response.json() == { "sub_items": [{"name": "subitem", "sub_items": []}], "name": "item", } response = client.get("/items/recursive-submodel") assert response.status_code == 200, response.text assert response.json() == { "name": "item", "sub_items1": [ { "name": "subitem", "sub_items2": [ { "name": "subsubitem", "sub_items1": [{"name": "subsubsubitem", "sub_items2": []}], } ], } ], }
from typing import List from fastapi import FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() class RecursiveItem(BaseModel): sub_items: List["RecursiveItem"] = [] name: str RecursiveItem.update_forward_refs() class RecursiveSubitemInSubmodel(BaseModel): sub_items2: List["RecursiveItemViaSubmodel"] = [] name: str class RecursiveItemViaSubmodel(BaseModel): sub_items1: List[RecursiveSubitemInSubmodel] = [] name: str RecursiveSubitemInSubmodel.update_forward_refs() @app.get("/items/recursive", response_model=RecursiveItem) def get_recursive(): return {"name": "item", "sub_items": [{"name": "subitem", "sub_items": []}]} @app.get("/items/recursive-submodel", response_model=RecursiveItemViaSubmodel) def get_recursive_submodel(): return { "name": "item", "sub_items1": [ { "name": "subitem", "sub_items2": [ { "name": "subsubitem", "sub_items1": [{"name": "subsubsubitem", "sub_items2": []}], } ], } ], } client = TestClient(app) def test_recursive(): response = client.get("/items/recursive") assert response.status_code == 200, response.text assert response.json() == { "sub_items": [{"name": "subitem", "sub_items": []}], "name": "item", } response = client.get("/items/recursive-submodel") assert response.status_code == 200, response.text assert response.json() == { "name": "item", "sub_items1": [ { "name": "subitem", "sub_items2": [ { "name": "subsubitem", "sub_items1": [{"name": "subsubsubitem", "sub_items2": []}], } ], } ], }
none
1
2.698221
3
tests/test_manifolds/test_special_orthogonal_group.py
NoemieJaquier/pymanopt
459
6612661
from pymanopt.manifolds import SpecialOrthogonalGroup from .._test import TestCase class TestSpecialOrthogonalGroup(TestCase): def test_constructor(self): SpecialOrthogonalGroup(10, 3)
from pymanopt.manifolds import SpecialOrthogonalGroup from .._test import TestCase class TestSpecialOrthogonalGroup(TestCase): def test_constructor(self): SpecialOrthogonalGroup(10, 3)
none
1
1.884368
2
apps/bot/commands/VoiceRecognition.py
Xoma163/petrovich
4
6612662
import io import requests import speech_recognition as sr from pydub import AudioSegment from apps.bot.classes.Command import Command from apps.bot.classes.consts.Consts import Platform from apps.bot.classes.consts.Exceptions import PWarning from apps.bot.classes.messages.attachments.VoiceAttachment import VoiceAttachment class VoiceRecognition(Command): name = 'распознай' names = ["голос", "голосовое"] help_text = "распознаёт голосовое сообщение" help_texts = [ "(Пересланное сообщение с голосовым сообщением) - распознаёт голосовое сообщение\n" "Если дан доступ к переписке, то распознает автоматически" ] platforms = [Platform.VK, Platform.TG] attachments = [VoiceAttachment] priority = -100 def start(self): audio_messages = self.event.get_all_attachments(VoiceAttachment) audio_message = audio_messages[0] download_url = audio_message.get_download_url() response = requests.get(download_url, stream=True) i = io.BytesIO(response.content) i.seek(0) o = io.BytesIO() o.name = "recognition.wav" try: input_file_format = download_url.split('.')[-1] if input_file_format == 'oga': input_file_format = 'ogg' except Exception: input_file_format = 'mp3' AudioSegment.from_file(i, input_file_format).export(o, format='wav') o.seek(0) r = sr.Recognizer() with sr.AudioFile(o) as source: audio = r.record(source) try: msg = r.recognize_google(audio, language='ru_RU') return msg except sr.UnknownValueError: raise PWarning("Ничего не понял((") except sr.RequestError as e: print(str(e)) raise PWarning("Проблема с форматом")
import io import requests import speech_recognition as sr from pydub import AudioSegment from apps.bot.classes.Command import Command from apps.bot.classes.consts.Consts import Platform from apps.bot.classes.consts.Exceptions import PWarning from apps.bot.classes.messages.attachments.VoiceAttachment import VoiceAttachment class VoiceRecognition(Command): name = 'распознай' names = ["голос", "голосовое"] help_text = "распознаёт голосовое сообщение" help_texts = [ "(Пересланное сообщение с голосовым сообщением) - распознаёт голосовое сообщение\n" "Если дан доступ к переписке, то распознает автоматически" ] platforms = [Platform.VK, Platform.TG] attachments = [VoiceAttachment] priority = -100 def start(self): audio_messages = self.event.get_all_attachments(VoiceAttachment) audio_message = audio_messages[0] download_url = audio_message.get_download_url() response = requests.get(download_url, stream=True) i = io.BytesIO(response.content) i.seek(0) o = io.BytesIO() o.name = "recognition.wav" try: input_file_format = download_url.split('.')[-1] if input_file_format == 'oga': input_file_format = 'ogg' except Exception: input_file_format = 'mp3' AudioSegment.from_file(i, input_file_format).export(o, format='wav') o.seek(0) r = sr.Recognizer() with sr.AudioFile(o) as source: audio = r.record(source) try: msg = r.recognize_google(audio, language='ru_RU') return msg except sr.UnknownValueError: raise PWarning("Ничего не понял((") except sr.RequestError as e: print(str(e)) raise PWarning("Проблема с форматом")
none
1
2.613104
3
agents/__init__.py
Kevin-Miao/Alpha-Woah
0
6612663
from .random_agent import random_agent_select_move from .minimax_agent import minimax_select_move, is_winner, is_board_full
from .random_agent import random_agent_select_move from .minimax_agent import minimax_select_move, is_winner, is_board_full
none
1
1.034393
1
stschema/util/base_modules/error_enum.py
erickvneri/st-schema-python
0
6612664
<reponame>erickvneri/st-schema-python<filename>stschema/util/base_modules/error_enum.py # MIT License # # Copyright (c) 2021 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import enum class StateErrorEnum(enum.Enum): """ The StateErrorEnum represents the supported device error states enumerators. """ CAPABILITY_NOT_SUPPORTED = "CAPABILITY-NOT-SUPPORTED" DEVICE_DELETED = "DEVICE-DELETED" DEVICE_UNAVAILABLE = "DEVICE-UNAVAILABLE" RESOURCE_CONSTRAINT_VIOLATION = "RESOURCE-CONSTRAINT-VIOLATION" class GlobalErrorEnum(enum.Enum): """ The GlobalErrorEnum represents the supported global-context error enumerators. """ BAD_REQUEST = "BAD-REQUEST" INTEGRATION_DELETED = "INTEGRATION-DELETED" INVALID_CLIENT = "INVALID-CLIENT" INVALID_CLIENT_SECRET = "INVALID-CLIENT-SECRET" INVALID_CODE = "INVALID-CODE" INVALID_INTERACTION_TYPE = "INVALID-INTERACTION-TYPE" INVALID_TOKEN = "INVALID-TOKEN" TOKEN_EXPIRED = "TOKEN-EXPIRED" UNSUPPORTED_GRANT_TYPE = "UNSUPPORTED-GRANT-TYPE"
# MIT License # # Copyright (c) 2021 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import enum class StateErrorEnum(enum.Enum): """ The StateErrorEnum represents the supported device error states enumerators. """ CAPABILITY_NOT_SUPPORTED = "CAPABILITY-NOT-SUPPORTED" DEVICE_DELETED = "DEVICE-DELETED" DEVICE_UNAVAILABLE = "DEVICE-UNAVAILABLE" RESOURCE_CONSTRAINT_VIOLATION = "RESOURCE-CONSTRAINT-VIOLATION" class GlobalErrorEnum(enum.Enum): """ The GlobalErrorEnum represents the supported global-context error enumerators. """ BAD_REQUEST = "BAD-REQUEST" INTEGRATION_DELETED = "INTEGRATION-DELETED" INVALID_CLIENT = "INVALID-CLIENT" INVALID_CLIENT_SECRET = "INVALID-CLIENT-SECRET" INVALID_CODE = "INVALID-CODE" INVALID_INTERACTION_TYPE = "INVALID-INTERACTION-TYPE" INVALID_TOKEN = "INVALID-TOKEN" TOKEN_EXPIRED = "TOKEN-EXPIRED" UNSUPPORTED_GRANT_TYPE = "UNSUPPORTED-GRANT-TYPE"
en
0.740567
# MIT License # # Copyright (c) 2021 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. The StateErrorEnum represents the supported device error states enumerators. The GlobalErrorEnum represents the supported global-context error enumerators.
1.828446
2
custom_components/climate_scheduler/__init__.py
FrancisLab/hass-climate-scheduler
4
6612665
<gh_stars>1-10 """The Climate Scheduler integration.""" import logging from datetime import timedelta import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.core import HomeAssistant VERSION = "0.0.0" DOMAIN = "climate_scheduler" CLIMATE_SCHEDULER_PLATFORMS = ["switch"] CLIMATE_SCHEDULER_UPDATE_TOPIC = "{0}_update".format(DOMAIN) DATA_CLIMATE_SCHEDULER = "data_climate_scheduler" CONF_UPDATE_INTERVAL = "update_interval" CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Optional( CONF_UPDATE_INTERVAL, default="00:15:00" ): cv.positive_time_period } ) }, extra=vol.ALLOW_EXTRA, ) _LOGGER = logging.getLogger(__name__) async def async_setup(hass: HomeAssistant, global_config: dict): """Set up the Climate Scheduler component.""" config = global_config.get(DOMAIN) if config is None: return climate_scheduler = ClimateScheduler(hass, config) hass.data[DATA_CLIMATE_SCHEDULER] = climate_scheduler return True class ClimateScheduler(object): """ Climate Scheduler Implementation """ def __init__(self, hass: HomeAssistant, config: dict) -> None: self.hass = hass self._update_interval: timedelta = config.get(CONF_UPDATE_INTERVAL) @property def update_interval(self) -> timedelta: return self._update_interval
"""The Climate Scheduler integration.""" import logging from datetime import timedelta import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.core import HomeAssistant VERSION = "0.0.0" DOMAIN = "climate_scheduler" CLIMATE_SCHEDULER_PLATFORMS = ["switch"] CLIMATE_SCHEDULER_UPDATE_TOPIC = "{0}_update".format(DOMAIN) DATA_CLIMATE_SCHEDULER = "data_climate_scheduler" CONF_UPDATE_INTERVAL = "update_interval" CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Optional( CONF_UPDATE_INTERVAL, default="00:15:00" ): cv.positive_time_period } ) }, extra=vol.ALLOW_EXTRA, ) _LOGGER = logging.getLogger(__name__) async def async_setup(hass: HomeAssistant, global_config: dict): """Set up the Climate Scheduler component.""" config = global_config.get(DOMAIN) if config is None: return climate_scheduler = ClimateScheduler(hass, config) hass.data[DATA_CLIMATE_SCHEDULER] = climate_scheduler return True class ClimateScheduler(object): """ Climate Scheduler Implementation """ def __init__(self, hass: HomeAssistant, config: dict) -> None: self.hass = hass self._update_interval: timedelta = config.get(CONF_UPDATE_INTERVAL) @property def update_interval(self) -> timedelta: return self._update_interval
en
0.63644
The Climate Scheduler integration. Set up the Climate Scheduler component. Climate Scheduler Implementation
2.314668
2
gym-basic/setup.py
zazangra/newcombe_game
0
6612666
<reponame>zazangra/newcombe_game<gh_stars>0 from setuptools import setup setup(name='gym_basic', version='0.0.1', install_requires=['gym'] )
from setuptools import setup setup(name='gym_basic', version='0.0.1', install_requires=['gym'] )
none
1
1.134449
1
Python/Tasks/staricase.py
Sonu589/Hacktoberfest2021-1
0
6612667
# Read input as specified in the question. # Print output as specified in the question. # Staircase # A child is running up a staircase with N steps, and can hop either 1 # step, 2 steps or 3 steps at a time. Implement a method to count how # many possible ways the child can run up to the stairs. You need to # return number of possible ways W. def stair(n): # Implement the function for stairs in range(1, n + 1): print(' ' * (n - stairs) + '##' * stairs) n = int(input()) print(stair(n))
# Read input as specified in the question. # Print output as specified in the question. # Staircase # A child is running up a staircase with N steps, and can hop either 1 # step, 2 steps or 3 steps at a time. Implement a method to count how # many possible ways the child can run up to the stairs. You need to # return number of possible ways W. def stair(n): # Implement the function for stairs in range(1, n + 1): print(' ' * (n - stairs) + '##' * stairs) n = int(input()) print(stair(n))
en
0.856677
# Read input as specified in the question. # Print output as specified in the question. # Staircase # A child is running up a staircase with N steps, and can hop either 1 # step, 2 steps or 3 steps at a time. Implement a method to count how # many possible ways the child can run up to the stairs. You need to # return number of possible ways W. # Implement the function #' * stairs)
4.260463
4
packages/pyglGA/scripts/basicCubeGuiECSS.py
ZackPer/glGA-SDK
1
6612668
<filename>packages/pyglGA/scripts/basicCubeGuiECSS.py """ BasicWindow example, showcasing the pyglGA SDK ECSS glGA SDK v2021.0.5 ECSS (Entity Component System in a Scenegraph) @Coopyright 2020-2021 <NAME> The classes below are all related to the GUI and Display of 3D content using the OpenGL, GLSL and SDL2, ImGUI APIs, on top of the pyglGA ECSS package """ from __future__ import annotations import numpy as np import imgui import pyglGA.ECSS.utilities as util from pyglGA.ECSS.System import System, TransformSystem, CameraSystem from pyglGA.ECSS.Entity import Entity from pyglGA.ECSS.Component import BasicTransform, Camera, RenderMesh from pyglGA.ECSS.Event import Event, EventManager from pyglGA.GUI.Viewer import SDL2Window, ImGUIDecorator, RenderGLStateSystem, RenderWindow from pyglGA.ECSS.ECSSManager import ECSSManager from pyglGA.ext.Shader import InitGLShaderSystem, Shader, ShaderGLDecorator, RenderGLShaderSystem from pyglGA.ext.VertexArray import VertexArray from pyglGA.ext.Scene import Scene class ImGUIecssDecorator(ImGUIDecorator): """custom ImGUI decorator for this example :param ImGUIDecorator: [description] :type ImGUIDecorator: [type] """ def __init__(self, wrapee: RenderWindow, imguiContext = None): super().__init__(wrapee, imguiContext) # @GPTODO: # we should be able to retrieve all these just from the Scene: ECSSManager self.translation = [0.0, 0.0, 0.0, 0.0] self.camOrthoLRBT = [-100.0, 100.0, -100.0, 100.0] self.camOrthoNF = [1.0, 100.0] self.mvpMat = None self.shaderDec = None def scenegraphVisualiser(self): """display the ECSS in an ImGUI tree node structure Typically this is a custom widget to be extended in an ImGUIDecorator subclass """ sceneRoot = self.wrapeeWindow.scene.world.root.name if sceneRoot is None: sceneRoot = "ECSS Root Entity" imgui.begin("ECSS graph") imgui.columns(2,"Properties") # below is a recursive call to build-up the whole scenegraph as ImGUI tree if imgui.tree_node(sceneRoot, imgui.TREE_NODE_OPEN_ON_ARROW): self.drawNode(self.wrapeeWindow.scene.world.root, self.translation, self.camOrthoLRBT, self.camOrthoNF) imgui.tree_pop() imgui.next_column() imgui.text("Properties") imgui.separator() #TRS sample changed, trans = imgui.drag_float4("Translation", *self.translation) self.translation = list(trans) changedLRBT, orthoLRBT = imgui.drag_float4("Camera LRBT", *self.camOrthoLRBT) self.camOrthoLRBT = list(orthoLRBT) changedNF, orthoNF = imgui.drag_float2("Camera Near, Far", *self.camOrthoNF) self.camOrthoNF = list(orthoNF) imgui.end() def drawNode(self, component, translation = None, camLRBT = None, camNF = None): #save initial translation value lastTranslation = translation lastLRBT = camLRBT lastNF = camNF #create a local iterator of Entity's children if component._children is not None: debugIterator = iter(component._children) #call print() on all children (Concrete Components or Entities) while there are more children to traverse done_traversing = False while not done_traversing: try: comp = next(debugIterator) imgui.indent(10) except StopIteration: done_traversing = True imgui.unindent(10) else: if imgui.tree_node(comp.name, imgui.TREE_NODE_OPEN_ON_ARROW): #imgui.text(comp.__str__()) _, selected = imgui.selectable(comp.__str__(), True) if selected: print(f'Selected: {selected} of node: {comp}'.center(100, '-')) selected = False #check if the component is a BasicTransform if (isinstance(comp, BasicTransform)): #set now the comp: comp.trs = util.translate(lastTranslation[0],lastTranslation[1],lastTranslation[2]) #retrive the translation vector from the TRS matrix # @GPTODO this needs to be provided as utility method trsMat = comp.trs [x,y,z] = trsMat[:3,3] if translation is not None: translation[0] = x translation[1] = y translation[2] = z translation[3] = 1 if (isinstance(comp, Camera)): print(comp, " ready to assign new camera values!") #set now camera params # @GPTODO # very dirty code, this is for a proof of concept only, should be replaced! comp.projMat = util.ortho(lastLRBT[0], lastLRBT[1],lastLRBT[2],lastLRBT[3],lastNF[0], lastNF[1]) self.mvpMat = comp.projMat if self.shaderDec is not None: self.shaderDec.setUniformVariable(key='modelViewProj', value=self.mvpMat, mat4=True) imgui.tree_pop() self.drawNode(comp, translation, camLRBT, camNF) # recursive call of this method to traverse hierarchy def main(imguiFlag = False): ########################################################## # Instantiate a simple complete ECSS with Entities, # Components, Camera, Shader, VertexArray and RenderMesh # ######################################################### """ ECSS for this example: root |---------------------------| entityCam1, node4, |-------| |--------------|----------|--------------| trans1, entityCam2 trans4, mesh4, shaderDec4 vArray4 | ortho, trans2 """ scene = Scene() # Scenegraph with Entities, Components rootEntity = scene.world.createEntity(Entity(name="Root")) entityCam1 = scene.world.createEntity(Entity(name="entityCam1")) scene.world.addEntityChild(rootEntity, entityCam1) trans1 = scene.world.addComponent(entityCam1, BasicTransform(name="trans1", trs=util.identity())) entityCam2 = scene.world.createEntity(Entity(name="entityCam2")) scene.world.addEntityChild(entityCam1, entityCam2) trans2 = scene.world.addComponent(entityCam2, BasicTransform(name="trans2", trs=util.identity())) orthoCam = scene.world.addComponent(entityCam2, Camera(util.ortho(-100.0, 100.0, -100.0, 100.0, 1.0, 100.0), "orthoCam","Camera","500")) node4 = scene.world.createEntity(Entity(name="node4")) scene.world.addEntityChild(rootEntity, node4) trans4 = scene.world.addComponent(node4, BasicTransform(name="trans4", trs=util.identity())) mesh4 = scene.world.addComponent(node4, RenderMesh(name="mesh4")) #Simple Cube vertexCube = np.array([ [-0.5, -0.5, 0.5, 1.0], [-0.5, 0.5, 0.5, 1.0], [0.5, 0.5, 0.5, 1.0], [0.5, -0.5, 0.5, 1.0], [-0.5, -0.5, -0.5, 1.0], [-0.5, 0.5, -0.5, 1.0], [0.5, 0.5, -0.5, 1.0], [0.5, -0.5, -0.5, 1.0] ],dtype=np.float32) colorCube = np.array([ [0.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 1.0, 1.0, 1.0] ], dtype=np.float32) #index arrays for above vertex Arrays indexCube = np.array((1,0,3, 1,3,2, 2,3,7, 2,7,6, 3,0,4, 3,4,7, 6,5,1, 6,1,2, 4,5,6, 4,6,7, 5,4,0, 5,0,1), np.uint32) #rhombus out of two triangles # Systems transUpdate = scene.world.createSystem(TransformSystem("transUpdate", "TransformSystem", "001")) camUpdate = scene.world.createSystem(CameraSystem("camUpdate", "CameraUpdate", "200")) renderUpdate = scene.world.createSystem(RenderGLShaderSystem()) initUpdate = scene.world.createSystem(InitGLShaderSystem()) # # MVP matrix calculation - # now set directly here only for Testing # otherwise automatically picked up at ECSS VertexArray level from the Scenegraph System # same process as VertexArray is automatically populated from RenderMesh # #model = util.translate(0.0,0.0,0.5) model = util.translate(0.0,0.0,0.0) eye = util.vec(0.0, 0.0, -10.0) target = util.vec(0,0,0) up = util.vec(0.0, 1.0, 0.0) view = util.lookat(eye, target, up) #projMat = util.frustum(-10.0, 10.0,-10.0,10.0, -1.0, 10) #projMat = util.perspective(120.0, 1.33, 0.1, 100.0) #projMat = util.ortho(-100.0, 100.0, -100.0, 100.0, 1.0, 100.0) projMat = util.ortho(-5.0, 5.0, -5.0, 5.0, -1.0, 5.0) mvpMat = model @ view @ projMat #mvpMat = projMat @ view @ model # # setup ECSS nodes pre-systems # orthoCam.projMat = projMat trans2.trs = view trans1.trs = model #l2cMat = node4.l2cam # decorated components and systems with sample, default pass-through shader with uniform MVP shaderDec4 = scene.world.addComponent(node4, ShaderGLDecorator(Shader(vertex_source = Shader.COLOR_VERT_MVP, fragment_source=Shader.COLOR_FRAG))) # attach a simple cube in a RenderMesh so that VertexArray can pick it up mesh4.vertex_attributes.append(vertexCube) mesh4.vertex_attributes.append(colorCube) mesh4.vertex_index.append(indexCube) vArray4 = scene.world.addComponent(node4, VertexArray()) scene.world.print() scene.world.eventManager.print() # MAIN RENDERING LOOP running = True scene.init(imgui=True, windowWidth = 1024, windowHeight = 768, windowTitle = "pyglGA Cube ECSS Scene", customImGUIdecorator = ImGUIecssDecorator) imGUIecss = scene.gContext imGUIecss.mvpMat = mvpMat imGUIecss.shaderDec = shaderDec4 # --------------------------------------------------------- # Run pre render GLInit traversal for once! # pre-pass scenegraph to initialise all GL context dependent geometry, shader classes # needs an active GL context # --------------------------------------------------------- scene.world.traverse_visit(initUpdate, scene.world.root) # # setup ECSS nodes after-systems # l2cMat = trans4.l2cam print(f'\nl2cMat: \n{l2cMat}') print(f'\nmvpMat: \n{mvpMat}') print(trans4) ############################################ # Instantiate all Event-related key objects ############################################ # instantiate new EventManager # need to pass that instance to all event publishers e.g. ImGUIDecorator eManager = scene.world.eventManager gWindow = scene.renderWindow gGUI = scene.gContext #simple Event actuator System renderGLEventActuator = RenderGLStateSystem() #setup Events and add them to the EventManager updateTRS = Event(name="OnUpdateTRS", id=100, value=None) updateBackground = Event(name="OnUpdateBackground", id=200, value=None) #updateWireframe = Event(name="OnUpdateWireframe", id=201, value=None) eManager._events[updateTRS.name] = updateTRS eManager._events[updateBackground.name] = updateBackground #eManager._events[updateWireframe.name] = updateWireframe # this is added inside ImGUIDecorator # Add RenderWindow to the EventManager subscribers # @GPTODO # values of these Dicts below should be List items, not objects only # use subscribe(), publish(), actuate() methhods # eManager._subscribers[updateTRS.name] = gGUI eManager._subscribers[updateBackground.name] = gGUI # this is a special case below: # this event is published in ImGUIDecorator and the subscriber is SDLWindow eManager._subscribers['OnUpdateWireframe'] = gWindow eManager._actuators['OnUpdateWireframe'] = renderGLEventActuator # Add RenderWindow to the EventManager publishers eManager._publishers[updateBackground.name] = gGUI while running: # --------------------------------------------------------- # run Systems in the scenegraph # root node is accessed via ECSSManagerObject.root property # normally these are run within the rendering loop (except 4th GLInit System) # -------------------------------------------------------- # 1. L2W traversal scene.world.traverse_visit(transUpdate, scene.world.root) # 2. pre-camera Mr2c traversal scene.world.traverse_visit_pre_camera(camUpdate, orthoCam) # 3. run proper Ml2c traversal scene.world.traverse_visit(camUpdate, scene.world.root) # 3.1 shader uniform variable allocation per frame #shaderDec4.setUniformVariable(key='modelViewProj', value=l2cMat, mat4=True) # direct uniform variable shader setup # should be called before ImGUI and before drawing Geometry shaderDec4.setUniformVariable(key='modelViewProj', value=mvpMat, mat4=True) #shaderDec4.setUniformVariable(key='modelViewProj', value=l2cMat, mat4=True) #shaderDec4.setUniformVariable(key='modelViewProj', value=trans4.l2cam, mat4=True) # 4. call SDLWindow/ImGUI display() and ImGUI event input process running = scene.render(running) # 5. call the GL State render System scene.world.traverse_visit(renderUpdate, scene.world.root) # 6. ImGUI post-display calls and SDLWindow swap scene.render_post() scene.shutdown() if __name__ == "__main__": main(imguiFlag = True)
<filename>packages/pyglGA/scripts/basicCubeGuiECSS.py """ BasicWindow example, showcasing the pyglGA SDK ECSS glGA SDK v2021.0.5 ECSS (Entity Component System in a Scenegraph) @Coopyright 2020-2021 <NAME> The classes below are all related to the GUI and Display of 3D content using the OpenGL, GLSL and SDL2, ImGUI APIs, on top of the pyglGA ECSS package """ from __future__ import annotations import numpy as np import imgui import pyglGA.ECSS.utilities as util from pyglGA.ECSS.System import System, TransformSystem, CameraSystem from pyglGA.ECSS.Entity import Entity from pyglGA.ECSS.Component import BasicTransform, Camera, RenderMesh from pyglGA.ECSS.Event import Event, EventManager from pyglGA.GUI.Viewer import SDL2Window, ImGUIDecorator, RenderGLStateSystem, RenderWindow from pyglGA.ECSS.ECSSManager import ECSSManager from pyglGA.ext.Shader import InitGLShaderSystem, Shader, ShaderGLDecorator, RenderGLShaderSystem from pyglGA.ext.VertexArray import VertexArray from pyglGA.ext.Scene import Scene class ImGUIecssDecorator(ImGUIDecorator): """custom ImGUI decorator for this example :param ImGUIDecorator: [description] :type ImGUIDecorator: [type] """ def __init__(self, wrapee: RenderWindow, imguiContext = None): super().__init__(wrapee, imguiContext) # @GPTODO: # we should be able to retrieve all these just from the Scene: ECSSManager self.translation = [0.0, 0.0, 0.0, 0.0] self.camOrthoLRBT = [-100.0, 100.0, -100.0, 100.0] self.camOrthoNF = [1.0, 100.0] self.mvpMat = None self.shaderDec = None def scenegraphVisualiser(self): """display the ECSS in an ImGUI tree node structure Typically this is a custom widget to be extended in an ImGUIDecorator subclass """ sceneRoot = self.wrapeeWindow.scene.world.root.name if sceneRoot is None: sceneRoot = "ECSS Root Entity" imgui.begin("ECSS graph") imgui.columns(2,"Properties") # below is a recursive call to build-up the whole scenegraph as ImGUI tree if imgui.tree_node(sceneRoot, imgui.TREE_NODE_OPEN_ON_ARROW): self.drawNode(self.wrapeeWindow.scene.world.root, self.translation, self.camOrthoLRBT, self.camOrthoNF) imgui.tree_pop() imgui.next_column() imgui.text("Properties") imgui.separator() #TRS sample changed, trans = imgui.drag_float4("Translation", *self.translation) self.translation = list(trans) changedLRBT, orthoLRBT = imgui.drag_float4("Camera LRBT", *self.camOrthoLRBT) self.camOrthoLRBT = list(orthoLRBT) changedNF, orthoNF = imgui.drag_float2("Camera Near, Far", *self.camOrthoNF) self.camOrthoNF = list(orthoNF) imgui.end() def drawNode(self, component, translation = None, camLRBT = None, camNF = None): #save initial translation value lastTranslation = translation lastLRBT = camLRBT lastNF = camNF #create a local iterator of Entity's children if component._children is not None: debugIterator = iter(component._children) #call print() on all children (Concrete Components or Entities) while there are more children to traverse done_traversing = False while not done_traversing: try: comp = next(debugIterator) imgui.indent(10) except StopIteration: done_traversing = True imgui.unindent(10) else: if imgui.tree_node(comp.name, imgui.TREE_NODE_OPEN_ON_ARROW): #imgui.text(comp.__str__()) _, selected = imgui.selectable(comp.__str__(), True) if selected: print(f'Selected: {selected} of node: {comp}'.center(100, '-')) selected = False #check if the component is a BasicTransform if (isinstance(comp, BasicTransform)): #set now the comp: comp.trs = util.translate(lastTranslation[0],lastTranslation[1],lastTranslation[2]) #retrive the translation vector from the TRS matrix # @GPTODO this needs to be provided as utility method trsMat = comp.trs [x,y,z] = trsMat[:3,3] if translation is not None: translation[0] = x translation[1] = y translation[2] = z translation[3] = 1 if (isinstance(comp, Camera)): print(comp, " ready to assign new camera values!") #set now camera params # @GPTODO # very dirty code, this is for a proof of concept only, should be replaced! comp.projMat = util.ortho(lastLRBT[0], lastLRBT[1],lastLRBT[2],lastLRBT[3],lastNF[0], lastNF[1]) self.mvpMat = comp.projMat if self.shaderDec is not None: self.shaderDec.setUniformVariable(key='modelViewProj', value=self.mvpMat, mat4=True) imgui.tree_pop() self.drawNode(comp, translation, camLRBT, camNF) # recursive call of this method to traverse hierarchy def main(imguiFlag = False): ########################################################## # Instantiate a simple complete ECSS with Entities, # Components, Camera, Shader, VertexArray and RenderMesh # ######################################################### """ ECSS for this example: root |---------------------------| entityCam1, node4, |-------| |--------------|----------|--------------| trans1, entityCam2 trans4, mesh4, shaderDec4 vArray4 | ortho, trans2 """ scene = Scene() # Scenegraph with Entities, Components rootEntity = scene.world.createEntity(Entity(name="Root")) entityCam1 = scene.world.createEntity(Entity(name="entityCam1")) scene.world.addEntityChild(rootEntity, entityCam1) trans1 = scene.world.addComponent(entityCam1, BasicTransform(name="trans1", trs=util.identity())) entityCam2 = scene.world.createEntity(Entity(name="entityCam2")) scene.world.addEntityChild(entityCam1, entityCam2) trans2 = scene.world.addComponent(entityCam2, BasicTransform(name="trans2", trs=util.identity())) orthoCam = scene.world.addComponent(entityCam2, Camera(util.ortho(-100.0, 100.0, -100.0, 100.0, 1.0, 100.0), "orthoCam","Camera","500")) node4 = scene.world.createEntity(Entity(name="node4")) scene.world.addEntityChild(rootEntity, node4) trans4 = scene.world.addComponent(node4, BasicTransform(name="trans4", trs=util.identity())) mesh4 = scene.world.addComponent(node4, RenderMesh(name="mesh4")) #Simple Cube vertexCube = np.array([ [-0.5, -0.5, 0.5, 1.0], [-0.5, 0.5, 0.5, 1.0], [0.5, 0.5, 0.5, 1.0], [0.5, -0.5, 0.5, 1.0], [-0.5, -0.5, -0.5, 1.0], [-0.5, 0.5, -0.5, 1.0], [0.5, 0.5, -0.5, 1.0], [0.5, -0.5, -0.5, 1.0] ],dtype=np.float32) colorCube = np.array([ [0.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 1.0, 1.0, 1.0] ], dtype=np.float32) #index arrays for above vertex Arrays indexCube = np.array((1,0,3, 1,3,2, 2,3,7, 2,7,6, 3,0,4, 3,4,7, 6,5,1, 6,1,2, 4,5,6, 4,6,7, 5,4,0, 5,0,1), np.uint32) #rhombus out of two triangles # Systems transUpdate = scene.world.createSystem(TransformSystem("transUpdate", "TransformSystem", "001")) camUpdate = scene.world.createSystem(CameraSystem("camUpdate", "CameraUpdate", "200")) renderUpdate = scene.world.createSystem(RenderGLShaderSystem()) initUpdate = scene.world.createSystem(InitGLShaderSystem()) # # MVP matrix calculation - # now set directly here only for Testing # otherwise automatically picked up at ECSS VertexArray level from the Scenegraph System # same process as VertexArray is automatically populated from RenderMesh # #model = util.translate(0.0,0.0,0.5) model = util.translate(0.0,0.0,0.0) eye = util.vec(0.0, 0.0, -10.0) target = util.vec(0,0,0) up = util.vec(0.0, 1.0, 0.0) view = util.lookat(eye, target, up) #projMat = util.frustum(-10.0, 10.0,-10.0,10.0, -1.0, 10) #projMat = util.perspective(120.0, 1.33, 0.1, 100.0) #projMat = util.ortho(-100.0, 100.0, -100.0, 100.0, 1.0, 100.0) projMat = util.ortho(-5.0, 5.0, -5.0, 5.0, -1.0, 5.0) mvpMat = model @ view @ projMat #mvpMat = projMat @ view @ model # # setup ECSS nodes pre-systems # orthoCam.projMat = projMat trans2.trs = view trans1.trs = model #l2cMat = node4.l2cam # decorated components and systems with sample, default pass-through shader with uniform MVP shaderDec4 = scene.world.addComponent(node4, ShaderGLDecorator(Shader(vertex_source = Shader.COLOR_VERT_MVP, fragment_source=Shader.COLOR_FRAG))) # attach a simple cube in a RenderMesh so that VertexArray can pick it up mesh4.vertex_attributes.append(vertexCube) mesh4.vertex_attributes.append(colorCube) mesh4.vertex_index.append(indexCube) vArray4 = scene.world.addComponent(node4, VertexArray()) scene.world.print() scene.world.eventManager.print() # MAIN RENDERING LOOP running = True scene.init(imgui=True, windowWidth = 1024, windowHeight = 768, windowTitle = "pyglGA Cube ECSS Scene", customImGUIdecorator = ImGUIecssDecorator) imGUIecss = scene.gContext imGUIecss.mvpMat = mvpMat imGUIecss.shaderDec = shaderDec4 # --------------------------------------------------------- # Run pre render GLInit traversal for once! # pre-pass scenegraph to initialise all GL context dependent geometry, shader classes # needs an active GL context # --------------------------------------------------------- scene.world.traverse_visit(initUpdate, scene.world.root) # # setup ECSS nodes after-systems # l2cMat = trans4.l2cam print(f'\nl2cMat: \n{l2cMat}') print(f'\nmvpMat: \n{mvpMat}') print(trans4) ############################################ # Instantiate all Event-related key objects ############################################ # instantiate new EventManager # need to pass that instance to all event publishers e.g. ImGUIDecorator eManager = scene.world.eventManager gWindow = scene.renderWindow gGUI = scene.gContext #simple Event actuator System renderGLEventActuator = RenderGLStateSystem() #setup Events and add them to the EventManager updateTRS = Event(name="OnUpdateTRS", id=100, value=None) updateBackground = Event(name="OnUpdateBackground", id=200, value=None) #updateWireframe = Event(name="OnUpdateWireframe", id=201, value=None) eManager._events[updateTRS.name] = updateTRS eManager._events[updateBackground.name] = updateBackground #eManager._events[updateWireframe.name] = updateWireframe # this is added inside ImGUIDecorator # Add RenderWindow to the EventManager subscribers # @GPTODO # values of these Dicts below should be List items, not objects only # use subscribe(), publish(), actuate() methhods # eManager._subscribers[updateTRS.name] = gGUI eManager._subscribers[updateBackground.name] = gGUI # this is a special case below: # this event is published in ImGUIDecorator and the subscriber is SDLWindow eManager._subscribers['OnUpdateWireframe'] = gWindow eManager._actuators['OnUpdateWireframe'] = renderGLEventActuator # Add RenderWindow to the EventManager publishers eManager._publishers[updateBackground.name] = gGUI while running: # --------------------------------------------------------- # run Systems in the scenegraph # root node is accessed via ECSSManagerObject.root property # normally these are run within the rendering loop (except 4th GLInit System) # -------------------------------------------------------- # 1. L2W traversal scene.world.traverse_visit(transUpdate, scene.world.root) # 2. pre-camera Mr2c traversal scene.world.traverse_visit_pre_camera(camUpdate, orthoCam) # 3. run proper Ml2c traversal scene.world.traverse_visit(camUpdate, scene.world.root) # 3.1 shader uniform variable allocation per frame #shaderDec4.setUniformVariable(key='modelViewProj', value=l2cMat, mat4=True) # direct uniform variable shader setup # should be called before ImGUI and before drawing Geometry shaderDec4.setUniformVariable(key='modelViewProj', value=mvpMat, mat4=True) #shaderDec4.setUniformVariable(key='modelViewProj', value=l2cMat, mat4=True) #shaderDec4.setUniformVariable(key='modelViewProj', value=trans4.l2cam, mat4=True) # 4. call SDLWindow/ImGUI display() and ImGUI event input process running = scene.render(running) # 5. call the GL State render System scene.world.traverse_visit(renderUpdate, scene.world.root) # 6. ImGUI post-display calls and SDLWindow swap scene.render_post() scene.shutdown() if __name__ == "__main__": main(imguiFlag = True)
en
0.612536
BasicWindow example, showcasing the pyglGA SDK ECSS glGA SDK v2021.0.5 ECSS (Entity Component System in a Scenegraph) @Coopyright 2020-2021 <NAME> The classes below are all related to the GUI and Display of 3D content using the OpenGL, GLSL and SDL2, ImGUI APIs, on top of the pyglGA ECSS package custom ImGUI decorator for this example :param ImGUIDecorator: [description] :type ImGUIDecorator: [type] # @GPTODO: # we should be able to retrieve all these just from the Scene: ECSSManager display the ECSS in an ImGUI tree node structure Typically this is a custom widget to be extended in an ImGUIDecorator subclass # below is a recursive call to build-up the whole scenegraph as ImGUI tree #TRS sample #save initial translation value #create a local iterator of Entity's children #call print() on all children (Concrete Components or Entities) while there are more children to traverse #imgui.text(comp.__str__()) #check if the component is a BasicTransform #set now the comp: #retrive the translation vector from the TRS matrix # @GPTODO this needs to be provided as utility method #set now camera params # @GPTODO # very dirty code, this is for a proof of concept only, should be replaced! # recursive call of this method to traverse hierarchy ########################################################## # Instantiate a simple complete ECSS with Entities, # Components, Camera, Shader, VertexArray and RenderMesh # ######################################################### ECSS for this example: root |---------------------------| entityCam1, node4, |-------| |--------------|----------|--------------| trans1, entityCam2 trans4, mesh4, shaderDec4 vArray4 | ortho, trans2 # Scenegraph with Entities, Components #Simple Cube #index arrays for above vertex Arrays #rhombus out of two triangles # Systems # # MVP matrix calculation - # now set directly here only for Testing # otherwise automatically picked up at ECSS VertexArray level from the Scenegraph System # same process as VertexArray is automatically populated from RenderMesh # #model = util.translate(0.0,0.0,0.5) #projMat = util.frustum(-10.0, 10.0,-10.0,10.0, -1.0, 10) #projMat = util.perspective(120.0, 1.33, 0.1, 100.0) #projMat = util.ortho(-100.0, 100.0, -100.0, 100.0, 1.0, 100.0) #mvpMat = projMat @ view @ model # # setup ECSS nodes pre-systems # #l2cMat = node4.l2cam # decorated components and systems with sample, default pass-through shader with uniform MVP # attach a simple cube in a RenderMesh so that VertexArray can pick it up # MAIN RENDERING LOOP # --------------------------------------------------------- # Run pre render GLInit traversal for once! # pre-pass scenegraph to initialise all GL context dependent geometry, shader classes # needs an active GL context # --------------------------------------------------------- # # setup ECSS nodes after-systems # ############################################ # Instantiate all Event-related key objects ############################################ # instantiate new EventManager # need to pass that instance to all event publishers e.g. ImGUIDecorator #simple Event actuator System #setup Events and add them to the EventManager #updateWireframe = Event(name="OnUpdateWireframe", id=201, value=None) #eManager._events[updateWireframe.name] = updateWireframe # this is added inside ImGUIDecorator # Add RenderWindow to the EventManager subscribers # @GPTODO # values of these Dicts below should be List items, not objects only # use subscribe(), publish(), actuate() methhods # # this is a special case below: # this event is published in ImGUIDecorator and the subscriber is SDLWindow # Add RenderWindow to the EventManager publishers # --------------------------------------------------------- # run Systems in the scenegraph # root node is accessed via ECSSManagerObject.root property # normally these are run within the rendering loop (except 4th GLInit System) # -------------------------------------------------------- # 1. L2W traversal # 2. pre-camera Mr2c traversal # 3. run proper Ml2c traversal # 3.1 shader uniform variable allocation per frame #shaderDec4.setUniformVariable(key='modelViewProj', value=l2cMat, mat4=True) # direct uniform variable shader setup # should be called before ImGUI and before drawing Geometry #shaderDec4.setUniformVariable(key='modelViewProj', value=l2cMat, mat4=True) #shaderDec4.setUniformVariable(key='modelViewProj', value=trans4.l2cam, mat4=True) # 4. call SDLWindow/ImGUI display() and ImGUI event input process # 5. call the GL State render System # 6. ImGUI post-display calls and SDLWindow swap
2.350862
2
cerebrate/core/__init__.py
frugs/cerebrate
1
6612669
<filename>cerebrate/core/__init__.py from .replay import Replay
<filename>cerebrate/core/__init__.py from .replay import Replay
none
1
1.030502
1
tests/test_bs_seeker_filter.py
Multiscale-Genomics/mg-process-fastq
2
6612670
<reponame>Multiscale-Genomics/mg-process-fastq<filename>tests/test_bs_seeker_filter.py """ .. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import gzip import pytest from basic_modules.metadata import Metadata from tool import bs_seeker_filter @pytest.mark.wgbs def test_bs_seeker_filter_00(): """ Extract the compressed FASTQ files """ resource_path = os.path.join(os.path.dirname(__file__), "data/") fastq_file_1 = resource_path + "bsSeeker.Mouse.SRR892982_1.fastq" fastq_file_2 = resource_path + "bsSeeker.Mouse.SRR892982_2.fastq" with gzip.open(fastq_file_1 + '.gz', 'rb') as fgz_in: with open(fastq_file_1, 'w') as f_out: f_out.write(fgz_in.read()) with gzip.open(fastq_file_2 + '.gz', 'rb') as fgz_in: with open(fastq_file_2, 'w') as f_out: f_out.write(fgz_in.read()) assert os.path.isfile(fastq_file_1) is True assert os.path.getsize(fastq_file_1) > 0 assert os.path.isfile(fastq_file_2) is True assert os.path.getsize(fastq_file_2) > 0 @pytest.mark.wgbs def test_bs_seeker_filter_01(): """ Test that it is possible to call the BSseeker filter """ resource_path = os.path.join(os.path.dirname(__file__), "data/") home = os.path.expanduser('~') input_files = { "fastq": resource_path + "bsSeeker.Mouse.SRR892982_1.fastq" } output_files = { "fastq_filtered": resource_path + "bsSeeker.Mouse.SRR892982_1.filtered.fastq" } metadata = { "fastq": Metadata( "data_wgbs", "fastq", input_files["fastq"], None, {'assembly': 'test'}) } config_param = { "aligner": "bowtie2", "aligner_path": home + "/lib/bowtie2-2.3.4-linux-x86_64", "bss_path": home + "/lib/BSseeker2", "execution": resource_path } bsi = bs_seeker_filter.filterReadsTool(config_param) bsi.run(input_files, metadata, output_files) assert os.path.isfile(output_files["fastq_filtered"]) is True assert os.path.getsize(output_files["fastq_filtered"]) > 0 @pytest.mark.wgbs def test_bs_seeker_filter_02(): """ Test that it is possible to call the BSseeker filter """ resource_path = os.path.join(os.path.dirname(__file__), "data/") home = os.path.expanduser('~') input_files = { "fastq": resource_path + "bsSeeker.Mouse.SRR892982_2.fastq" } output_files = { "fastq_filtered": resource_path + "bsSeeker.Mouse.SRR892982_2.filtered.fastq" } metadata = { "fastq": Metadata( "data_wgbs", "fastq", input_files["fastq"], None, {'assembly': 'test'}) } config_param = { "aligner": "bowtie2", "aligner_path": home + "/lib/bowtie2-2.3.4-linux-x86_64", "bss_path": home + "/lib/BSseeker2", "execution": resource_path } bsi = bs_seeker_filter.filterReadsTool(config_param) bsi.run(input_files, metadata, output_files) assert os.path.isfile(output_files["fastq_filtered"]) is True assert os.path.getsize(output_files["fastq_filtered"]) > 0
""" .. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import gzip import pytest from basic_modules.metadata import Metadata from tool import bs_seeker_filter @pytest.mark.wgbs def test_bs_seeker_filter_00(): """ Extract the compressed FASTQ files """ resource_path = os.path.join(os.path.dirname(__file__), "data/") fastq_file_1 = resource_path + "bsSeeker.Mouse.SRR892982_1.fastq" fastq_file_2 = resource_path + "bsSeeker.Mouse.SRR892982_2.fastq" with gzip.open(fastq_file_1 + '.gz', 'rb') as fgz_in: with open(fastq_file_1, 'w') as f_out: f_out.write(fgz_in.read()) with gzip.open(fastq_file_2 + '.gz', 'rb') as fgz_in: with open(fastq_file_2, 'w') as f_out: f_out.write(fgz_in.read()) assert os.path.isfile(fastq_file_1) is True assert os.path.getsize(fastq_file_1) > 0 assert os.path.isfile(fastq_file_2) is True assert os.path.getsize(fastq_file_2) > 0 @pytest.mark.wgbs def test_bs_seeker_filter_01(): """ Test that it is possible to call the BSseeker filter """ resource_path = os.path.join(os.path.dirname(__file__), "data/") home = os.path.expanduser('~') input_files = { "fastq": resource_path + "bsSeeker.Mouse.SRR892982_1.fastq" } output_files = { "fastq_filtered": resource_path + "bsSeeker.Mouse.SRR892982_1.filtered.fastq" } metadata = { "fastq": Metadata( "data_wgbs", "fastq", input_files["fastq"], None, {'assembly': 'test'}) } config_param = { "aligner": "bowtie2", "aligner_path": home + "/lib/bowtie2-2.3.4-linux-x86_64", "bss_path": home + "/lib/BSseeker2", "execution": resource_path } bsi = bs_seeker_filter.filterReadsTool(config_param) bsi.run(input_files, metadata, output_files) assert os.path.isfile(output_files["fastq_filtered"]) is True assert os.path.getsize(output_files["fastq_filtered"]) > 0 @pytest.mark.wgbs def test_bs_seeker_filter_02(): """ Test that it is possible to call the BSseeker filter """ resource_path = os.path.join(os.path.dirname(__file__), "data/") home = os.path.expanduser('~') input_files = { "fastq": resource_path + "bsSeeker.Mouse.SRR892982_2.fastq" } output_files = { "fastq_filtered": resource_path + "bsSeeker.Mouse.SRR892982_2.filtered.fastq" } metadata = { "fastq": Metadata( "data_wgbs", "fastq", input_files["fastq"], None, {'assembly': 'test'}) } config_param = { "aligner": "bowtie2", "aligner_path": home + "/lib/bowtie2-2.3.4-linux-x86_64", "bss_path": home + "/lib/BSseeker2", "execution": resource_path } bsi = bs_seeker_filter.filterReadsTool(config_param) bsi.run(input_files, metadata, output_files) assert os.path.isfile(output_files["fastq_filtered"]) is True assert os.path.getsize(output_files["fastq_filtered"]) > 0
en
0.882957
.. See the NOTICE file distributed with this work for additional information regarding copyright ownership. 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. Extract the compressed FASTQ files Test that it is possible to call the BSseeker filter Test that it is possible to call the BSseeker filter
1.914428
2
assignments/assignment2/assignment2.py
royadams/intro_to_numerical_computing_with_python
1
6612671
<gh_stars>1-10 import unittest import numpy as np #################################################### # Problem 1: Classes #################################################### class Course: def __init__(self, course_number): ## Add code here ## pass def get_course_number(self): ## Add code here ## pass def add_student(self, student): ## Add code here ## pass def drop_student(self,student_id): ## Add code here ## pass def get_roster(self): ## Add code here ## pass #################################################### # Problem 2: Root Finding #################################################### def find_roots(a,b,c): ## Add code here ## return []
import unittest import numpy as np #################################################### # Problem 1: Classes #################################################### class Course: def __init__(self, course_number): ## Add code here ## pass def get_course_number(self): ## Add code here ## pass def add_student(self, student): ## Add code here ## pass def drop_student(self,student_id): ## Add code here ## pass def get_roster(self): ## Add code here ## pass #################################################### # Problem 2: Root Finding #################################################### def find_roots(a,b,c): ## Add code here ## return []
de
0.678578
#################################################### # Problem 1: Classes #################################################### ## Add code here ## ## Add code here ## ## Add code here ## ## Add code here ## ## Add code here ## #################################################### # Problem 2: Root Finding #################################################### ## Add code here ##
3.460747
3
castor/mount_alignment.py
coupole-orsay/castor
0
6612672
<gh_stars>0 #!/usr/bin/env python3 import numpy as np from numpy import sin, cos from astropy import units as u from astropy import constants as c Ωsid = u.Quantity(360, 'deg') / u.Quantity(24, 'h') * 366.2422 / 365.2422 def r2d(ang): try: if ang.to('').unit is u.dimensionless_unscaled: ang = ang.to('').value except (AttributeError, u.UnitconversionError): pass ang = u.Quantity(ang, 'rad').to('deg') return ang def rotation_to_screw_turns(angle_variation, axis): if axis.lower() in ('az', 'azimuth', 'lon', 'longitude'): a = u.Quantity(3.400, 'cycle / deg') elif axis.lower() in ('alt', 'altitude', 'lat', 'latitude'): a = u.Quantity(3.707, 'cycle / deg') else: raise ValueError('Unknown axis: {}'.format(axis)) return (a * angle_variation).to('cycle') def drifts_to_adjustments(ωδ, ωH, δ, H, φ): ''' Get the alignment corrections to apply to a mount given measured drifts. Parameters ========== ωδ : declination drift ωH : right ascension drift δ : declination of the tracked star H : hour angle of the tracked star φ : latitude of observation location Returns ======= Δφ : correction to the altitude axis ΔA : correction to the azimuth axis ''' a = 1 / (Ωsid * sin(δ) * (sin(H)**2 + cos(H)**2 * cos(φ))) Δφ = a * (- sin(H) * sin(δ) * ωδ + cos(H) * cos(φ) * ωH) ΔA = a * (cos(H) * sin(δ) * ωδ + sin(H) * ωH) return r2d(Δφ), r2d(ΔA) def bigourdan(ωδ, φ, where): if where.lower() in ('s', 'south'): ΔA = ωδ / (Ωsid * cos(φ)) return r2d(ΔA) elif where.lower() in ('e', 'east'): Δφ = + ωδ / Ωsid return r2d(Δφ) elif where.lower() in ('w', 'west'): Δφ = - ωδ / Ωsid return r2d(Δφ) else: raise ValueError('unknown_location') if __name__ == '__main__': # Coupole 470 φ = u.Quantity(48.70272, 'deg') θ = u.Quantity(2.18270, 'deg') ωδ = u.Quantity(726.87, 'arcsec / h') ωH = u.Quantity(-31.78, 'arcsec / h') # # altair # δ = u.Quantity(9, 'deg') # H = u.Quantity(3.25, 'hourangle') # # deneb # δ = u.Quantity(45, 'deg') # H = u.Quantity(2.5, 'hourangle') # 59 aql 2018-11-30 19:20 CET δ = u.Quantity(8.5, 'deg') H = u.Quantity(3.25, 'hourangle') Δφ, ΔA = drifts_to_adjustments(ωδ, ωH, δ, H, φ) print('Alt / Az') print('{:.3g} {:.3g}'.format(Δφ, ΔA)) print('{:.3g} {:.3g}'.format( rotation_to_screw_turns(Δφ, 'alt'), rotation_to_screw_turns(ΔA, 'az'), )) # ωδ = u.Quantity(726.87, 'arcsec / h') # where = 'west' # Δ = bigourdan(ωδ, φ, where) # print(Δ)
#!/usr/bin/env python3 import numpy as np from numpy import sin, cos from astropy import units as u from astropy import constants as c Ωsid = u.Quantity(360, 'deg') / u.Quantity(24, 'h') * 366.2422 / 365.2422 def r2d(ang): try: if ang.to('').unit is u.dimensionless_unscaled: ang = ang.to('').value except (AttributeError, u.UnitconversionError): pass ang = u.Quantity(ang, 'rad').to('deg') return ang def rotation_to_screw_turns(angle_variation, axis): if axis.lower() in ('az', 'azimuth', 'lon', 'longitude'): a = u.Quantity(3.400, 'cycle / deg') elif axis.lower() in ('alt', 'altitude', 'lat', 'latitude'): a = u.Quantity(3.707, 'cycle / deg') else: raise ValueError('Unknown axis: {}'.format(axis)) return (a * angle_variation).to('cycle') def drifts_to_adjustments(ωδ, ωH, δ, H, φ): ''' Get the alignment corrections to apply to a mount given measured drifts. Parameters ========== ωδ : declination drift ωH : right ascension drift δ : declination of the tracked star H : hour angle of the tracked star φ : latitude of observation location Returns ======= Δφ : correction to the altitude axis ΔA : correction to the azimuth axis ''' a = 1 / (Ωsid * sin(δ) * (sin(H)**2 + cos(H)**2 * cos(φ))) Δφ = a * (- sin(H) * sin(δ) * ωδ + cos(H) * cos(φ) * ωH) ΔA = a * (cos(H) * sin(δ) * ωδ + sin(H) * ωH) return r2d(Δφ), r2d(ΔA) def bigourdan(ωδ, φ, where): if where.lower() in ('s', 'south'): ΔA = ωδ / (Ωsid * cos(φ)) return r2d(ΔA) elif where.lower() in ('e', 'east'): Δφ = + ωδ / Ωsid return r2d(Δφ) elif where.lower() in ('w', 'west'): Δφ = - ωδ / Ωsid return r2d(Δφ) else: raise ValueError('unknown_location') if __name__ == '__main__': # Coupole 470 φ = u.Quantity(48.70272, 'deg') θ = u.Quantity(2.18270, 'deg') ωδ = u.Quantity(726.87, 'arcsec / h') ωH = u.Quantity(-31.78, 'arcsec / h') # # altair # δ = u.Quantity(9, 'deg') # H = u.Quantity(3.25, 'hourangle') # # deneb # δ = u.Quantity(45, 'deg') # H = u.Quantity(2.5, 'hourangle') # 59 aql 2018-11-30 19:20 CET δ = u.Quantity(8.5, 'deg') H = u.Quantity(3.25, 'hourangle') Δφ, ΔA = drifts_to_adjustments(ωδ, ωH, δ, H, φ) print('Alt / Az') print('{:.3g} {:.3g}'.format(Δφ, ΔA)) print('{:.3g} {:.3g}'.format( rotation_to_screw_turns(Δφ, 'alt'), rotation_to_screw_turns(ΔA, 'az'), )) # ωδ = u.Quantity(726.87, 'arcsec / h') # where = 'west' # Δ = bigourdan(ωδ, φ, where) # print(Δ)
en
0.468201
#!/usr/bin/env python3 Get the alignment corrections to apply to a mount given measured drifts. Parameters ========== ωδ : declination drift ωH : right ascension drift δ : declination of the tracked star H : hour angle of the tracked star φ : latitude of observation location Returns ======= Δφ : correction to the altitude axis ΔA : correction to the azimuth axis # Coupole 470 # # altair # δ = u.Quantity(9, 'deg') # H = u.Quantity(3.25, 'hourangle') # # deneb # δ = u.Quantity(45, 'deg') # H = u.Quantity(2.5, 'hourangle') # 59 aql 2018-11-30 19:20 CET # ωδ = u.Quantity(726.87, 'arcsec / h') # where = 'west' # Δ = bigourdan(ωδ, φ, where) # print(Δ)
2.620076
3
termapp/dialog_user_pass.py
faintcoder/termapp
1
6612673
#!/usr/bin/env python3 import urwid from .common import * from .dialog_base import DialogBase class DialogUserPass(DialogBase): def __init__( self, main_application, text = "Enter username and password.", title = "Login", tag = "tag" ): self.userWidget = urwid.Edit("User: ", "") self.passWidget = urwid.Edit("Pass: ", "", mask="*") super().__init__( main_application = main_application, text = text, title = title, tag = tag, width = 40, height = 15, buttons = 2, button_captions = ["Enter", "Cancel"], additional_widgets = [self.userWidget, self.passWidget], focus = "body" ) def onResult(self, button_tuple): self.result["username"] = self.userWidget.get_edit_text() self.result["password"] = self.passWidget.get_edit_text() super().onResult(button_tuple) def keypress(self, size, key): if key == "enter" or key == "tab": if self.widget.get_focus() == "body": column_widget_in_focus = self.pile.focus_position if column_widget_in_focus == 1: self.pile.set_focus(2) return if column_widget_in_focus == 2: self.widget.set_focus("footer") return if key == "tab": if self.widget.get_focus() == "footer": self.widget.set_focus("body") self.pile.set_focus(1) super().keypress(size, key)
#!/usr/bin/env python3 import urwid from .common import * from .dialog_base import DialogBase class DialogUserPass(DialogBase): def __init__( self, main_application, text = "Enter username and password.", title = "Login", tag = "tag" ): self.userWidget = urwid.Edit("User: ", "") self.passWidget = urwid.Edit("Pass: ", "", mask="*") super().__init__( main_application = main_application, text = text, title = title, tag = tag, width = 40, height = 15, buttons = 2, button_captions = ["Enter", "Cancel"], additional_widgets = [self.userWidget, self.passWidget], focus = "body" ) def onResult(self, button_tuple): self.result["username"] = self.userWidget.get_edit_text() self.result["password"] = self.passWidget.get_edit_text() super().onResult(button_tuple) def keypress(self, size, key): if key == "enter" or key == "tab": if self.widget.get_focus() == "body": column_widget_in_focus = self.pile.focus_position if column_widget_in_focus == 1: self.pile.set_focus(2) return if column_widget_in_focus == 2: self.widget.set_focus("footer") return if key == "tab": if self.widget.get_focus() == "footer": self.widget.set_focus("body") self.pile.set_focus(1) super().keypress(size, key)
fr
0.221828
#!/usr/bin/env python3
2.502468
3
src/s3_manager/src/access_point.py
shankarr-code/backend-apis
34
6612674
#!/usr/bin/env python3 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 """ This script performs 2 operations: PUT operation by creating access points on the bucket. GET operation to retrieve objects based on access-point. """ import os from http import HTTPStatus import botocore import constants import helper ACCOUNT_ID = os.environ["AWS_ACCOUNT_ID"] ACCESSPOINT_BASE_ARN = "arn:aws:s3:{0}:{1}:accesspoint".format( os.environ["AWS_REGION"], os.environ["AWS_ACCOUNT_ID"], ) def put_object(sts_creds, req_header): """ Uploads objects into s3 bucket/prefix with {tenant_id/user_id} along with access point per tenant {tenant_id} :param sts_creds: :param req_header: :return: 201 - Success 400 - Bad Request, 401 - Unauthorized 500 - Error, 503 - Unavailable """ try: s3_client = helper.get_boto3_client("s3", sts_creds) helper.check_create_bucket(s3_client, req_header["bucket_name"]) s3_ctl_client = helper.get_boto3_client("s3control", sts_creds) helper.check_create_access_point(s3_ctl_client, req_header["bucket_name"], ACCOUNT_ID, req_header["access_point_name"]) api_put_resp = s3_client.put_object(Bucket=req_header["bucket_name"], Key='{0}/{1}'.format(req_header["prefix"], req_header["object_key"]), Body=req_header["object_value"]) if api_put_resp and \ api_put_resp['ResponseMetadata']['HTTPStatusCode'] == HTTPStatus.OK: return helper.success_response(api_put_resp) else: return helper.failure_response("Operation failed. Please retry.", HTTPStatus.SERVICE_UNAVAILABLE) except Exception as ex: return helper.failure_response(helper.format_exception(ex)) def get_object(sts_creds, req_header): """ Retrieve objects based on access points per tenant :param sts_creds: :param req_header: :return: 200 - Success 400 - Bad Request, 401 - Unauthorized 500 - Error, 503 - Unavailable """ try: s3_client = helper.get_boto3_client("s3", sts_creds) s3_ctl_client = helper.get_boto3_client("s3control", sts_creds) s3_ctl_client.get_access_point(AccountId=ACCOUNT_ID, Name=req_header["access_point_name"]) api_list_resp = s3_client.list_objects_v2(Bucket=req_header["access_point_arn"], Prefix=req_header["prefix"]) if api_list_resp and api_list_resp['KeyCount'] > 0: user_objects = [obj['Key'].rsplit('/', 1)[-1] for obj in api_list_resp['Contents']] return helper.success_response(user_objects, HTTPStatus.OK) else: return helper.failure_response("Operation failed. Please retry.", HTTPStatus.SERVICE_UNAVAILABLE) except botocore.exceptions.ClientError as ex: return helper.failure_response_message(helper.format_exception(ex), ex.response["Error"]["Code"]) except Exception as ex: return helper.failure_response(helper.format_exception(ex)) def populate_context(event): """ Adds derived fields to support operations :param req_header: """ req_header = helper.get_tenant_context(event) if "missing_fields" in req_header: return req_header bucket_name = "{0}-{1}".format(constants.BUCKET_NAME_AP, os.environ["AWS_ACCOUNT_ID"]) access_point_name = sanitize_ap_name(req_header['tenant_id']) req_header.update({ "bucket_name": bucket_name, "bucket_arn": "arn:aws:s3:::{0}".format(bucket_name), "prefix": "{0}/{1}".format(req_header["tenant_id"], req_header["user_id"]), "access_point_name": access_point_name, "access_point_arn": "{0}/{1}".format(ACCESSPOINT_BASE_ARN, access_point_name) }) return req_header def sanitize_ap_name(input_name): """ Returns access_point name that begins with a number or lowercase letter, 3 to 50 chars long, no dash at begin or end, no underscores, uppercase letters, or periods :param input_name: """ output_name = input_name.translate( str.maketrans({'_': '', '.': ''}) ) if output_name.startswith('-'): output_name = output_name[1:] if output_name.endswith('-'): output_name = output_name[0:-1] return output_name[0:50].lower()
#!/usr/bin/env python3 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 """ This script performs 2 operations: PUT operation by creating access points on the bucket. GET operation to retrieve objects based on access-point. """ import os from http import HTTPStatus import botocore import constants import helper ACCOUNT_ID = os.environ["AWS_ACCOUNT_ID"] ACCESSPOINT_BASE_ARN = "arn:aws:s3:{0}:{1}:accesspoint".format( os.environ["AWS_REGION"], os.environ["AWS_ACCOUNT_ID"], ) def put_object(sts_creds, req_header): """ Uploads objects into s3 bucket/prefix with {tenant_id/user_id} along with access point per tenant {tenant_id} :param sts_creds: :param req_header: :return: 201 - Success 400 - Bad Request, 401 - Unauthorized 500 - Error, 503 - Unavailable """ try: s3_client = helper.get_boto3_client("s3", sts_creds) helper.check_create_bucket(s3_client, req_header["bucket_name"]) s3_ctl_client = helper.get_boto3_client("s3control", sts_creds) helper.check_create_access_point(s3_ctl_client, req_header["bucket_name"], ACCOUNT_ID, req_header["access_point_name"]) api_put_resp = s3_client.put_object(Bucket=req_header["bucket_name"], Key='{0}/{1}'.format(req_header["prefix"], req_header["object_key"]), Body=req_header["object_value"]) if api_put_resp and \ api_put_resp['ResponseMetadata']['HTTPStatusCode'] == HTTPStatus.OK: return helper.success_response(api_put_resp) else: return helper.failure_response("Operation failed. Please retry.", HTTPStatus.SERVICE_UNAVAILABLE) except Exception as ex: return helper.failure_response(helper.format_exception(ex)) def get_object(sts_creds, req_header): """ Retrieve objects based on access points per tenant :param sts_creds: :param req_header: :return: 200 - Success 400 - Bad Request, 401 - Unauthorized 500 - Error, 503 - Unavailable """ try: s3_client = helper.get_boto3_client("s3", sts_creds) s3_ctl_client = helper.get_boto3_client("s3control", sts_creds) s3_ctl_client.get_access_point(AccountId=ACCOUNT_ID, Name=req_header["access_point_name"]) api_list_resp = s3_client.list_objects_v2(Bucket=req_header["access_point_arn"], Prefix=req_header["prefix"]) if api_list_resp and api_list_resp['KeyCount'] > 0: user_objects = [obj['Key'].rsplit('/', 1)[-1] for obj in api_list_resp['Contents']] return helper.success_response(user_objects, HTTPStatus.OK) else: return helper.failure_response("Operation failed. Please retry.", HTTPStatus.SERVICE_UNAVAILABLE) except botocore.exceptions.ClientError as ex: return helper.failure_response_message(helper.format_exception(ex), ex.response["Error"]["Code"]) except Exception as ex: return helper.failure_response(helper.format_exception(ex)) def populate_context(event): """ Adds derived fields to support operations :param req_header: """ req_header = helper.get_tenant_context(event) if "missing_fields" in req_header: return req_header bucket_name = "{0}-{1}".format(constants.BUCKET_NAME_AP, os.environ["AWS_ACCOUNT_ID"]) access_point_name = sanitize_ap_name(req_header['tenant_id']) req_header.update({ "bucket_name": bucket_name, "bucket_arn": "arn:aws:s3:::{0}".format(bucket_name), "prefix": "{0}/{1}".format(req_header["tenant_id"], req_header["user_id"]), "access_point_name": access_point_name, "access_point_arn": "{0}/{1}".format(ACCESSPOINT_BASE_ARN, access_point_name) }) return req_header def sanitize_ap_name(input_name): """ Returns access_point name that begins with a number or lowercase letter, 3 to 50 chars long, no dash at begin or end, no underscores, uppercase letters, or periods :param input_name: """ output_name = input_name.translate( str.maketrans({'_': '', '.': ''}) ) if output_name.startswith('-'): output_name = output_name[1:] if output_name.endswith('-'): output_name = output_name[0:-1] return output_name[0:50].lower()
en
0.684972
#!/usr/bin/env python3 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 This script performs 2 operations: PUT operation by creating access points on the bucket. GET operation to retrieve objects based on access-point. Uploads objects into s3 bucket/prefix with {tenant_id/user_id} along with access point per tenant {tenant_id} :param sts_creds: :param req_header: :return: 201 - Success 400 - Bad Request, 401 - Unauthorized 500 - Error, 503 - Unavailable Retrieve objects based on access points per tenant :param sts_creds: :param req_header: :return: 200 - Success 400 - Bad Request, 401 - Unauthorized 500 - Error, 503 - Unavailable Adds derived fields to support operations :param req_header: Returns access_point name that begins with a number or lowercase letter, 3 to 50 chars long, no dash at begin or end, no underscores, uppercase letters, or periods :param input_name:
2.533772
3
spacy/lang/ur/stop_words.py
algteam/spacy_zh_model
5
6612675
# encoding: utf8 from __future__ import unicode_literals # Source: collected from different resource on internet STOP_WORDS = set(""" ثھی خو گی اپٌے گئے ثہت طرف ہوبری پبئے اپٌب دوضری گیب کت گب ثھی ضے ہر پر اش دی گے لگیں ہے ثعذ ضکتے تھی اى دیب لئے والے یہ ثدبئے ضکتی تھب اًذر رریعے لگی ہوبرا ہوًے ثبہر ضکتب ًہیں تو اور رہب لگے ہوضکتب ہوں کب ہوبرے توبم کیب ایطے رہی هگر ہوضکتی ہیں کریں ہو تک کی ایک رہے هیں ہوضکتے کیطے ہوًب تت کہ ہوا آئے ضبت تھے کیوں ہو تب کے پھر ثغیر خبر ہے رکھ کی طب کوئی رریعے ثبرے خب اضطرذ ثلکہ خجکہ رکھ تب کی طرف ثراں خبر رریعہ اضکب ثٌذ خص کی لئے توہیں دوضرے کررہی اضکی ثیچ خوکہ رکھتی کیوًکہ دوًوں کر رہے خبر ہی ثرآں اضکے پچھلا خیطب رکھتے کے ثعذ تو ہی دورى کر یہبں آش تھوڑا چکے زکویہ دوضروں ضکب اوًچب ثٌب پل تھوڑی چلا خبهوظ دیتب ضکٌب اخبزت اوًچبئی ثٌبرہب پوچھب تھوڑے چلو ختن دیتی ضکی اچھب اوًچی ثٌبرہی پوچھتب تیي چلیں در دیتے ضکے اچھی اوًچے ثٌبرہے پوچھتی خبًب چلے درخبت دیر ضلطلہ اچھے اٹھبًب ثٌبًب پوچھتے خبًتب چھوٹب درخہ دیکھٌب ضوچ اختتبم اہن ثٌذ پوچھٌب خبًتی چھوٹوں درخے دیکھو ضوچب ادھر آئی ثٌذکرًب پوچھو خبًتے چھوٹی درزقیقت دیکھی ضوچتب ارد آئے ثٌذکرو پوچھوں خبًٌب چھوٹے درضت دیکھیں ضوچتی اردگرد آج ثٌذی پوچھیں خططرذ چھہ دش دیٌب ضوچتے ارکبى آخر ثڑا پورا خگہ چیسیں دفعہ دے ضوچٌب اضتعوبل آخر پہلا خگہوں زبصل دکھبئیں راضتوں ضوچو اضتعوبلات آدهی ثڑی پہلی خگہیں زبضر دکھبتب راضتہ ضوچی اغیب آًب ثڑے پہلےضی خلذی زبل دکھبتی راضتے ضوچیں اطراف آٹھ ثھر خٌبة زبل دکھبتے رکي ضیذھب افراد آیب ثھرا پہلے خواى زبلات دکھبًب رکھب ضیذھی اکثر ثب ہوا پیع خوًہی زبلیہ دکھبو رکھی ضیذھے اکٹھب ثھرپور تبزٍ خیطبکہ زصوں رکھے ضیکٌڈ اکٹھی ثبری ثہتر تر چبر زصہ دلچطپ زیبدٍ غبیذ اکٹھے ثبلا ثہتری ترتیت چبہب زصے دلچطپی ضبت غخص اکیلا ثبلترتیت ثہتریي تریي چبہٌب زقبئق دلچطپیبں ضبدٍ غذ اکیلی ثرش پبش تعذاد چبہے زقیتیں هٌبضت ضبرا غروع اکیلے ثغیر پبًب چکب زقیقت دو ضبرے غروعبت اگرچہ ثلٌذ پبًچ تن چکی زکن دور ضبل غے الگ پراًب تٌہب چکیں دوضرا ضبلوں صبف صسیر قجیلہ کوًطے لازهی هطئلے ًیب طریق کرتی کہتے صفر قطن کھولا لگتب هطبئل وار طریقوں کرتے کہٌب صورت کئی کھولٌب لگتی هطتعول وار طریقہ کرتے ہو کہٌب صورتسبل کئے کھولو لگتے هػتول ٹھیک طریقے کرًب کہو صورتوں کبفی هطلق ڈھوًڈا طور کرو کہوں صورتیں کبم کھولیں لگی هعلوم ڈھوًڈلیب طورپر کریں کہی ضرور کجھی کھولے لگے هکول ڈھوًڈًب ظبہر کرے کہیں ضرورت کرا کہب لوجب هلا ڈھوًڈو عذد کل کہیں کرتب کہتب لوجی هوکي ڈھوًڈی عظین کن کہے ضروری کرتبہوں کہتی لوجے هوکٌبت ڈھوًڈیں علاقوں کوتر کیے لوسبت هوکٌہ ہن لے ًبپطٌذ ہورہے علاقہ کورا کے رریعے لوسہ هڑا ہوئی هتعلق ًبگسیر ہوگئی علاقے کوروں گئی لو هڑًب ہوئے هسترم ًطجت ہو گئے علاوٍ کورٍ گرد لوگ هڑے ہوتی هسترهہ ًقطہ ہوگیب کورے گروپ لوگوں هہرثبى ہوتے هسطوش ًکبلٌب ہوًی عووهی کوطي گروٍ لڑکپي هیرا ہوچکب هختلف ًکتہ ہی فرد کوى گروہوں لی هیری ہوچکی هسیذ فی کوًطب گٌتی لیب هیرے ہوچکے هطئلہ ًوخواى یقیٌی قجل کوًطی لیٌب ًئی ہورہب لیں ًئے ہورہی ثبعث ضت """.split())
# encoding: utf8 from __future__ import unicode_literals # Source: collected from different resource on internet STOP_WORDS = set(""" ثھی خو گی اپٌے گئے ثہت طرف ہوبری پبئے اپٌب دوضری گیب کت گب ثھی ضے ہر پر اش دی گے لگیں ہے ثعذ ضکتے تھی اى دیب لئے والے یہ ثدبئے ضکتی تھب اًذر رریعے لگی ہوبرا ہوًے ثبہر ضکتب ًہیں تو اور رہب لگے ہوضکتب ہوں کب ہوبرے توبم کیب ایطے رہی هگر ہوضکتی ہیں کریں ہو تک کی ایک رہے هیں ہوضکتے کیطے ہوًب تت کہ ہوا آئے ضبت تھے کیوں ہو تب کے پھر ثغیر خبر ہے رکھ کی طب کوئی رریعے ثبرے خب اضطرذ ثلکہ خجکہ رکھ تب کی طرف ثراں خبر رریعہ اضکب ثٌذ خص کی لئے توہیں دوضرے کررہی اضکی ثیچ خوکہ رکھتی کیوًکہ دوًوں کر رہے خبر ہی ثرآں اضکے پچھلا خیطب رکھتے کے ثعذ تو ہی دورى کر یہبں آش تھوڑا چکے زکویہ دوضروں ضکب اوًچب ثٌب پل تھوڑی چلا خبهوظ دیتب ضکٌب اخبزت اوًچبئی ثٌبرہب پوچھب تھوڑے چلو ختن دیتی ضکی اچھب اوًچی ثٌبرہی پوچھتب تیي چلیں در دیتے ضکے اچھی اوًچے ثٌبرہے پوچھتی خبًب چلے درخبت دیر ضلطلہ اچھے اٹھبًب ثٌبًب پوچھتے خبًتب چھوٹب درخہ دیکھٌب ضوچ اختتبم اہن ثٌذ پوچھٌب خبًتی چھوٹوں درخے دیکھو ضوچب ادھر آئی ثٌذکرًب پوچھو خبًتے چھوٹی درزقیقت دیکھی ضوچتب ارد آئے ثٌذکرو پوچھوں خبًٌب چھوٹے درضت دیکھیں ضوچتی اردگرد آج ثٌذی پوچھیں خططرذ چھہ دش دیٌب ضوچتے ارکبى آخر ثڑا پورا خگہ چیسیں دفعہ دے ضوچٌب اضتعوبل آخر پہلا خگہوں زبصل دکھبئیں راضتوں ضوچو اضتعوبلات آدهی ثڑی پہلی خگہیں زبضر دکھبتب راضتہ ضوچی اغیب آًب ثڑے پہلےضی خلذی زبل دکھبتی راضتے ضوچیں اطراف آٹھ ثھر خٌبة زبل دکھبتے رکي ضیذھب افراد آیب ثھرا پہلے خواى زبلات دکھبًب رکھب ضیذھی اکثر ثب ہوا پیع خوًہی زبلیہ دکھبو رکھی ضیذھے اکٹھب ثھرپور تبزٍ خیطبکہ زصوں رکھے ضیکٌڈ اکٹھی ثبری ثہتر تر چبر زصہ دلچطپ زیبدٍ غبیذ اکٹھے ثبلا ثہتری ترتیت چبہب زصے دلچطپی ضبت غخص اکیلا ثبلترتیت ثہتریي تریي چبہٌب زقبئق دلچطپیبں ضبدٍ غذ اکیلی ثرش پبش تعذاد چبہے زقیتیں هٌبضت ضبرا غروع اکیلے ثغیر پبًب چکب زقیقت دو ضبرے غروعبت اگرچہ ثلٌذ پبًچ تن چکی زکن دور ضبل غے الگ پراًب تٌہب چکیں دوضرا ضبلوں صبف صسیر قجیلہ کوًطے لازهی هطئلے ًیب طریق کرتی کہتے صفر قطن کھولا لگتب هطبئل وار طریقوں کرتے کہٌب صورت کئی کھولٌب لگتی هطتعول وار طریقہ کرتے ہو کہٌب صورتسبل کئے کھولو لگتے هػتول ٹھیک طریقے کرًب کہو صورتوں کبفی هطلق ڈھوًڈا طور کرو کہوں صورتیں کبم کھولیں لگی هعلوم ڈھوًڈلیب طورپر کریں کہی ضرور کجھی کھولے لگے هکول ڈھوًڈًب ظبہر کرے کہیں ضرورت کرا کہب لوجب هلا ڈھوًڈو عذد کل کہیں کرتب کہتب لوجی هوکي ڈھوًڈی عظین کن کہے ضروری کرتبہوں کہتی لوجے هوکٌبت ڈھوًڈیں علاقوں کوتر کیے لوسبت هوکٌہ ہن لے ًبپطٌذ ہورہے علاقہ کورا کے رریعے لوسہ هڑا ہوئی هتعلق ًبگسیر ہوگئی علاقے کوروں گئی لو هڑًب ہوئے هسترم ًطجت ہو گئے علاوٍ کورٍ گرد لوگ هڑے ہوتی هسترهہ ًقطہ ہوگیب کورے گروپ لوگوں هہرثبى ہوتے هسطوش ًکبلٌب ہوًی عووهی کوطي گروٍ لڑکپي هیرا ہوچکب هختلف ًکتہ ہی فرد کوى گروہوں لی هیری ہوچکی هسیذ فی کوًطب گٌتی لیب هیرے ہوچکے هطئلہ ًوخواى یقیٌی قجل کوًطی لیٌب ًئی ہورہب لیں ًئے ہورہی ثبعث ضت """.split())
ur
0.747931
# encoding: utf8 # Source: collected from different resource on internet ثھی خو گی اپٌے گئے ثہت طرف ہوبری پبئے اپٌب دوضری گیب کت گب ثھی ضے ہر پر اش دی گے لگیں ہے ثعذ ضکتے تھی اى دیب لئے والے یہ ثدبئے ضکتی تھب اًذر رریعے لگی ہوبرا ہوًے ثبہر ضکتب ًہیں تو اور رہب لگے ہوضکتب ہوں کب ہوبرے توبم کیب ایطے رہی هگر ہوضکتی ہیں کریں ہو تک کی ایک رہے هیں ہوضکتے کیطے ہوًب تت کہ ہوا آئے ضبت تھے کیوں ہو تب کے پھر ثغیر خبر ہے رکھ کی طب کوئی رریعے ثبرے خب اضطرذ ثلکہ خجکہ رکھ تب کی طرف ثراں خبر رریعہ اضکب ثٌذ خص کی لئے توہیں دوضرے کررہی اضکی ثیچ خوکہ رکھتی کیوًکہ دوًوں کر رہے خبر ہی ثرآں اضکے پچھلا خیطب رکھتے کے ثعذ تو ہی دورى کر یہبں آش تھوڑا چکے زکویہ دوضروں ضکب اوًچب ثٌب پل تھوڑی چلا خبهوظ دیتب ضکٌب اخبزت اوًچبئی ثٌبرہب پوچھب تھوڑے چلو ختن دیتی ضکی اچھب اوًچی ثٌبرہی پوچھتب تیي چلیں در دیتے ضکے اچھی اوًچے ثٌبرہے پوچھتی خبًب چلے درخبت دیر ضلطلہ اچھے اٹھبًب ثٌبًب پوچھتے خبًتب چھوٹب درخہ دیکھٌب ضوچ اختتبم اہن ثٌذ پوچھٌب خبًتی چھوٹوں درخے دیکھو ضوچب ادھر آئی ثٌذکرًب پوچھو خبًتے چھوٹی درزقیقت دیکھی ضوچتب ارد آئے ثٌذکرو پوچھوں خبًٌب چھوٹے درضت دیکھیں ضوچتی اردگرد آج ثٌذی پوچھیں خططرذ چھہ دش دیٌب ضوچتے ارکبى آخر ثڑا پورا خگہ چیسیں دفعہ دے ضوچٌب اضتعوبل آخر پہلا خگہوں زبصل دکھبئیں راضتوں ضوچو اضتعوبلات آدهی ثڑی پہلی خگہیں زبضر دکھبتب راضتہ ضوچی اغیب آًب ثڑے پہلےضی خلذی زبل دکھبتی راضتے ضوچیں اطراف آٹھ ثھر خٌبة زبل دکھبتے رکي ضیذھب افراد آیب ثھرا پہلے خواى زبلات دکھبًب رکھب ضیذھی اکثر ثب ہوا پیع خوًہی زبلیہ دکھبو رکھی ضیذھے اکٹھب ثھرپور تبزٍ خیطبکہ زصوں رکھے ضیکٌڈ اکٹھی ثبری ثہتر تر چبر زصہ دلچطپ زیبدٍ غبیذ اکٹھے ثبلا ثہتری ترتیت چبہب زصے دلچطپی ضبت غخص اکیلا ثبلترتیت ثہتریي تریي چبہٌب زقبئق دلچطپیبں ضبدٍ غذ اکیلی ثرش پبش تعذاد چبہے زقیتیں هٌبضت ضبرا غروع اکیلے ثغیر پبًب چکب زقیقت دو ضبرے غروعبت اگرچہ ثلٌذ پبًچ تن چکی زکن دور ضبل غے الگ پراًب تٌہب چکیں دوضرا ضبلوں صبف صسیر قجیلہ کوًطے لازهی هطئلے ًیب طریق کرتی کہتے صفر قطن کھولا لگتب هطبئل وار طریقوں کرتے کہٌب صورت کئی کھولٌب لگتی هطتعول وار طریقہ کرتے ہو کہٌب صورتسبل کئے کھولو لگتے هػتول ٹھیک طریقے کرًب کہو صورتوں کبفی هطلق ڈھوًڈا طور کرو کہوں صورتیں کبم کھولیں لگی هعلوم ڈھوًڈلیب طورپر کریں کہی ضرور کجھی کھولے لگے هکول ڈھوًڈًب ظبہر کرے کہیں ضرورت کرا کہب لوجب هلا ڈھوًڈو عذد کل کہیں کرتب کہتب لوجی هوکي ڈھوًڈی عظین کن کہے ضروری کرتبہوں کہتی لوجے هوکٌبت ڈھوًڈیں علاقوں کوتر کیے لوسبت هوکٌہ ہن لے ًبپطٌذ ہورہے علاقہ کورا کے رریعے لوسہ هڑا ہوئی هتعلق ًبگسیر ہوگئی علاقے کوروں گئی لو هڑًب ہوئے هسترم ًطجت ہو گئے علاوٍ کورٍ گرد لوگ هڑے ہوتی هسترهہ ًقطہ ہوگیب کورے گروپ لوگوں هہرثبى ہوتے هسطوش ًکبلٌب ہوًی عووهی کوطي گروٍ لڑکپي هیرا ہوچکب هختلف ًکتہ ہی فرد کوى گروہوں لی هیری ہوچکی هسیذ فی کوًطب گٌتی لیب هیرے ہوچکے هطئلہ ًوخواى یقیٌی قجل کوًطی لیٌب ًئی ہورہب لیں ًئے ہورہی ثبعث ضت
2.131112
2
baselines/node/node_experiment.py
xxchenxx/WellTunedSimpleNets
23
6612676
<reponame>xxchenxx/WellTunedSimpleNets import argparse import json import os import time from typing import List import numpy as np import openml from category_encoders import LeaveOneOutEncoder from qhoptim.pyt import QHAdam from sklearn.model_selection import ParameterGrid from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.metrics import balanced_accuracy_score import torch, torch.nn as nn import torch.nn.functional as F import lib from lib.utils import check_numpy, process_in_chunks def get_task_list( benchmark_task_file: str = 'path/to/tasks.txt', ) -> List[int]: """Get the task id list. Goes through the given file and collects all of the task ids. Parameters: ----------- benchmark_task_file: str A string to the path of the benchmark task file. Including the task file name. Returns: -------- benchmark_task_ids - list A list of all the task ids for the benchmark. """ with open(os.path.join(benchmark_task_file), 'r') as f: benchmark_info_str = f.readline() benchmark_task_ids = [int(task_id) for task_id in benchmark_info_str.split(' ')] return benchmark_task_ids def get_data( task_id: int, test_size: float = 0.2, validation_size: float = 0.25, seed: int = 11, ): task = openml.tasks.get_task(task_id=task_id) dataset = task.get_dataset() X, y, categorical_indicator, _ = dataset.get_data( dataset_format='dataframe', target=dataset.default_target_attribute, ) label_encoder = LabelEncoder() y = label_encoder.fit_transform(y) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=test_size, random_state=seed, stratify=y, ) if validation_size != 0: X_train, X_val, y_train, y_val = train_test_split( X_train, y_train, test_size=validation_size, random_state=seed, stratify=y_train, ) else: X_val = None y_val = None # the code below drops columns that are # completely null in the train set, however, are not null in the validation # and test set. train_column_nan_info = X_train.isna().all() only_nan_columns = [label for label, value in train_column_nan_info.items() if value] only_nan_columns = set(only_nan_columns) X_train.drop(only_nan_columns, axis='columns', inplace=True) X_test.drop(only_nan_columns, axis='columns', inplace=True) if validation_size != 0: X_val.drop(only_nan_columns, axis='columns', inplace=True) cat_encoder = LeaveOneOutEncoder() column_names = X_train.columns.to_numpy() categorical_column_names = [column_name for column_indicator, column_name in zip(categorical_indicator, column_names) if column_indicator] cat_encoder.fit(X_train[categorical_column_names], y_train) X_train[categorical_column_names] = cat_encoder.transform(X_train[categorical_column_names]) if validation_size != 0: X_val[categorical_column_names] = cat_encoder.transform(X_val[categorical_column_names]) X_val = X_val.values.astype('float32') X_test[categorical_column_names] = cat_encoder.transform(X_test[categorical_column_names]) X_train = X_train.values.astype('float32') X_test = X_test.values.astype('float32') dataset_name = dataset.name return { 'X_train': X_train, 'y_train': y_train, 'X_val': X_val, 'y_val': y_val, 'X_test': X_test, 'y_test': y_test, 'name': dataset_name, } def get_node_dataset( task_id: int, test_size: float = 0.2, validation_size: float = 0.25, seed: int = 11, refit=False, ): if not refit: data_splits = get_data( task_id, seed=seed, test_size=test_size, validation_size=validation_size, ) else: data_splits = get_data( task_id, seed=seed, test_size=test_size, validation_size=0, ) node_dataset = lib.Dataset( dataset=data_splits['name'], random_state=seed, quantile_transform=True, quantile_noise=1e-3, X_train=data_splits['X_train'], X_valid=data_splits['X_val'], X_test=data_splits['X_test'], y_train=data_splits['y_train'], y_valid=data_splits['y_val'], y_test=data_splits['y_test'], ) return node_dataset def evaluate_balanced_classification_error( trainer, X_test, y_test, device, batch_size=128, ): X_test = torch.as_tensor(X_test, device=device) y_test = check_numpy(y_test) trainer.train(False) with torch.no_grad(): logits = process_in_chunks(trainer.model, X_test, batch_size=batch_size) logits = check_numpy(logits) y_pred = np.argmax(logits, axis=1) error_rate = 1 - balanced_accuracy_score(y_test, y_pred) return error_rate def evaluate_node( data, config, device, experiment_name, epochs=105, batch_size=128, refit=False, ): config_start_time = time.time() num_examples = data.X_train.shape[0] num_features = data.X_train.shape[1] num_classes = len(set(data.y_train)) model = nn.Sequential( lib.DenseBlock( num_features, layer_dim=config['total_tree_count'], num_layers=config['num_layers'], tree_dim=num_classes + 1, flatten_output=False, depth=config['tree_depth'], choice_function=lib.entmax15, bin_function=lib.entmoid15, ), lib.Lambda(lambda x: x[..., :num_classes].mean(dim=-2)), ).to(device) with torch.no_grad(): res = model(torch.as_tensor(data.X_train[:batch_size], device=device)) # trigger data-aware init if torch.cuda.device_count() > 1: model = nn.DataParallel(model) trainer = lib.Trainer( model=model, loss_function=F.cross_entropy, experiment_name=experiment_name, warm_start=False, Optimizer=QHAdam, optimizer_params=dict(nus=(0.7, 1.0), betas=(0.95, 0.998)), verbose=True, n_last_checkpoints=5 ) loss_history, err_history = [], [] best_val_err = 1.0 best_step = 0 # calculate the number of early stopping rounds to # be around 10 epochs. Allow incomplete batches. number_batches_epoch = int(np.ceil(num_examples / batch_size)) early_stopping_rounds = 10 * number_batches_epoch report_frequency = number_batches_epoch print(early_stopping_rounds) # Flag if early stopping is hit or not early_stopping_activated = False for batch in lib.iterate_minibatches( data.X_train, data.y_train, batch_size=batch_size, shuffle=True, epochs=epochs, ): metrics = trainer.train_on_batch( *batch, device=device, ) loss_history.append(metrics['loss'].item()) # calculate the information below on every epoch if trainer.step % report_frequency == 0: train_err = evaluate_balanced_classification_error( trainer, data.X_train, data.y_train, device=device, batch_size=batch_size, ) if not refit: val_err = evaluate_balanced_classification_error( trainer, data.X_valid, data.y_valid, device=device, batch_size=batch_size, ) err_history.append(val_err) print("Val Error Rate: %0.5f" % (val_err)) if val_err < best_val_err: best_val_err = val_err best_step = trainer.step trainer.save_checkpoint(tag='best') print("Loss %.5f" % (metrics['loss'])) print("Train Error Rate: %0.5f" % (train_err)) if not refit: if trainer.step > best_step + early_stopping_rounds: print('BREAK. There is no improvement for {} steps'.format(early_stopping_rounds)) print("Best step: ", best_step) print("Best Val Error Rate: %0.5f" % (best_val_err)) early_stopping_activated = True break config_duration = time.time() - config_start_time if early_stopping_activated: best_epoch = int(best_step / report_frequency) else: best_epoch = int(trainer.step / report_frequency) # save the model in the end trainer.save_checkpoint(tag='best') # we will always have a best checkpoint, be it # from early stopping, be it from the normal training. trainer.load_checkpoint(tag='best') train_error_rate = evaluate_balanced_classification_error( trainer, data.X_train, data.y_train, device=device, batch_size=batch_size, ) if not refit: val_error_rate = evaluate_balanced_classification_error( trainer, data.X_valid, data.y_valid, device=device, batch_size=batch_size, ) else: val_error_rate = None test_error_rate = evaluate_balanced_classification_error( trainer, data.X_test, data.y_test, device=device, batch_size=batch_size, ) run_information = { 'train_error': train_error_rate, 'val_error': val_error_rate, 'test_error': test_error_rate, 'best_epoch': best_epoch, 'duration': config_duration } return run_information def predict_node( data, config, device, experiment_name, batch_size=128, refit=True, ): num_features = data.X_train.shape[1] num_classes = len(set(data.y_train)) model = nn.Sequential( lib.DenseBlock( num_features, layer_dim=config['total_tree_count'], num_layers=config['num_layers'], tree_dim=num_classes + 1, flatten_output=False, depth=config['tree_depth'], choice_function=lib.entmax15, bin_function=lib.entmoid15, ), lib.Lambda(lambda x: x[..., :num_classes].mean(dim=-2)), ).to(device) with torch.no_grad(): res = model(torch.as_tensor(data.X_train[:batch_size], device=device)) # trigger data-aware init if torch.cuda.device_count() > 1: model = nn.DataParallel(model) trainer = lib.Trainer( model=model, warm_start=True, loss_function=F.cross_entropy, experiment_name=experiment_name, Optimizer=QHAdam, optimizer_params=dict(nus=(0.7, 1.0), betas=(0.95, 0.998)), verbose=True, n_last_checkpoints=5 ) # we will always have a best checkpoint, be it # from early stopping, be it from the normal training. trainer.load_checkpoint(tag='best') train_error_rate = evaluate_balanced_classification_error( trainer, data.X_train, data.y_train, device=device, batch_size=batch_size, ) if not refit: val_error_rate = evaluate_balanced_classification_error( trainer, data.X_valid, data.y_valid, device=device, batch_size=batch_size, ) else: val_error_rate = None test_error_rate = evaluate_balanced_classification_error( trainer, data.X_test, data.y_test, device=device, batch_size=batch_size, ) run_information = { 'train_error': train_error_rate, 'val_error': val_error_rate, 'test_error': test_error_rate, } return run_information parser = argparse.ArgumentParser( description='Run node on a benchmark' ) # experiment setup arguments parser.add_argument( '--task_id', type=int, default=233090, ) parser.add_argument( '--batch_size', type=int, default=128, ) parser.add_argument( '--epochs', type=int, default=1, ) parser.add_argument( '--test_size', type=float, default=0.2, ) parser.add_argument( '--validation_size', type=float, default=0.25, ) parser.add_argument( '--seed', type=int, default=11, ) parser.add_argument( '--device', type=str, default="cpu", ) parser.add_argument( '--output_dir', type=str, default="./node_experiments", ) args = parser.parse_args() options = vars(args) print(options) if __name__ == '__main__': print("Experiment Started") start_time = time.time() hpo_phase = False task_dir = os.path.expanduser( os.path.join( args.output_dir, f'{args.seed}', f'{args.task_id}', ) ) data = get_node_dataset( seed=args.seed, task_id=args.task_id, test_size=args.test_size, validation_size=args.validation_size, refit=False, ) if hpo_phase: # Start HPO Phase print("HPO Phase started") param_grid = ParameterGrid( { 'num_layers': {2, 4, 8}, 'total_tree_count': {1024, 2048}, 'tree_depth': {6, 8}, 'tree_output_dim': {2, 3} } ) results = [] for config_counter, params in enumerate(param_grid): config_dir = os.path.join(task_dir, f'{config_counter}') print(params) run_information = evaluate_node( batch_size=args.batch_size, refit=False, data=data, config=params, device=args.device, experiment_name=config_dir, epochs=args.epochs, ) print(params) print(run_information) results.append( { 'val_error': run_information['val_error'], 'best_epoch': run_information['best_epoch'], 'config': params, } ) incumbent = sorted(results, key=lambda result: result['val_error'])[0] print(f"Best results, with validation error: {incumbent['val_error']}, " f"configuration: {incumbent['config']}") best_config = incumbent['config'] best_epoch = incumbent['best_epoch'] else: best_config = { 'num_layers': 2, 'total_tree_count': 1024, 'tree_depth': 6, 'tree_output_dim': 2, } run_information = evaluate_node( batch_size=args.batch_size, refit=False, data=data, config=best_config, device=args.device, experiment_name=os.path.join(task_dir, 'run'), epochs=args.epochs, ) best_epoch = run_information['best_epoch'] # Start Refit Phase print("Refit Started") refit_dir = os.path.join(task_dir, 'refit') print(f'Best epoch found for task: {args.task_id} in refit is: {best_epoch}') data = get_node_dataset( seed=args.seed, task_id=args.task_id, test_size=args.test_size, validation_size=0, refit=True, ) run_information = evaluate_node( batch_size=args.batch_size, refit=True, data=data, config=best_config, device=args.device, experiment_name=refit_dir, epochs=best_epoch, ) duration = time.time() - start_time os.makedirs(task_dir, exist_ok=True) result_dir = os.path.join( task_dir, 'results.json', ) result_dict = { 'train balanced accuracy': 1 - run_information['train_error'], 'test balanced accuracy': 1 - run_information['test_error'], 'task_id': args.task_id, 'duration': duration, } with open(result_dir, 'w') as file: json.dump(result_dict, file)
import argparse import json import os import time from typing import List import numpy as np import openml from category_encoders import LeaveOneOutEncoder from qhoptim.pyt import QHAdam from sklearn.model_selection import ParameterGrid from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.metrics import balanced_accuracy_score import torch, torch.nn as nn import torch.nn.functional as F import lib from lib.utils import check_numpy, process_in_chunks def get_task_list( benchmark_task_file: str = 'path/to/tasks.txt', ) -> List[int]: """Get the task id list. Goes through the given file and collects all of the task ids. Parameters: ----------- benchmark_task_file: str A string to the path of the benchmark task file. Including the task file name. Returns: -------- benchmark_task_ids - list A list of all the task ids for the benchmark. """ with open(os.path.join(benchmark_task_file), 'r') as f: benchmark_info_str = f.readline() benchmark_task_ids = [int(task_id) for task_id in benchmark_info_str.split(' ')] return benchmark_task_ids def get_data( task_id: int, test_size: float = 0.2, validation_size: float = 0.25, seed: int = 11, ): task = openml.tasks.get_task(task_id=task_id) dataset = task.get_dataset() X, y, categorical_indicator, _ = dataset.get_data( dataset_format='dataframe', target=dataset.default_target_attribute, ) label_encoder = LabelEncoder() y = label_encoder.fit_transform(y) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=test_size, random_state=seed, stratify=y, ) if validation_size != 0: X_train, X_val, y_train, y_val = train_test_split( X_train, y_train, test_size=validation_size, random_state=seed, stratify=y_train, ) else: X_val = None y_val = None # the code below drops columns that are # completely null in the train set, however, are not null in the validation # and test set. train_column_nan_info = X_train.isna().all() only_nan_columns = [label for label, value in train_column_nan_info.items() if value] only_nan_columns = set(only_nan_columns) X_train.drop(only_nan_columns, axis='columns', inplace=True) X_test.drop(only_nan_columns, axis='columns', inplace=True) if validation_size != 0: X_val.drop(only_nan_columns, axis='columns', inplace=True) cat_encoder = LeaveOneOutEncoder() column_names = X_train.columns.to_numpy() categorical_column_names = [column_name for column_indicator, column_name in zip(categorical_indicator, column_names) if column_indicator] cat_encoder.fit(X_train[categorical_column_names], y_train) X_train[categorical_column_names] = cat_encoder.transform(X_train[categorical_column_names]) if validation_size != 0: X_val[categorical_column_names] = cat_encoder.transform(X_val[categorical_column_names]) X_val = X_val.values.astype('float32') X_test[categorical_column_names] = cat_encoder.transform(X_test[categorical_column_names]) X_train = X_train.values.astype('float32') X_test = X_test.values.astype('float32') dataset_name = dataset.name return { 'X_train': X_train, 'y_train': y_train, 'X_val': X_val, 'y_val': y_val, 'X_test': X_test, 'y_test': y_test, 'name': dataset_name, } def get_node_dataset( task_id: int, test_size: float = 0.2, validation_size: float = 0.25, seed: int = 11, refit=False, ): if not refit: data_splits = get_data( task_id, seed=seed, test_size=test_size, validation_size=validation_size, ) else: data_splits = get_data( task_id, seed=seed, test_size=test_size, validation_size=0, ) node_dataset = lib.Dataset( dataset=data_splits['name'], random_state=seed, quantile_transform=True, quantile_noise=1e-3, X_train=data_splits['X_train'], X_valid=data_splits['X_val'], X_test=data_splits['X_test'], y_train=data_splits['y_train'], y_valid=data_splits['y_val'], y_test=data_splits['y_test'], ) return node_dataset def evaluate_balanced_classification_error( trainer, X_test, y_test, device, batch_size=128, ): X_test = torch.as_tensor(X_test, device=device) y_test = check_numpy(y_test) trainer.train(False) with torch.no_grad(): logits = process_in_chunks(trainer.model, X_test, batch_size=batch_size) logits = check_numpy(logits) y_pred = np.argmax(logits, axis=1) error_rate = 1 - balanced_accuracy_score(y_test, y_pred) return error_rate def evaluate_node( data, config, device, experiment_name, epochs=105, batch_size=128, refit=False, ): config_start_time = time.time() num_examples = data.X_train.shape[0] num_features = data.X_train.shape[1] num_classes = len(set(data.y_train)) model = nn.Sequential( lib.DenseBlock( num_features, layer_dim=config['total_tree_count'], num_layers=config['num_layers'], tree_dim=num_classes + 1, flatten_output=False, depth=config['tree_depth'], choice_function=lib.entmax15, bin_function=lib.entmoid15, ), lib.Lambda(lambda x: x[..., :num_classes].mean(dim=-2)), ).to(device) with torch.no_grad(): res = model(torch.as_tensor(data.X_train[:batch_size], device=device)) # trigger data-aware init if torch.cuda.device_count() > 1: model = nn.DataParallel(model) trainer = lib.Trainer( model=model, loss_function=F.cross_entropy, experiment_name=experiment_name, warm_start=False, Optimizer=QHAdam, optimizer_params=dict(nus=(0.7, 1.0), betas=(0.95, 0.998)), verbose=True, n_last_checkpoints=5 ) loss_history, err_history = [], [] best_val_err = 1.0 best_step = 0 # calculate the number of early stopping rounds to # be around 10 epochs. Allow incomplete batches. number_batches_epoch = int(np.ceil(num_examples / batch_size)) early_stopping_rounds = 10 * number_batches_epoch report_frequency = number_batches_epoch print(early_stopping_rounds) # Flag if early stopping is hit or not early_stopping_activated = False for batch in lib.iterate_minibatches( data.X_train, data.y_train, batch_size=batch_size, shuffle=True, epochs=epochs, ): metrics = trainer.train_on_batch( *batch, device=device, ) loss_history.append(metrics['loss'].item()) # calculate the information below on every epoch if trainer.step % report_frequency == 0: train_err = evaluate_balanced_classification_error( trainer, data.X_train, data.y_train, device=device, batch_size=batch_size, ) if not refit: val_err = evaluate_balanced_classification_error( trainer, data.X_valid, data.y_valid, device=device, batch_size=batch_size, ) err_history.append(val_err) print("Val Error Rate: %0.5f" % (val_err)) if val_err < best_val_err: best_val_err = val_err best_step = trainer.step trainer.save_checkpoint(tag='best') print("Loss %.5f" % (metrics['loss'])) print("Train Error Rate: %0.5f" % (train_err)) if not refit: if trainer.step > best_step + early_stopping_rounds: print('BREAK. There is no improvement for {} steps'.format(early_stopping_rounds)) print("Best step: ", best_step) print("Best Val Error Rate: %0.5f" % (best_val_err)) early_stopping_activated = True break config_duration = time.time() - config_start_time if early_stopping_activated: best_epoch = int(best_step / report_frequency) else: best_epoch = int(trainer.step / report_frequency) # save the model in the end trainer.save_checkpoint(tag='best') # we will always have a best checkpoint, be it # from early stopping, be it from the normal training. trainer.load_checkpoint(tag='best') train_error_rate = evaluate_balanced_classification_error( trainer, data.X_train, data.y_train, device=device, batch_size=batch_size, ) if not refit: val_error_rate = evaluate_balanced_classification_error( trainer, data.X_valid, data.y_valid, device=device, batch_size=batch_size, ) else: val_error_rate = None test_error_rate = evaluate_balanced_classification_error( trainer, data.X_test, data.y_test, device=device, batch_size=batch_size, ) run_information = { 'train_error': train_error_rate, 'val_error': val_error_rate, 'test_error': test_error_rate, 'best_epoch': best_epoch, 'duration': config_duration } return run_information def predict_node( data, config, device, experiment_name, batch_size=128, refit=True, ): num_features = data.X_train.shape[1] num_classes = len(set(data.y_train)) model = nn.Sequential( lib.DenseBlock( num_features, layer_dim=config['total_tree_count'], num_layers=config['num_layers'], tree_dim=num_classes + 1, flatten_output=False, depth=config['tree_depth'], choice_function=lib.entmax15, bin_function=lib.entmoid15, ), lib.Lambda(lambda x: x[..., :num_classes].mean(dim=-2)), ).to(device) with torch.no_grad(): res = model(torch.as_tensor(data.X_train[:batch_size], device=device)) # trigger data-aware init if torch.cuda.device_count() > 1: model = nn.DataParallel(model) trainer = lib.Trainer( model=model, warm_start=True, loss_function=F.cross_entropy, experiment_name=experiment_name, Optimizer=QHAdam, optimizer_params=dict(nus=(0.7, 1.0), betas=(0.95, 0.998)), verbose=True, n_last_checkpoints=5 ) # we will always have a best checkpoint, be it # from early stopping, be it from the normal training. trainer.load_checkpoint(tag='best') train_error_rate = evaluate_balanced_classification_error( trainer, data.X_train, data.y_train, device=device, batch_size=batch_size, ) if not refit: val_error_rate = evaluate_balanced_classification_error( trainer, data.X_valid, data.y_valid, device=device, batch_size=batch_size, ) else: val_error_rate = None test_error_rate = evaluate_balanced_classification_error( trainer, data.X_test, data.y_test, device=device, batch_size=batch_size, ) run_information = { 'train_error': train_error_rate, 'val_error': val_error_rate, 'test_error': test_error_rate, } return run_information parser = argparse.ArgumentParser( description='Run node on a benchmark' ) # experiment setup arguments parser.add_argument( '--task_id', type=int, default=233090, ) parser.add_argument( '--batch_size', type=int, default=128, ) parser.add_argument( '--epochs', type=int, default=1, ) parser.add_argument( '--test_size', type=float, default=0.2, ) parser.add_argument( '--validation_size', type=float, default=0.25, ) parser.add_argument( '--seed', type=int, default=11, ) parser.add_argument( '--device', type=str, default="cpu", ) parser.add_argument( '--output_dir', type=str, default="./node_experiments", ) args = parser.parse_args() options = vars(args) print(options) if __name__ == '__main__': print("Experiment Started") start_time = time.time() hpo_phase = False task_dir = os.path.expanduser( os.path.join( args.output_dir, f'{args.seed}', f'{args.task_id}', ) ) data = get_node_dataset( seed=args.seed, task_id=args.task_id, test_size=args.test_size, validation_size=args.validation_size, refit=False, ) if hpo_phase: # Start HPO Phase print("HPO Phase started") param_grid = ParameterGrid( { 'num_layers': {2, 4, 8}, 'total_tree_count': {1024, 2048}, 'tree_depth': {6, 8}, 'tree_output_dim': {2, 3} } ) results = [] for config_counter, params in enumerate(param_grid): config_dir = os.path.join(task_dir, f'{config_counter}') print(params) run_information = evaluate_node( batch_size=args.batch_size, refit=False, data=data, config=params, device=args.device, experiment_name=config_dir, epochs=args.epochs, ) print(params) print(run_information) results.append( { 'val_error': run_information['val_error'], 'best_epoch': run_information['best_epoch'], 'config': params, } ) incumbent = sorted(results, key=lambda result: result['val_error'])[0] print(f"Best results, with validation error: {incumbent['val_error']}, " f"configuration: {incumbent['config']}") best_config = incumbent['config'] best_epoch = incumbent['best_epoch'] else: best_config = { 'num_layers': 2, 'total_tree_count': 1024, 'tree_depth': 6, 'tree_output_dim': 2, } run_information = evaluate_node( batch_size=args.batch_size, refit=False, data=data, config=best_config, device=args.device, experiment_name=os.path.join(task_dir, 'run'), epochs=args.epochs, ) best_epoch = run_information['best_epoch'] # Start Refit Phase print("Refit Started") refit_dir = os.path.join(task_dir, 'refit') print(f'Best epoch found for task: {args.task_id} in refit is: {best_epoch}') data = get_node_dataset( seed=args.seed, task_id=args.task_id, test_size=args.test_size, validation_size=0, refit=True, ) run_information = evaluate_node( batch_size=args.batch_size, refit=True, data=data, config=best_config, device=args.device, experiment_name=refit_dir, epochs=best_epoch, ) duration = time.time() - start_time os.makedirs(task_dir, exist_ok=True) result_dir = os.path.join( task_dir, 'results.json', ) result_dict = { 'train balanced accuracy': 1 - run_information['train_error'], 'test balanced accuracy': 1 - run_information['test_error'], 'task_id': args.task_id, 'duration': duration, } with open(result_dir, 'w') as file: json.dump(result_dict, file)
en
0.823415
Get the task id list. Goes through the given file and collects all of the task ids. Parameters: ----------- benchmark_task_file: str A string to the path of the benchmark task file. Including the task file name. Returns: -------- benchmark_task_ids - list A list of all the task ids for the benchmark. # the code below drops columns that are # completely null in the train set, however, are not null in the validation # and test set. # trigger data-aware init # calculate the number of early stopping rounds to # be around 10 epochs. Allow incomplete batches. # Flag if early stopping is hit or not # calculate the information below on every epoch # save the model in the end # we will always have a best checkpoint, be it # from early stopping, be it from the normal training. # trigger data-aware init # we will always have a best checkpoint, be it # from early stopping, be it from the normal training. # experiment setup arguments # Start HPO Phase # Start Refit Phase
2.372894
2
ml/learn/metrics/__init__.py
sandbornm/MIMOSA
1
6612677
<filename>ml/learn/metrics/__init__.py import copy import numpy as np from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report, \ multilabel_confusion_matrix, hamming_loss def degree_overfit(train_metrics, val_metrics): """ Degree of overfitting based on mean difference between training and validation metrics """ diffs = 0 for metric, values in train_metrics.items(): t_mean = np.mean(values) v_mean = np.mean(val_metrics[metric]) diffs += abs(t_mean - v_mean) return diffs / len(train_metrics) def hit_rate(y_true, y_pred): """ Computes the hit rate i.e. how many samples are classified to the correct Parameters: y_true = one-hot multilabel ground truths (N, m) y_pred = one-hot class belonging predictions (N, m) Returns: hit rate = hits / # of samples """ hits = 0 for true, pred in zip(y_true, y_pred): # if a single true at positive index passed threshold, then it's a hit # o/w total miss # if there are no positive labels, then automatic hit regardless of classification if not true.any() or pred[true.astype(bool)].any(): hits += 1 return hits / len(y_true) def log_metrics(experiment, train_metrics, val_metrics, train_loss, val_loss, epoch): d_overfit = degree_overfit(train_metrics, val_metrics) experiment.log_metric('Degree overfit', d_overfit, step=epoch) with experiment.train(): experiment.log_metric('Loss', train_loss, step=epoch) for metric, values in train_metrics.items(): experiment.log_metric(metric, np.mean(values), step=epoch) with experiment.validate(): experiment.log_metric('Loss', val_loss, step=epoch) for metric, values in val_metrics.items(): experiment.log_metric(metric, np.mean(values), step=epoch) def log_reports(experiment, train_metrics, val_metrics, train_loss, val_loss, epoch): with experiment.train(): experiment.log_metric('Loss', train_loss, step=epoch) with experiment.validate(): experiment.log_metric('Loss', val_loss, step=epoch) labels = train_metrics.keys() scores = train_metrics[0].keys() for label in labels: for score in scores: with experiment.train(): experiment.log_metric(label + '/' + score, np.mean(train_metrics[label][score]), step=epoch) with experiment.validate(): experiment.log_metric(label + '/' + score, np.mean(val_metrics[label][score]), step=epoch) def merge_metrics(dict_1: dict, dict_2: dict): """ Merge dicts with common keys as list """ dict_3 = {**dict_1, **dict_2} for key, value in dict_3.items(): if key in dict_1 and key in dict_2: dict_3[key] = dict_1[key] + value # since dict_1 val overwritten by above merge return dict_3 def merge_reports(master: dict, report: dict): """ Merge classification reports into a master list """ keys = master.keys() ret = copy.deepcopy(master) for key in keys: scores = report[key] for score, value in scores.items(): ret[key][score] += [value] return ret # generate a classification report def report(pred, target, configs, threshold=0.5): pred = np.array(pred > threshold, dtype=float) return classification_report(target, pred, output_dict=True, target_names=configs, zero_division=1) # Use threshold to define predicted labels and invoke sklearn's metrics with different averaging strategies. def calculate_metrics(pred, target, threshold=0.5): predt = np.array(pred > threshold, dtype=float) return {'micro/precision': [precision_score(y_true=target, y_pred=predt, average='micro', zero_division=1)], 'micro/recall': [recall_score(y_true=target, y_pred=predt, average='micro', zero_division=1)], 'micro/f1': [f1_score(y_true=target, y_pred=predt, average='micro', zero_division=1)], 'macro/precision': [precision_score(y_true=target, y_pred=predt, average='macro', zero_division=1)], 'macro/recall': [recall_score(y_true=target, y_pred=predt, average='macro', zero_division=1)], 'macro/f1': [f1_score(y_true=target, y_pred=predt, average='macro', zero_division=1)], 'samples/precision': [precision_score(y_true=target, y_pred=predt, average='samples', zero_division=1)], 'samples/recall': [recall_score(y_true=target, y_pred=predt, average='samples', zero_division=1)], 'samples/f1': [f1_score(y_true=target, y_pred=predt, average='samples', zero_division=1)], 'accuracy': [accuracy_score(y_true=target, y_pred=predt)], 'hamming': [hamming_loss(y_true=target, y_pred=predt)], 'ranking': [hit_rate(y_true=target, y_pred=predt)], }
<filename>ml/learn/metrics/__init__.py import copy import numpy as np from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report, \ multilabel_confusion_matrix, hamming_loss def degree_overfit(train_metrics, val_metrics): """ Degree of overfitting based on mean difference between training and validation metrics """ diffs = 0 for metric, values in train_metrics.items(): t_mean = np.mean(values) v_mean = np.mean(val_metrics[metric]) diffs += abs(t_mean - v_mean) return diffs / len(train_metrics) def hit_rate(y_true, y_pred): """ Computes the hit rate i.e. how many samples are classified to the correct Parameters: y_true = one-hot multilabel ground truths (N, m) y_pred = one-hot class belonging predictions (N, m) Returns: hit rate = hits / # of samples """ hits = 0 for true, pred in zip(y_true, y_pred): # if a single true at positive index passed threshold, then it's a hit # o/w total miss # if there are no positive labels, then automatic hit regardless of classification if not true.any() or pred[true.astype(bool)].any(): hits += 1 return hits / len(y_true) def log_metrics(experiment, train_metrics, val_metrics, train_loss, val_loss, epoch): d_overfit = degree_overfit(train_metrics, val_metrics) experiment.log_metric('Degree overfit', d_overfit, step=epoch) with experiment.train(): experiment.log_metric('Loss', train_loss, step=epoch) for metric, values in train_metrics.items(): experiment.log_metric(metric, np.mean(values), step=epoch) with experiment.validate(): experiment.log_metric('Loss', val_loss, step=epoch) for metric, values in val_metrics.items(): experiment.log_metric(metric, np.mean(values), step=epoch) def log_reports(experiment, train_metrics, val_metrics, train_loss, val_loss, epoch): with experiment.train(): experiment.log_metric('Loss', train_loss, step=epoch) with experiment.validate(): experiment.log_metric('Loss', val_loss, step=epoch) labels = train_metrics.keys() scores = train_metrics[0].keys() for label in labels: for score in scores: with experiment.train(): experiment.log_metric(label + '/' + score, np.mean(train_metrics[label][score]), step=epoch) with experiment.validate(): experiment.log_metric(label + '/' + score, np.mean(val_metrics[label][score]), step=epoch) def merge_metrics(dict_1: dict, dict_2: dict): """ Merge dicts with common keys as list """ dict_3 = {**dict_1, **dict_2} for key, value in dict_3.items(): if key in dict_1 and key in dict_2: dict_3[key] = dict_1[key] + value # since dict_1 val overwritten by above merge return dict_3 def merge_reports(master: dict, report: dict): """ Merge classification reports into a master list """ keys = master.keys() ret = copy.deepcopy(master) for key in keys: scores = report[key] for score, value in scores.items(): ret[key][score] += [value] return ret # generate a classification report def report(pred, target, configs, threshold=0.5): pred = np.array(pred > threshold, dtype=float) return classification_report(target, pred, output_dict=True, target_names=configs, zero_division=1) # Use threshold to define predicted labels and invoke sklearn's metrics with different averaging strategies. def calculate_metrics(pred, target, threshold=0.5): predt = np.array(pred > threshold, dtype=float) return {'micro/precision': [precision_score(y_true=target, y_pred=predt, average='micro', zero_division=1)], 'micro/recall': [recall_score(y_true=target, y_pred=predt, average='micro', zero_division=1)], 'micro/f1': [f1_score(y_true=target, y_pred=predt, average='micro', zero_division=1)], 'macro/precision': [precision_score(y_true=target, y_pred=predt, average='macro', zero_division=1)], 'macro/recall': [recall_score(y_true=target, y_pred=predt, average='macro', zero_division=1)], 'macro/f1': [f1_score(y_true=target, y_pred=predt, average='macro', zero_division=1)], 'samples/precision': [precision_score(y_true=target, y_pred=predt, average='samples', zero_division=1)], 'samples/recall': [recall_score(y_true=target, y_pred=predt, average='samples', zero_division=1)], 'samples/f1': [f1_score(y_true=target, y_pred=predt, average='samples', zero_division=1)], 'accuracy': [accuracy_score(y_true=target, y_pred=predt)], 'hamming': [hamming_loss(y_true=target, y_pred=predt)], 'ranking': [hit_rate(y_true=target, y_pred=predt)], }
en
0.872283
Degree of overfitting based on mean difference between training and validation metrics Computes the hit rate i.e. how many samples are classified to the correct Parameters: y_true = one-hot multilabel ground truths (N, m) y_pred = one-hot class belonging predictions (N, m) Returns: hit rate = hits / # of samples # if a single true at positive index passed threshold, then it's a hit # o/w total miss # if there are no positive labels, then automatic hit regardless of classification Merge dicts with common keys as list # since dict_1 val overwritten by above merge Merge classification reports into a master list # generate a classification report # Use threshold to define predicted labels and invoke sklearn's metrics with different averaging strategies.
3.129228
3
cli/bin/csv2_metadata.py
hep-gc/cloud-scheduler-2
3
6612678
from csv2_common import check_keys, qc, requests, show_active_user_groups, show_table from subprocess import Popen, PIPE from getpass import getuser from shutil import rmtree from tempfile import mkdtemp import filecmp import json import os import yaml from csv2_common import yaml_full_load from csv2_group import defaults, metadata_delete, metadata_edit, metadata_list, metadata_load, metadata_update KEY_MAP = { '-g': 'group', } COMMAS_TO_NL = str.maketrans(',','\n') def _conditionally_restore_a_file(gvar, path, metadata): """ Compare the metadata on the server with its' backup and if they differ, ask the user whether they want to restore the backup. """ if metadata and path in gvar['backup_path_list']: del gvar['backup_path_list'][path] path_dir = os.path.dirname(path) if path[:-1] == path_dir: print('Skipping metadata file with no name, path="%s"' % path) return work_path = '%s/work%s' % (gvar['temp_dir'], path) work_dir = os.path.dirname(work_path) if not os.path.exists(work_dir): os.makedirs(work_dir) fd = open(work_path, 'w') if metadata: fd.write(json.dumps(metadata)) fd.close() if 'backup-key' in gvar['user_settings']: compare_path = '%s/compare%s' % (gvar['temp_dir'], path) compare_dir = os.path.dirname(compare_path) if not os.path.exists(compare_dir): os.makedirs(compare_dir) restore_path = compare_path p = Popen( [ 'ansible-vault', 'decrypt', path, '--output', restore_path, '--vault-password-file', gvar['user_settings']['backup-key'] ], stdout=PIPE, stderr=PIPE ) stdout, stderr = p.communicate() if p.returncode != 0: raise Exception('Error: ansible-vault decrypt: stdout=%s, stderr=%s' % (stdout, stderr)) else: restore_path = path if not metadata or not filecmp.cmp(work_path, restore_path, shallow=False): while(True): if metadata: rsp = input('Backup up differs from server metadata, path=%s. Do you want to restore the backup? (yes, no (default), show, or quit):' % path) else: rsp = input('File missing from server, backup file path=%s. Do you want to restore the backup? (yes, no (default), show, or quit):' % path) if rsp == '' or 'no'[:len(rsp)] == rsp.lower(): break elif 'yes'[:len(rsp)] == rsp.lower(): words = restore_path.split('/') ix = words.index('groups') response = requests(gvar, '/settings/prepare/', {'group': words[ix+1]}) fd = open(restore_path) restore_data = qc(json.loads(fd.read()), columns=['group_name'], option='prune') fd.close() if len(words) == ix+3: response = requests(gvar, '/group/defaults/', _get_restore_data(gvar, restore_path, other_prune_columns=['job_scratch'])) elif len(words) == ix+4: response = requests(gvar, '/group/metadata-update/', _get_restore_data(gvar, restore_path)) elif len(words) == ix+5: response = requests(gvar, '/cloud/update/', _get_restore_data(gvar, restore_path)) elif len(words) == ix+6: response = requests(gvar, '/cloud/metadata-update/', _get_restore_data(gvar, restore_path)) if response['response_code'] == 0: print('Successfully restored.') else: raise Exception('Metadata restoration failed, msg=%s' % response['message']) break elif 'quit'[:len(rsp)] == rsp.lower(): exit(0) elif 'show'[:len(rsp)] == rsp.lower(): expanded_work_path = _expand(gvar, work_path) expanded_restore_path = _expand(gvar, restore_path) print('< server (%s), > backup' % gvar['pid_defaults']['server']) p = Popen( [ 'diff', '-y', expanded_work_path, expanded_restore_path ] ) p.communicate() else: print('Invalid response "%s".' % rsp) def _create_backup_file(gvar, path, metadata): """ Open the backup file (for writing), making the directory if necessary, and return the file descriptor. """ path_dir = os.path.dirname(path) if path[:-1] == path_dir: print('Skipping metadata file with no name, path="%s"' % path) return if not os.path.exists(path_dir): os.makedirs(path_dir) if gvar['temp_dir'] and os.path.exists(path): compare_path = '%s/compare%s' % (gvar['temp_dir'], path) compare_dir = os.path.dirname(compare_path) if not os.path.exists(compare_dir): os.makedirs(compare_dir) work_path = '%s/work%s' % (gvar['temp_dir'], path) work_dir = os.path.dirname(work_path) if not os.path.exists(work_dir): os.makedirs(work_dir) p = Popen( [ 'ansible-vault', 'decrypt', path, '--output', compare_path, '--vault-password-file', gvar['user_settings']['backup-key'] ], stdout=PIPE, stderr=PIPE ) stdout, stderr = p.communicate() if p.returncode != 0: raise Exception('Error: ansible-vault decrypt: stdout=%s, stderr=%s' % (stdout, stderr)) fd = open(work_path, 'w') fd.write(json.dumps(metadata)) fd.close() if not filecmp.cmp(work_path, compare_path, shallow=False): print('Updating backup for %s' % path) p = Popen( [ 'ansible-vault', 'encrypt', work_path, '--output', path, '--vault-password-file', gvar['user_settings']['backup-key'] ], stdout=PIPE, stderr=PIPE ) stdout, stderr = p.communicate() if p.returncode != 0: raise Exception('Error: ansible-vault encrypt: stdout=%s, stderr=%s' % (stdout, stderr)) else: fd = open(path, 'w') fd.write(json.dumps(metadata)) fd.close() if 'backup-key' in gvar['user_settings']: p = Popen( [ 'ansible-vault', 'encrypt', path, '--vault-password-file', gvar['user_settings']['backup-key'] ], stdout=PIPE, stderr=PIPE ) stdout, stderr = p.communicate() def _expand(gvar, meta_path): """ Expand the json file to make a readable diff. """ expanded_meta_path = '%s-expanded' % meta_path fd = open(meta_path) metadata = json.loads(fd.read()) fd.close() fd = open(expanded_meta_path, 'w') if metadata : for column in metadata: if column == 'metadata': fd.write('%-16s:\n' % column) lines = metadata[column].replace('\r\n', '\n').split('\n') count = 0 for line in lines: count += 1 fd.write(' %04d %s:\n' % (count, line)) else: fd.write('%-16s: %s\n' % (column, metadata[column])) fd.close() return expanded_meta_path def _get_backup_path_list(gvar, dir_path): """ Scan the backup repository saving a list of all file paths. """ for item in os.listdir(dir_path): current_path = '%s/%s' % (dir_path, item) if os.path.isdir(current_path) and item[0] != '.': _get_backup_path_list(gvar, current_path) elif os.path.isfile(current_path) and item [0] != '.': gvar['backup_path_list'][current_path] = True def _get_cloud_settings(query_list): """ Remove superfluous columns from the cloud query_list. """ return qc(query_list, [ 'group_name', 'cloud_name', 'enabled', 'spot_price', 'vm_flavor', 'vm_image', 'vm_keep_alive', 'vm_keyname', 'vm_network', 'authurl', 'project_domain_name', 'project', 'user_domain_name', 'username', 'cacertificate', 'region', 'cloud_type', 'cores_ctl' ], option='keep' ) def _get_repository_and_servers(gvar): """ Backup all user data for all groups/clouds for each server configured in the user defaults. """ # Retrieve default backup repository. if os.path.isfile('%s/.csv2/backup_repository' % gvar['home_dir']): fd = open('%s/.csv2/backup_repository' % gvar['home_dir']) backup_repository = fd.read() fd.close else: backup_repository = None if 'backup-repository' in gvar['user_settings']: if gvar['user_settings']['backup-repository'] == '': print('Error: path specified for backup repository cannot be null.') exit(1) else: gvar['user_settings']['backup-repository'] = os.path.abspath(gvar['user_settings']['backup-repository']) if not os.path.isdir(gvar['user_settings']['backup-repository']): print('Error: path specified for backup repository "%s" is not a directory or does not exist.' % gvar['user_settings']['backup-repository']) exit(1) if gvar['user_settings']['backup-repository'] != backup_repository: fd = open('%s/.csv2/backup_repository' % gvar['home_dir'], 'w') fd.write(gvar['user_settings']['backup-repository']) fd.close os.chmod('%s/.csv2/backup_repository' % gvar['home_dir'], 0o600) elif backup_repository: gvar['user_settings']['backup-repository'] = backup_repository # Retrieve default backup key - no key, no encryption. if os.path.isfile('%s/.csv2/backup_key' % gvar['home_dir']): fd = open('%s/.csv2/backup_key' % gvar['home_dir']) backup_key = fd.read() fd.close else: backup_key = None if 'backup-key' in gvar['user_settings']: if gvar['user_settings']['backup-key'] == '': os.remove('%s/.csv2/backup_key' % gvar['home_dir']) del gvar['user_settings']['backup-key'] else: gvar['user_settings']['backup-key'] = os.path.abspath(gvar['user_settings']['backup-key']) if not os.path.isfile(gvar['user_settings']['backup-key']): print('Error: path specified for backup key "%s" is not a file or does not exist.' % gvar['user_settings']['backup-key']) exit(1) if gvar['user_settings']['backup-key'] != backup_key: fd = open('%s/.csv2/backup_key' % gvar['home_dir'], 'w') fd.write(gvar['user_settings']['backup-key']) fd.close os.chmod('%s/.csv2/backup_key' % gvar['home_dir'], 0o600) elif backup_key: gvar['user_settings']['backup-key'] = backup_key servers = {} server_xref = {} for host_dir in os.listdir('%s/.csv2' % gvar['home_dir']): if not os.path.isdir('%s/.csv2/%s' % (gvar['home_dir'], host_dir)) or host_dir[0] == '.': continue _fd = open('%s/.csv2/%s/settings.yaml' % (gvar['home_dir'], host_dir)) servers[host_dir] = yaml_full_load(_fd) _fd.close() if 'server-address' in servers[host_dir]: server_xref[servers[host_dir]['server-address'][8:]] = host_dir return servers, server_xref def _get_restore_data(gvar, restore_path, other_prune_columns=[]): """ Return the backup data to be resored minus the group_name. """ fd = open(restore_path) restore_data = qc(json.loads(fd.read()), columns=['group_name'] + other_prune_columns, option='prune') fd.close() return restore_data def _set_host(gvar, servers, server): """ Set the address and credentials for the specified cloudscheduler server. """ try: gvar['user_settings']['server-address'] = servers['settings'][server]['server-address'] del gvar['user_settings']['server-user'] del gvar['user_settings']['server-password'] except: pass if 'server-user' in gvar['user_settings']: gvar['user_settings']['server-user'] = servers['settings'][server]['server-user'] if 'server-password' not in gvar['user_settings'] or gvar['user_settings']['server-password'] == '?': gvar['user_settings']['server-password'] = getpass('Enter your %s password for server "%s": ' % (gvar['command_name'], gvar['pid_defaults']['server'])) else: gvar['user_settings']['server-password'] = servers['settings'][server]['server-password'] if 'server-address' in servers['settings'][server]: gvar['pid_defaults']['server'] = server return servers['settings'][server]['server-address'][8:], '%s/%s' % (gvar['user_settings']['backup-repository'], servers['settings'][server]['server-address'][8:]) else: gvar['pid_defaults']['server'] = None return None, None def _update_git(gvar, msg): """ Add untracked items and commit all updates. """ # If the backup directory is a git repository, update git. if os.path.exists('%s/.git' % gvar['user_settings']['backup-repository']): p = Popen( [ 'git', 'status', '-s' ], cwd=gvar['user_settings']['backup-repository'], stdout=PIPE, stderr=PIPE ) stdout, stderr = p.communicate() if p.returncode != 0: raise Exception('Error: git status: stdout=%s, stderr=%s' % (stdout, stderr)) # Process untracked files. count = 0 lines = stdout.decode("utf-8").split('\n') for line in lines: if line[:3] == ' A ' or line[:3] == ' M ': count += 1 if line[:3] == '?? ': count += 1 p = Popen( [ 'git', 'add', line[3:] ], cwd=gvar['user_settings']['backup-repository'], stdout=PIPE, stderr=PIPE ) stdout, stderr = p.communicate() if p.returncode != 0: raise Exception('Error: git add: stdout=%s, stderr=%s' % (stdout, stderr)) if count > 0: p = Popen( [ 'git', 'commit', '-am', '%s commit by %s' % (msg, getuser()) ], cwd=gvar['user_settings']['backup-repository'], stdout=PIPE, stderr=PIPE ) stdout, stderr = p.communicate() if p.returncode != 0: raise Exception('Error: git commit: stdout=%s, stderr=%s' % (stdout, stderr)) def backup(gvar): """ Backup all user data for all groups/clouds for each server configured in the user defaults. """ mandatory = [] required = ['-br'] optional = ['-bk', '-v', '-x509', '-xA'] servers = {} if gvar['retrieve_options']: return mandatory + required + optional # Retrieve the backup repository and all server information. servers['settings'], servers['xref'] = _get_repository_and_servers(gvar) # Check for missing arguments or help required. check_keys( gvar, mandatory, required, optional) # If the backup directory is an encrypted git repository, create a working temorary directory. _update_git(gvar, 'pre-backup') # If the backup directory is an encrypted git repository, create a working temorary directory. if 'backup-key' in gvar['user_settings'] and os.path.exists('%s/.git' % gvar['user_settings']['backup-repository']): gvar['temp_dir'] = mkdtemp() else: gvar['temp_dir'] = None # Retrieve data to backup for each cloudscheduler server. fetched = {} for server in sorted(servers['settings']): host, host_dir = _set_host(gvar, servers, server) if not host: print('Skipping server="%s", no server address.' % server) continue if host not in fetched: fetched[host] = {} # Save the initital server group so it can be restored later. response = requests(gvar, '/settings/prepare/') servers['initial_server_group'] = gvar['active_group'] groups = gvar['user_groups'] for group in sorted(groups): if group in fetched[host]: continue fetched[host][group] = True # Switch groups. response = requests(gvar, '/settings/prepare/', {'group': group}) print('Fetching: server=%s, group=%s' % (server, group)) response = requests(gvar, '/group/defaults/') _create_backup_file(gvar, '%s/groups/%s/defaults' % (host_dir, response['defaults_list'][0]['group_name']), response['defaults_list'][0]) response = requests(gvar, '/group/metadata-list/') for metadata in response['group_metadata_list']: _create_backup_file(gvar, '%s/groups/%s/metadata/%s' % (host_dir, metadata['group_name'], metadata['metadata_name']), metadata) response = requests(gvar, '/cloud/list/') for cloud in response['cloud_list']: _create_backup_file(gvar, '%s/groups/%s/clouds/%s/settings' % (host_dir, cloud['group_name'], cloud['cloud_name']), _get_cloud_settings(cloud)) response = requests(gvar, '/cloud/metadata-list/') for metadata in response['cloud_metadata_list']: _create_backup_file(gvar, '%s/groups/%s/clouds/%s/metadata/%s' % (host_dir, metadata['group_name'], metadata['cloud_name'], metadata['metadata_name']), metadata) # Restore the server's initial group. response = requests(gvar, '/settings/prepare?%s' % servers['initial_server_group']) _update_git(gvar, 'post-backup') if gvar['temp_dir']: rmtree(gvar['temp_dir']) def delete(gvar): return metadata_delete(gvar) def edit(gvar): return metadata_edit(gvar) def group(gvar): return defaults(gvar) def list(gvar): return metadata_list(gvar) def load(gvar): return metadata_load(gvar) def restore(gvar): """ Restore user data. """ mandatory = [] required = ['-br'] optional = ['-bk', '-v', '-x509', '-xA'] servers = {} if gvar['retrieve_options']: return mandatory + required + optional # Retrieve the backup repository and all server information. servers['settings'], servers['xref'] = _get_repository_and_servers(gvar) # Check for missing arguments or help required. check_keys( gvar, mandatory, required, optional) # Commit any outstanding repository updates prior to the restore. _update_git(gvar, 'pre-restore') # Retrieve an inventory of the current backup files. gvar['backup_path_list'] = {} _get_backup_path_list(gvar, gvar['user_settings']['backup-repository']) # We need a temporary working directory. gvar['temp_dir'] = mkdtemp() # Retrieve data from each cloudscheduler server to compare with its' backup. If the # backup is different, conditionally (allow the user to choose) restore it. fetched = {} host_group_xref = {} for server in sorted(servers['settings']): host, host_dir = _set_host(gvar, servers, server) if not host: print('Skipping server="%s", no server address.' % server) continue if host not in fetched: fetched[host] = {} # Save the initital server group so it can be restored later. response = requests(gvar, '/settings/prepare/') servers['initial_server_group'] = gvar['active_group'] groups = gvar['user_groups'] for group in sorted(groups): if group in fetched[host]: continue fetched[host][group] = True host_group_xref['%s::%s' % (host, group)] = server # Switch groups. response = requests(gvar, '/settings/prepare/', {'group': group}) print('Checking: server=%s, group=%s' % (server, group)) response = requests(gvar, '/group/defaults/') _conditionally_restore_a_file(gvar, '%s/groups/%s/defaults' % (host_dir, response['defaults_list'][0]['group_name']), response['defaults_list'][0]) response = requests(gvar, '/group/metadata-list/') for metadata in response['group_metadata_list']: _conditionally_restore_a_file(gvar, '%s/groups/%s/metadata/%s' % (host_dir, metadata['group_name'], metadata['metadata_name']), metadata) response = requests(gvar, '/cloud/list/') for cloud in response['cloud_list']: _conditionally_restore_a_file(gvar, '%s/groups/%s/clouds/%s/settings' % (host_dir, cloud['group_name'], cloud['cloud_name']), _get_cloud_settings(cloud)) response = requests(gvar, '/cloud/metadata-list/') for metadata in response['cloud_metadata_list']: _conditionally_restore_a_file(gvar, '%s/groups/%s/clouds/%s/metadata/%s' % (host_dir, metadata['group_name'], metadata['cloud_name'], metadata['metadata_name']), metadata) # Restore the server's initial group. response = requests(gvar, '/settings/prepare?%s' % servers['initial_server_group']) # Scan remaining backup files building an inventory to restore. remaining_inventory = {} for path in sorted(gvar['backup_path_list']): words = path.split('/') ix = words.index('groups') host = words[ix-1] group = words[ix+1] xref_key = '%s::%s' % (host, group) if xref_key in gvar['host_group_xref']: server = host_group_xref[xref_key] if server not in remaining_inventory: remaining_inventory[server] = {} if group not in remaining_inventory[server]: remaining_inventory[server][group] = [] remaining_inventory[server][group].append(path) else: print('Skipping backup file "%s", you have no access to the server.') continue # Perform remaining conditional restores. for server in sorted(remaining_inventory): host, host_dir = _set_host(gvar, servers, server) # Save the initital server group so it can be restored later. response = requests(gvar, '/settings/prepare/') servers['initial_server_group'] = gvar['active_group'] for group in sorted(remaining_inventory[server]): print('Processing missing files: server=%s, group=%s' % (server, group)) # Switch groups. response = requests(gvar, '/settings/prepare/', {'group': group}) for path in remaining_inventory[server][group]: _conditionally_restore_a_file(gvar, path, None) # Restore the server's initial group. response = requests(gvar, '/settings/prepare?%s' % servers['initial_server_group']) _update_git(gvar, 'post-restore') rmtree(gvar['temp_dir']) def update(gvar): return metadata_update(gvar)
from csv2_common import check_keys, qc, requests, show_active_user_groups, show_table from subprocess import Popen, PIPE from getpass import getuser from shutil import rmtree from tempfile import mkdtemp import filecmp import json import os import yaml from csv2_common import yaml_full_load from csv2_group import defaults, metadata_delete, metadata_edit, metadata_list, metadata_load, metadata_update KEY_MAP = { '-g': 'group', } COMMAS_TO_NL = str.maketrans(',','\n') def _conditionally_restore_a_file(gvar, path, metadata): """ Compare the metadata on the server with its' backup and if they differ, ask the user whether they want to restore the backup. """ if metadata and path in gvar['backup_path_list']: del gvar['backup_path_list'][path] path_dir = os.path.dirname(path) if path[:-1] == path_dir: print('Skipping metadata file with no name, path="%s"' % path) return work_path = '%s/work%s' % (gvar['temp_dir'], path) work_dir = os.path.dirname(work_path) if not os.path.exists(work_dir): os.makedirs(work_dir) fd = open(work_path, 'w') if metadata: fd.write(json.dumps(metadata)) fd.close() if 'backup-key' in gvar['user_settings']: compare_path = '%s/compare%s' % (gvar['temp_dir'], path) compare_dir = os.path.dirname(compare_path) if not os.path.exists(compare_dir): os.makedirs(compare_dir) restore_path = compare_path p = Popen( [ 'ansible-vault', 'decrypt', path, '--output', restore_path, '--vault-password-file', gvar['user_settings']['backup-key'] ], stdout=PIPE, stderr=PIPE ) stdout, stderr = p.communicate() if p.returncode != 0: raise Exception('Error: ansible-vault decrypt: stdout=%s, stderr=%s' % (stdout, stderr)) else: restore_path = path if not metadata or not filecmp.cmp(work_path, restore_path, shallow=False): while(True): if metadata: rsp = input('Backup up differs from server metadata, path=%s. Do you want to restore the backup? (yes, no (default), show, or quit):' % path) else: rsp = input('File missing from server, backup file path=%s. Do you want to restore the backup? (yes, no (default), show, or quit):' % path) if rsp == '' or 'no'[:len(rsp)] == rsp.lower(): break elif 'yes'[:len(rsp)] == rsp.lower(): words = restore_path.split('/') ix = words.index('groups') response = requests(gvar, '/settings/prepare/', {'group': words[ix+1]}) fd = open(restore_path) restore_data = qc(json.loads(fd.read()), columns=['group_name'], option='prune') fd.close() if len(words) == ix+3: response = requests(gvar, '/group/defaults/', _get_restore_data(gvar, restore_path, other_prune_columns=['job_scratch'])) elif len(words) == ix+4: response = requests(gvar, '/group/metadata-update/', _get_restore_data(gvar, restore_path)) elif len(words) == ix+5: response = requests(gvar, '/cloud/update/', _get_restore_data(gvar, restore_path)) elif len(words) == ix+6: response = requests(gvar, '/cloud/metadata-update/', _get_restore_data(gvar, restore_path)) if response['response_code'] == 0: print('Successfully restored.') else: raise Exception('Metadata restoration failed, msg=%s' % response['message']) break elif 'quit'[:len(rsp)] == rsp.lower(): exit(0) elif 'show'[:len(rsp)] == rsp.lower(): expanded_work_path = _expand(gvar, work_path) expanded_restore_path = _expand(gvar, restore_path) print('< server (%s), > backup' % gvar['pid_defaults']['server']) p = Popen( [ 'diff', '-y', expanded_work_path, expanded_restore_path ] ) p.communicate() else: print('Invalid response "%s".' % rsp) def _create_backup_file(gvar, path, metadata): """ Open the backup file (for writing), making the directory if necessary, and return the file descriptor. """ path_dir = os.path.dirname(path) if path[:-1] == path_dir: print('Skipping metadata file with no name, path="%s"' % path) return if not os.path.exists(path_dir): os.makedirs(path_dir) if gvar['temp_dir'] and os.path.exists(path): compare_path = '%s/compare%s' % (gvar['temp_dir'], path) compare_dir = os.path.dirname(compare_path) if not os.path.exists(compare_dir): os.makedirs(compare_dir) work_path = '%s/work%s' % (gvar['temp_dir'], path) work_dir = os.path.dirname(work_path) if not os.path.exists(work_dir): os.makedirs(work_dir) p = Popen( [ 'ansible-vault', 'decrypt', path, '--output', compare_path, '--vault-password-file', gvar['user_settings']['backup-key'] ], stdout=PIPE, stderr=PIPE ) stdout, stderr = p.communicate() if p.returncode != 0: raise Exception('Error: ansible-vault decrypt: stdout=%s, stderr=%s' % (stdout, stderr)) fd = open(work_path, 'w') fd.write(json.dumps(metadata)) fd.close() if not filecmp.cmp(work_path, compare_path, shallow=False): print('Updating backup for %s' % path) p = Popen( [ 'ansible-vault', 'encrypt', work_path, '--output', path, '--vault-password-file', gvar['user_settings']['backup-key'] ], stdout=PIPE, stderr=PIPE ) stdout, stderr = p.communicate() if p.returncode != 0: raise Exception('Error: ansible-vault encrypt: stdout=%s, stderr=%s' % (stdout, stderr)) else: fd = open(path, 'w') fd.write(json.dumps(metadata)) fd.close() if 'backup-key' in gvar['user_settings']: p = Popen( [ 'ansible-vault', 'encrypt', path, '--vault-password-file', gvar['user_settings']['backup-key'] ], stdout=PIPE, stderr=PIPE ) stdout, stderr = p.communicate() def _expand(gvar, meta_path): """ Expand the json file to make a readable diff. """ expanded_meta_path = '%s-expanded' % meta_path fd = open(meta_path) metadata = json.loads(fd.read()) fd.close() fd = open(expanded_meta_path, 'w') if metadata : for column in metadata: if column == 'metadata': fd.write('%-16s:\n' % column) lines = metadata[column].replace('\r\n', '\n').split('\n') count = 0 for line in lines: count += 1 fd.write(' %04d %s:\n' % (count, line)) else: fd.write('%-16s: %s\n' % (column, metadata[column])) fd.close() return expanded_meta_path def _get_backup_path_list(gvar, dir_path): """ Scan the backup repository saving a list of all file paths. """ for item in os.listdir(dir_path): current_path = '%s/%s' % (dir_path, item) if os.path.isdir(current_path) and item[0] != '.': _get_backup_path_list(gvar, current_path) elif os.path.isfile(current_path) and item [0] != '.': gvar['backup_path_list'][current_path] = True def _get_cloud_settings(query_list): """ Remove superfluous columns from the cloud query_list. """ return qc(query_list, [ 'group_name', 'cloud_name', 'enabled', 'spot_price', 'vm_flavor', 'vm_image', 'vm_keep_alive', 'vm_keyname', 'vm_network', 'authurl', 'project_domain_name', 'project', 'user_domain_name', 'username', 'cacertificate', 'region', 'cloud_type', 'cores_ctl' ], option='keep' ) def _get_repository_and_servers(gvar): """ Backup all user data for all groups/clouds for each server configured in the user defaults. """ # Retrieve default backup repository. if os.path.isfile('%s/.csv2/backup_repository' % gvar['home_dir']): fd = open('%s/.csv2/backup_repository' % gvar['home_dir']) backup_repository = fd.read() fd.close else: backup_repository = None if 'backup-repository' in gvar['user_settings']: if gvar['user_settings']['backup-repository'] == '': print('Error: path specified for backup repository cannot be null.') exit(1) else: gvar['user_settings']['backup-repository'] = os.path.abspath(gvar['user_settings']['backup-repository']) if not os.path.isdir(gvar['user_settings']['backup-repository']): print('Error: path specified for backup repository "%s" is not a directory or does not exist.' % gvar['user_settings']['backup-repository']) exit(1) if gvar['user_settings']['backup-repository'] != backup_repository: fd = open('%s/.csv2/backup_repository' % gvar['home_dir'], 'w') fd.write(gvar['user_settings']['backup-repository']) fd.close os.chmod('%s/.csv2/backup_repository' % gvar['home_dir'], 0o600) elif backup_repository: gvar['user_settings']['backup-repository'] = backup_repository # Retrieve default backup key - no key, no encryption. if os.path.isfile('%s/.csv2/backup_key' % gvar['home_dir']): fd = open('%s/.csv2/backup_key' % gvar['home_dir']) backup_key = fd.read() fd.close else: backup_key = None if 'backup-key' in gvar['user_settings']: if gvar['user_settings']['backup-key'] == '': os.remove('%s/.csv2/backup_key' % gvar['home_dir']) del gvar['user_settings']['backup-key'] else: gvar['user_settings']['backup-key'] = os.path.abspath(gvar['user_settings']['backup-key']) if not os.path.isfile(gvar['user_settings']['backup-key']): print('Error: path specified for backup key "%s" is not a file or does not exist.' % gvar['user_settings']['backup-key']) exit(1) if gvar['user_settings']['backup-key'] != backup_key: fd = open('%s/.csv2/backup_key' % gvar['home_dir'], 'w') fd.write(gvar['user_settings']['backup-key']) fd.close os.chmod('%s/.csv2/backup_key' % gvar['home_dir'], 0o600) elif backup_key: gvar['user_settings']['backup-key'] = backup_key servers = {} server_xref = {} for host_dir in os.listdir('%s/.csv2' % gvar['home_dir']): if not os.path.isdir('%s/.csv2/%s' % (gvar['home_dir'], host_dir)) or host_dir[0] == '.': continue _fd = open('%s/.csv2/%s/settings.yaml' % (gvar['home_dir'], host_dir)) servers[host_dir] = yaml_full_load(_fd) _fd.close() if 'server-address' in servers[host_dir]: server_xref[servers[host_dir]['server-address'][8:]] = host_dir return servers, server_xref def _get_restore_data(gvar, restore_path, other_prune_columns=[]): """ Return the backup data to be resored minus the group_name. """ fd = open(restore_path) restore_data = qc(json.loads(fd.read()), columns=['group_name'] + other_prune_columns, option='prune') fd.close() return restore_data def _set_host(gvar, servers, server): """ Set the address and credentials for the specified cloudscheduler server. """ try: gvar['user_settings']['server-address'] = servers['settings'][server]['server-address'] del gvar['user_settings']['server-user'] del gvar['user_settings']['server-password'] except: pass if 'server-user' in gvar['user_settings']: gvar['user_settings']['server-user'] = servers['settings'][server]['server-user'] if 'server-password' not in gvar['user_settings'] or gvar['user_settings']['server-password'] == '?': gvar['user_settings']['server-password'] = getpass('Enter your %s password for server "%s": ' % (gvar['command_name'], gvar['pid_defaults']['server'])) else: gvar['user_settings']['server-password'] = servers['settings'][server]['server-password'] if 'server-address' in servers['settings'][server]: gvar['pid_defaults']['server'] = server return servers['settings'][server]['server-address'][8:], '%s/%s' % (gvar['user_settings']['backup-repository'], servers['settings'][server]['server-address'][8:]) else: gvar['pid_defaults']['server'] = None return None, None def _update_git(gvar, msg): """ Add untracked items and commit all updates. """ # If the backup directory is a git repository, update git. if os.path.exists('%s/.git' % gvar['user_settings']['backup-repository']): p = Popen( [ 'git', 'status', '-s' ], cwd=gvar['user_settings']['backup-repository'], stdout=PIPE, stderr=PIPE ) stdout, stderr = p.communicate() if p.returncode != 0: raise Exception('Error: git status: stdout=%s, stderr=%s' % (stdout, stderr)) # Process untracked files. count = 0 lines = stdout.decode("utf-8").split('\n') for line in lines: if line[:3] == ' A ' or line[:3] == ' M ': count += 1 if line[:3] == '?? ': count += 1 p = Popen( [ 'git', 'add', line[3:] ], cwd=gvar['user_settings']['backup-repository'], stdout=PIPE, stderr=PIPE ) stdout, stderr = p.communicate() if p.returncode != 0: raise Exception('Error: git add: stdout=%s, stderr=%s' % (stdout, stderr)) if count > 0: p = Popen( [ 'git', 'commit', '-am', '%s commit by %s' % (msg, getuser()) ], cwd=gvar['user_settings']['backup-repository'], stdout=PIPE, stderr=PIPE ) stdout, stderr = p.communicate() if p.returncode != 0: raise Exception('Error: git commit: stdout=%s, stderr=%s' % (stdout, stderr)) def backup(gvar): """ Backup all user data for all groups/clouds for each server configured in the user defaults. """ mandatory = [] required = ['-br'] optional = ['-bk', '-v', '-x509', '-xA'] servers = {} if gvar['retrieve_options']: return mandatory + required + optional # Retrieve the backup repository and all server information. servers['settings'], servers['xref'] = _get_repository_and_servers(gvar) # Check for missing arguments or help required. check_keys( gvar, mandatory, required, optional) # If the backup directory is an encrypted git repository, create a working temorary directory. _update_git(gvar, 'pre-backup') # If the backup directory is an encrypted git repository, create a working temorary directory. if 'backup-key' in gvar['user_settings'] and os.path.exists('%s/.git' % gvar['user_settings']['backup-repository']): gvar['temp_dir'] = mkdtemp() else: gvar['temp_dir'] = None # Retrieve data to backup for each cloudscheduler server. fetched = {} for server in sorted(servers['settings']): host, host_dir = _set_host(gvar, servers, server) if not host: print('Skipping server="%s", no server address.' % server) continue if host not in fetched: fetched[host] = {} # Save the initital server group so it can be restored later. response = requests(gvar, '/settings/prepare/') servers['initial_server_group'] = gvar['active_group'] groups = gvar['user_groups'] for group in sorted(groups): if group in fetched[host]: continue fetched[host][group] = True # Switch groups. response = requests(gvar, '/settings/prepare/', {'group': group}) print('Fetching: server=%s, group=%s' % (server, group)) response = requests(gvar, '/group/defaults/') _create_backup_file(gvar, '%s/groups/%s/defaults' % (host_dir, response['defaults_list'][0]['group_name']), response['defaults_list'][0]) response = requests(gvar, '/group/metadata-list/') for metadata in response['group_metadata_list']: _create_backup_file(gvar, '%s/groups/%s/metadata/%s' % (host_dir, metadata['group_name'], metadata['metadata_name']), metadata) response = requests(gvar, '/cloud/list/') for cloud in response['cloud_list']: _create_backup_file(gvar, '%s/groups/%s/clouds/%s/settings' % (host_dir, cloud['group_name'], cloud['cloud_name']), _get_cloud_settings(cloud)) response = requests(gvar, '/cloud/metadata-list/') for metadata in response['cloud_metadata_list']: _create_backup_file(gvar, '%s/groups/%s/clouds/%s/metadata/%s' % (host_dir, metadata['group_name'], metadata['cloud_name'], metadata['metadata_name']), metadata) # Restore the server's initial group. response = requests(gvar, '/settings/prepare?%s' % servers['initial_server_group']) _update_git(gvar, 'post-backup') if gvar['temp_dir']: rmtree(gvar['temp_dir']) def delete(gvar): return metadata_delete(gvar) def edit(gvar): return metadata_edit(gvar) def group(gvar): return defaults(gvar) def list(gvar): return metadata_list(gvar) def load(gvar): return metadata_load(gvar) def restore(gvar): """ Restore user data. """ mandatory = [] required = ['-br'] optional = ['-bk', '-v', '-x509', '-xA'] servers = {} if gvar['retrieve_options']: return mandatory + required + optional # Retrieve the backup repository and all server information. servers['settings'], servers['xref'] = _get_repository_and_servers(gvar) # Check for missing arguments or help required. check_keys( gvar, mandatory, required, optional) # Commit any outstanding repository updates prior to the restore. _update_git(gvar, 'pre-restore') # Retrieve an inventory of the current backup files. gvar['backup_path_list'] = {} _get_backup_path_list(gvar, gvar['user_settings']['backup-repository']) # We need a temporary working directory. gvar['temp_dir'] = mkdtemp() # Retrieve data from each cloudscheduler server to compare with its' backup. If the # backup is different, conditionally (allow the user to choose) restore it. fetched = {} host_group_xref = {} for server in sorted(servers['settings']): host, host_dir = _set_host(gvar, servers, server) if not host: print('Skipping server="%s", no server address.' % server) continue if host not in fetched: fetched[host] = {} # Save the initital server group so it can be restored later. response = requests(gvar, '/settings/prepare/') servers['initial_server_group'] = gvar['active_group'] groups = gvar['user_groups'] for group in sorted(groups): if group in fetched[host]: continue fetched[host][group] = True host_group_xref['%s::%s' % (host, group)] = server # Switch groups. response = requests(gvar, '/settings/prepare/', {'group': group}) print('Checking: server=%s, group=%s' % (server, group)) response = requests(gvar, '/group/defaults/') _conditionally_restore_a_file(gvar, '%s/groups/%s/defaults' % (host_dir, response['defaults_list'][0]['group_name']), response['defaults_list'][0]) response = requests(gvar, '/group/metadata-list/') for metadata in response['group_metadata_list']: _conditionally_restore_a_file(gvar, '%s/groups/%s/metadata/%s' % (host_dir, metadata['group_name'], metadata['metadata_name']), metadata) response = requests(gvar, '/cloud/list/') for cloud in response['cloud_list']: _conditionally_restore_a_file(gvar, '%s/groups/%s/clouds/%s/settings' % (host_dir, cloud['group_name'], cloud['cloud_name']), _get_cloud_settings(cloud)) response = requests(gvar, '/cloud/metadata-list/') for metadata in response['cloud_metadata_list']: _conditionally_restore_a_file(gvar, '%s/groups/%s/clouds/%s/metadata/%s' % (host_dir, metadata['group_name'], metadata['cloud_name'], metadata['metadata_name']), metadata) # Restore the server's initial group. response = requests(gvar, '/settings/prepare?%s' % servers['initial_server_group']) # Scan remaining backup files building an inventory to restore. remaining_inventory = {} for path in sorted(gvar['backup_path_list']): words = path.split('/') ix = words.index('groups') host = words[ix-1] group = words[ix+1] xref_key = '%s::%s' % (host, group) if xref_key in gvar['host_group_xref']: server = host_group_xref[xref_key] if server not in remaining_inventory: remaining_inventory[server] = {} if group not in remaining_inventory[server]: remaining_inventory[server][group] = [] remaining_inventory[server][group].append(path) else: print('Skipping backup file "%s", you have no access to the server.') continue # Perform remaining conditional restores. for server in sorted(remaining_inventory): host, host_dir = _set_host(gvar, servers, server) # Save the initital server group so it can be restored later. response = requests(gvar, '/settings/prepare/') servers['initial_server_group'] = gvar['active_group'] for group in sorted(remaining_inventory[server]): print('Processing missing files: server=%s, group=%s' % (server, group)) # Switch groups. response = requests(gvar, '/settings/prepare/', {'group': group}) for path in remaining_inventory[server][group]: _conditionally_restore_a_file(gvar, path, None) # Restore the server's initial group. response = requests(gvar, '/settings/prepare?%s' % servers['initial_server_group']) _update_git(gvar, 'post-restore') rmtree(gvar['temp_dir']) def update(gvar): return metadata_update(gvar)
en
0.762926
Compare the metadata on the server with its' backup and if they differ, ask the user whether they want to restore the backup. Open the backup file (for writing), making the directory if necessary, and return the file descriptor. Expand the json file to make a readable diff. Scan the backup repository saving a list of all file paths. Remove superfluous columns from the cloud query_list. Backup all user data for all groups/clouds for each server configured in the user defaults. # Retrieve default backup repository. # Retrieve default backup key - no key, no encryption. Return the backup data to be resored minus the group_name. Set the address and credentials for the specified cloudscheduler server. Add untracked items and commit all updates. # If the backup directory is a git repository, update git. # Process untracked files. Backup all user data for all groups/clouds for each server configured in the user defaults. # Retrieve the backup repository and all server information. # Check for missing arguments or help required. # If the backup directory is an encrypted git repository, create a working temorary directory. # If the backup directory is an encrypted git repository, create a working temorary directory. # Retrieve data to backup for each cloudscheduler server. # Save the initital server group so it can be restored later. # Switch groups. # Restore the server's initial group. Restore user data. # Retrieve the backup repository and all server information. # Check for missing arguments or help required. # Commit any outstanding repository updates prior to the restore. # Retrieve an inventory of the current backup files. # We need a temporary working directory. # Retrieve data from each cloudscheduler server to compare with its' backup. If the # backup is different, conditionally (allow the user to choose) restore it. # Save the initital server group so it can be restored later. # Switch groups. # Restore the server's initial group. # Scan remaining backup files building an inventory to restore. # Perform remaining conditional restores. # Save the initital server group so it can be restored later. # Switch groups. # Restore the server's initial group.
2.34275
2
src/error_analysis/compare_msc_datasets.py
fracivilization/distant_ner_using_thesaurus
0
6612679
from collections import Counter from datasets.arrow_dataset import Dataset import os class MSCDatasetComparer: def __init__( self, base_dataset: Dataset, focus_dataset: Dataset, output_dir: str ) -> None: if not os.path.exists(output_dir): os.mkdir(output_dir) i = 1 base_dataset[i], focus_dataset[i] # over predicted spans を 集計する base_label_names = base_dataset.features["labels"].feature.names focus_label_names = focus_dataset.features["labels"].feature.names over_predicted_spans = [] under_predicted_spans = [] base_snts = set([" ".join(snt["tokens"]) for snt in base_dataset]) focus_snts = set([" ".join(snt["tokens"]) for snt in focus_dataset]) duplicate_snts = base_snts & focus_snts duplicate_base_datasets = [ snt for snt in base_dataset if " ".join(snt["tokens"]) in duplicate_snts ] duplicate_focus_datasets = [ snt for snt in focus_dataset if " ".join(snt["tokens"]) in duplicate_snts ] for base_snt, focus_snt in zip( duplicate_base_datasets, duplicate_focus_datasets ): assert base_snt["tokens"] == focus_snt["tokens"] tokens = base_snt["tokens"] snt = " ".join(tokens) base_labels = [base_label_names[l] for l in base_snt["labels"]] focus_labels = [focus_label_names[l] for l in focus_snt["labels"]] base_spans = set(zip(base_snt["starts"], base_snt["ends"], base_labels)) focus_spans = set(zip(focus_snt["starts"], focus_snt["ends"], focus_labels)) for s, e, l in focus_spans - base_spans: over_predicted_spans.append( (" ".join(tokens[s:e]), l, str(s), str(e), snt) ) for s, e, l in base_spans - focus_spans: under_predicted_spans.append( (" ".join(tokens[s:e]), l, str(s), str(e), snt) ) print( "Over predicted span labels: ", Counter([span[1] for span in over_predicted_spans]), ) print("Over predicted span top 300 ranking") print("WORD\tCOUNT") print( "\n".join( [ "\t".join(map(str, word)) for word in Counter( [ span[0].split(" ")[-1].lower() for span in over_predicted_spans ] ).most_common()[:300] ] ) ) with open(os.path.join(output_dir, "over_predicted_spans.tsv"), "w") as f: f.write("\n".join(["\t".join(span) for span in over_predicted_spans])) print( "Under predicted span labels: ", Counter([span[1] for span in under_predicted_spans]), ) print("Under predicted span top 300 ranking") print("WORD\tCOUNT") print( "\n".join( [ "\t".join(map(str, word)) for word in Counter( [ span[0].split(" ")[-1].lower() for span in under_predicted_spans ] ).most_common()[:300] ] ) ) with open(os.path.join(output_dir, "under_predicted_spans.tsv"), "w") as f: f.write("\n".join(["\t".join(span) for span in under_predicted_spans]))
from collections import Counter from datasets.arrow_dataset import Dataset import os class MSCDatasetComparer: def __init__( self, base_dataset: Dataset, focus_dataset: Dataset, output_dir: str ) -> None: if not os.path.exists(output_dir): os.mkdir(output_dir) i = 1 base_dataset[i], focus_dataset[i] # over predicted spans を 集計する base_label_names = base_dataset.features["labels"].feature.names focus_label_names = focus_dataset.features["labels"].feature.names over_predicted_spans = [] under_predicted_spans = [] base_snts = set([" ".join(snt["tokens"]) for snt in base_dataset]) focus_snts = set([" ".join(snt["tokens"]) for snt in focus_dataset]) duplicate_snts = base_snts & focus_snts duplicate_base_datasets = [ snt for snt in base_dataset if " ".join(snt["tokens"]) in duplicate_snts ] duplicate_focus_datasets = [ snt for snt in focus_dataset if " ".join(snt["tokens"]) in duplicate_snts ] for base_snt, focus_snt in zip( duplicate_base_datasets, duplicate_focus_datasets ): assert base_snt["tokens"] == focus_snt["tokens"] tokens = base_snt["tokens"] snt = " ".join(tokens) base_labels = [base_label_names[l] for l in base_snt["labels"]] focus_labels = [focus_label_names[l] for l in focus_snt["labels"]] base_spans = set(zip(base_snt["starts"], base_snt["ends"], base_labels)) focus_spans = set(zip(focus_snt["starts"], focus_snt["ends"], focus_labels)) for s, e, l in focus_spans - base_spans: over_predicted_spans.append( (" ".join(tokens[s:e]), l, str(s), str(e), snt) ) for s, e, l in base_spans - focus_spans: under_predicted_spans.append( (" ".join(tokens[s:e]), l, str(s), str(e), snt) ) print( "Over predicted span labels: ", Counter([span[1] for span in over_predicted_spans]), ) print("Over predicted span top 300 ranking") print("WORD\tCOUNT") print( "\n".join( [ "\t".join(map(str, word)) for word in Counter( [ span[0].split(" ")[-1].lower() for span in over_predicted_spans ] ).most_common()[:300] ] ) ) with open(os.path.join(output_dir, "over_predicted_spans.tsv"), "w") as f: f.write("\n".join(["\t".join(span) for span in over_predicted_spans])) print( "Under predicted span labels: ", Counter([span[1] for span in under_predicted_spans]), ) print("Under predicted span top 300 ranking") print("WORD\tCOUNT") print( "\n".join( [ "\t".join(map(str, word)) for word in Counter( [ span[0].split(" ")[-1].lower() for span in under_predicted_spans ] ).most_common()[:300] ] ) ) with open(os.path.join(output_dir, "under_predicted_spans.tsv"), "w") as f: f.write("\n".join(["\t".join(span) for span in under_predicted_spans]))
ja
0.920634
# over predicted spans を 集計する
2.328606
2
fedlearner/data_join/cmd/data_join_portal_service.py
saswat0/fedlearner
2
6612680
# Copyright 2020 The FedLearner Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding: utf-8 import argparse import logging from fedlearner.common import data_join_service_pb2 as dj_pb from fedlearner.data_join import DataJoinPortalService if __name__ == "__main__": logging.getLogger().setLevel(logging.INFO) logging.basicConfig(format='%(asctime)s %(message)s') parser = argparse.ArgumentParser(description='DataJointPortal cmd.') parser.add_argument('data_join_portal_name', type=str, help='the name of data join portal') parser.add_argument('--etcd_name', type=str, default='test_etcd', help='the name of etcd') parser.add_argument('--etcd_addrs', type=str, default='localhost:2379', help='the addrs of etcd') parser.add_argument('--etcd_base_dir', type=str, default='fedlearner_protal_test', help='the namespace of etcd key for data join portal') parser.add_argument('--raw_data_publish_dir', type=str, required=True, help='the etcd base dir to publish new raw data') parser.add_argument('--use_mock_etcd', action='store_true', help='use to mock etcd for test') parser.add_argument('--input_data_file_iter', type=str, default='TF_RECORD', help='the type for iter of input data file') parser.add_argument('--compressed_type', type=str, default='', choices=['', 'ZLIB', 'GZIP'], help='the compressed type of input data file') parser.add_argument('--portal_reducer_buffer_size', type=int, default=4096, help='the buffer size of portal reducer') parser.add_argument('--example_validator', type=str, default='EXAMPLE_VALIDATOR', help='the name of example validator') parser.add_argument('--validate_event_time', action='store_true', help='validate the example has event time') args = parser.parse_args() options = dj_pb.DataJoinPotralOptions( example_validator=dj_pb.ExampleValidatorOptions( example_validator=args.example_validator, validate_event_time=args.validate_event_time ), reducer_buffer_size=args.portal_reducer_buffer_size, raw_data_options=dj_pb.RawDataOptions( raw_data_iter=args.input_data_file_iter, compressed_type=args.compressed_type ), raw_data_publish_dir=args.raw_data_publish_dir, use_mock_etcd=args.use_mock_etcd ) portal_srv = DataJoinPortalService( args.listen_port, args.data_join_portal_name, args.etcd_name, args.etcd_addrs, args.etcd_base_dir, options, ) portal_srv.run()
# Copyright 2020 The FedLearner Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding: utf-8 import argparse import logging from fedlearner.common import data_join_service_pb2 as dj_pb from fedlearner.data_join import DataJoinPortalService if __name__ == "__main__": logging.getLogger().setLevel(logging.INFO) logging.basicConfig(format='%(asctime)s %(message)s') parser = argparse.ArgumentParser(description='DataJointPortal cmd.') parser.add_argument('data_join_portal_name', type=str, help='the name of data join portal') parser.add_argument('--etcd_name', type=str, default='test_etcd', help='the name of etcd') parser.add_argument('--etcd_addrs', type=str, default='localhost:2379', help='the addrs of etcd') parser.add_argument('--etcd_base_dir', type=str, default='fedlearner_protal_test', help='the namespace of etcd key for data join portal') parser.add_argument('--raw_data_publish_dir', type=str, required=True, help='the etcd base dir to publish new raw data') parser.add_argument('--use_mock_etcd', action='store_true', help='use to mock etcd for test') parser.add_argument('--input_data_file_iter', type=str, default='TF_RECORD', help='the type for iter of input data file') parser.add_argument('--compressed_type', type=str, default='', choices=['', 'ZLIB', 'GZIP'], help='the compressed type of input data file') parser.add_argument('--portal_reducer_buffer_size', type=int, default=4096, help='the buffer size of portal reducer') parser.add_argument('--example_validator', type=str, default='EXAMPLE_VALIDATOR', help='the name of example validator') parser.add_argument('--validate_event_time', action='store_true', help='validate the example has event time') args = parser.parse_args() options = dj_pb.DataJoinPotralOptions( example_validator=dj_pb.ExampleValidatorOptions( example_validator=args.example_validator, validate_event_time=args.validate_event_time ), reducer_buffer_size=args.portal_reducer_buffer_size, raw_data_options=dj_pb.RawDataOptions( raw_data_iter=args.input_data_file_iter, compressed_type=args.compressed_type ), raw_data_publish_dir=args.raw_data_publish_dir, use_mock_etcd=args.use_mock_etcd ) portal_srv = DataJoinPortalService( args.listen_port, args.data_join_portal_name, args.etcd_name, args.etcd_addrs, args.etcd_base_dir, options, ) portal_srv.run()
en
0.851503
# Copyright 2020 The FedLearner Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding: utf-8
1.778214
2
python/str/20. Valid Parentheses.py
Nobodylesszb/LeetCode
0
6612681
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ open_p = ['(', '{', '['] close_p = [')', '}', ']'] # Stack stack = [] for elm in s: # if opening bracket if elm in open_p: # Add the element to the stack stack.append(elm) else: # if the stack is empty if len(stack) == 0: return False # Pop the element off the stack poped = stack.pop() # if the indexes are the same if open_p.index(poped) != close_p.index(elm): return False return len(stack) == 0 class Solution2: def isValid(self, s): stack = [] map = { "{": "}", "[": "]", "(": ")" } for x in s: if x in map: stack.append(map[x]) else: if len(stack) != 0: top_element = stack.pop() if x != top_element: return False else: continue else: return False return len(stack) == 0
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ open_p = ['(', '{', '['] close_p = [')', '}', ']'] # Stack stack = [] for elm in s: # if opening bracket if elm in open_p: # Add the element to the stack stack.append(elm) else: # if the stack is empty if len(stack) == 0: return False # Pop the element off the stack poped = stack.pop() # if the indexes are the same if open_p.index(poped) != close_p.index(elm): return False return len(stack) == 0 class Solution2: def isValid(self, s): stack = [] map = { "{": "}", "[": "]", "(": ")" } for x in s: if x in map: stack.append(map[x]) else: if len(stack) != 0: top_element = stack.pop() if x != top_element: return False else: continue else: return False return len(stack) == 0
en
0.592812
:type s: str :rtype: bool # Stack # if opening bracket # Add the element to the stack # if the stack is empty # Pop the element off the stack # if the indexes are the same
3.62009
4
2017-12/2017-12-21.py
wenjuanchendora/Python_Study
0
6612682
<filename>2017-12/2017-12-21.py """ 利用生成器写入 csv 文件 """ import csv # def fibon(n): # a = b =1 # for i in range(n): # yield a # a, b = b, a + b # def write_csv(list): # with open('data.csv',mode='a',newline="") as f: # w = csv.writer(f) # w.writerow(list) # f.close() # for x in fibon(10): # write_csv([str(x)]) def fibon(n): a = b =1 for i in range(n): yield a a, b = b, a + b # 此方法比定义函数要快速 with open('data.csv',mode='a',newline="") as f: w = csv.writer(f) for x in fibon(10): w.writerow([str(x)]) f.close()
<filename>2017-12/2017-12-21.py """ 利用生成器写入 csv 文件 """ import csv # def fibon(n): # a = b =1 # for i in range(n): # yield a # a, b = b, a + b # def write_csv(list): # with open('data.csv',mode='a',newline="") as f: # w = csv.writer(f) # w.writerow(list) # f.close() # for x in fibon(10): # write_csv([str(x)]) def fibon(n): a = b =1 for i in range(n): yield a a, b = b, a + b # 此方法比定义函数要快速 with open('data.csv',mode='a',newline="") as f: w = csv.writer(f) for x in fibon(10): w.writerow([str(x)]) f.close()
en
0.491798
利用生成器写入 csv 文件 # def fibon(n): # a = b =1 # for i in range(n): # yield a # a, b = b, a + b # def write_csv(list): # with open('data.csv',mode='a',newline="") as f: # w = csv.writer(f) # w.writerow(list) # f.close() # for x in fibon(10): # write_csv([str(x)]) # 此方法比定义函数要快速
3.750754
4
tests/fixtures/bigquery_fixtures.py
autosuggested/fidesops
41
6612683
<gh_stars>10-100 import ast import logging import os from typing import Generator, List, Dict from uuid import uuid4 import pytest from sqlalchemy.orm import Session from fidesops.models.connectionconfig import AccessLevel, ConnectionType, ConnectionConfig from fidesops.models.datasetconfig import DatasetConfig from fidesops.schemas.connection_configuration import BigQuerySchema from fidesops.service.connectors import BigQueryConnector, get_connector from .application_fixtures import integration_config logger = logging.getLogger(__name__) @pytest.fixture(scope="function") def bigquery_connection_config_without_secrets(db: Session) -> Generator: connection_config = ConnectionConfig.create( db=db, data={ "name": str(uuid4()), "key": "my_bigquery_config", "connection_type": ConnectionType.bigquery, "access": AccessLevel.write, }, ) yield connection_config connection_config.delete(db) @pytest.fixture(scope="function") def bigquery_connection_config(db: Session) -> Generator: connection_config = ConnectionConfig.create( db=db, data={ "name": str(uuid4()), "key": "my_bigquery_config", "connection_type": ConnectionType.bigquery, "access": AccessLevel.write, }, ) # Pulling from integration config file or GitHub secrets keyfile_creds = integration_config.get("bigquery", {}).get("keyfile_creds") or ast.literal_eval(os.environ.get( "BIGQUERY_KEYFILE_CREDS" )) dataset = integration_config.get("bigquery", {}).get( "dataset" ) or os.environ.get("BIGQUERY_DATASET") if keyfile_creds: schema = BigQuerySchema(keyfile_creds=keyfile_creds, dataset=dataset) connection_config.secrets = schema.dict() connection_config.save(db=db) yield connection_config connection_config.delete(db) @pytest.fixture def bigquery_example_test_dataset_config( bigquery_connection_config: ConnectionConfig, db: Session, example_datasets: List[Dict], ) -> Generator: bigquery_dataset = example_datasets[7] fides_key = bigquery_dataset["fides_key"] bigquery_connection_config.name = fides_key bigquery_connection_config.key = fides_key bigquery_connection_config.save(db=db) dataset = DatasetConfig.create( db=db, data={ "connection_config_id": bigquery_connection_config.id, "fides_key": fides_key, "dataset": bigquery_dataset, }, ) yield dataset dataset.delete(db=db) @pytest.fixture(scope="function") def bigquery_resources( bigquery_example_test_dataset_config, ): bigquery_connection_config = bigquery_example_test_dataset_config.connection_config connector = BigQueryConnector(bigquery_connection_config) bigquery_client = connector.client() with bigquery_client.connect() as connection: uuid = str(uuid4()) customer_email = f"<EMAIL>" customer_name = f"{uuid}" stmt = "select max(id) from customer;" res = connection.execute(stmt) customer_id = res.all()[0][0] + 1 stmt = "select max(id) from address;" res = connection.execute(stmt) address_id = res.all()[0][0] + 1 city = "Test City" state = "TX" stmt = f""" insert into address (id, house, street, city, state, zip) values ({address_id}, '{111}', 'Test Street', '{city}', '{state}', '55555'); """ connection.execute(stmt) stmt = f""" insert into customer (id, email, name, address_id) values ({customer_id}, '{customer_email}', '{customer_name}', {address_id}); """ connection.execute(stmt) yield { "email": customer_email, "name": customer_name, "id": customer_id, "client": bigquery_client, "address_id": address_id, "city": city, "state": state, "connector": connector, } # Remove test data and close BigQuery connection in teardown stmt = f"delete from customer where email = '{customer_email}';" connection.execute(stmt) stmt = f'delete from address where id = {address_id};' connection.execute(stmt) @pytest.fixture(scope="session") def bigquery_test_engine() -> Generator: """Return a connection to a Google BigQuery Warehouse""" connection_config = ConnectionConfig( name="My BigQuery Config", key="test_bigquery_key", connection_type=ConnectionType.bigquery, ) # Pulling from integration config file or GitHub secrets keyfile_creds = integration_config.get("bigquery", {}).get("keyfile_creds") or ast.literal_eval(os.environ.get( "BIGQUERY_KEYFILE_CREDS" )) dataset = integration_config.get("bigquery", {}).get( "dataset" ) or os.environ.get("BIGQUERY_DATASET") if keyfile_creds: schema = BigQuerySchema(keyfile_creds=keyfile_creds, dataset=dataset) connection_config.secrets = schema.dict() connector: BigQueryConnector = get_connector(connection_config) engine = connector.client() yield engine engine.dispose() def seed_bigquery_integration_db(bigquery_integration_engine) -> None: """ Currently unused. This helper function has already been run once, and data has been populated in the test BigQuery dataset. We may need this later for integration erasure tests, or in case tables are accidentally removed. """ logger.info(f"Seeding bigquery db") statements = [ """ DROP TABLE IF EXISTS fidesopstest.report; """, """ DROP TABLE IF EXISTS fidesopstest.service_request; """, """ DROP TABLE IF EXISTS fidesopstest.login; """, """ DROP TABLE IF EXISTS fidesopstest.visit; """, """ DROP TABLE IF EXISTS fidesopstest.order_item; """, """ DROP TABLE IF EXISTS fidesopstest.orders; """, """ DROP TABLE IF EXISTS fidesopstest.payment_card; """, """ DROP TABLE IF EXISTS fidesopstest.employee; """, """ DROP TABLE IF EXISTS fidesopstest.customer; """, """ DROP TABLE IF EXISTS fidesopstest.address; """, """ DROP TABLE IF EXISTS fidesopstest.product; """, """ CREATE TABLE fidesopstest.product ( id INT, name STRING, price DECIMAL(10,2) ); """, """ CREATE TABLE fidesopstest.address ( id BIGINT, house STRING, street STRING, city STRING, state STRING, zip STRING ); """, """ CREATE TABLE fidesopstest.customer ( id INT, email STRING, name STRING, created TIMESTAMP, address_id BIGINT ); """, """ CREATE TABLE fidesopstest.employee ( id INT, email STRING, name STRING, address_id BIGINT ); """, """ CREATE TABLE fidesopstest.payment_card ( id STRING, name STRING, ccn BIGINT, code SMALLINT, preferred BOOLEAN, customer_id INT, billing_address_id BIGINT ); """, """ CREATE TABLE fidesopstest.orders ( id STRING, customer_id INT, shipping_address_id BIGINT, payment_card_id STRING ); """, """ CREATE TABLE fidesopstest.order_item ( order_id STRING, item_no SMALLINT, product_id INT, quantity SMALLINT ); """, """ CREATE TABLE fidesopstest.visit ( email STRING, last_visit TIMESTAMP ); """, """ CREATE TABLE fidesopstest.login ( id INT, customer_id INT, time TIMESTAMP ); """, """ CREATE TABLE fidesopstest.service_request ( id STRING, email STRING, alt_email STRING, opened DATE, closed DATE, employee_id INT ); """, """ CREATE TABLE fidesopstest.report ( id INT, email STRING, name STRING, year INT, month INT, total_visits INT ); """, """ INSERT INTO fidesopstest.product VALUES (1, 'Example Product 1', 10.00), (2, 'Example Product 2', 20.00), (3, 'Example Product 3', 50.00); """, """ INSERT INTO fidesopstest.address VALUES (1, '123', 'Example Street', 'Exampletown', 'NY', '12345'), (2, '4', 'Example Lane', 'Exampletown', 'NY', '12321'), (3, '555', 'Example Ave', 'Example City', 'NY', '12000'); """, """ INSERT INTO fidesopstest.customer VALUES (1, '<EMAIL>', '<NAME>', '2020-04-01 11:47:42', 1), (2, '<EMAIL>', '<NAME>', '2020-04-01 11:47:42', 2); """, """ INSERT INTO fidesopstest.employee VALUES (1, '<EMAIL>', '<NAME>', 3), (2, '<EMAIL>', '<NAME>', 3); """, """ INSERT INTO fidesopstest.payment_card VALUES ('pay_aaa-aaa', 'Example Card 1', 123456789, 321, true, 1, 1), ('pay_bbb-bbb', 'Example Card 2', 987654321, 123, false, 2, 1); """, """ INSERT INTO fidesopstest.orders VALUES ('ord_aaa-aaa', 1, 2, 'pay_aaa-aaa'), ('ord_bbb-bbb', 2, 1, 'pay_bbb-bbb'), ('ord_ccc-ccc', 1, 1, 'pay_aaa-aaa'), ('ord_ddd-ddd', 1, 1, 'pay_bbb-bbb'); """, """ INSERT INTO fidesopstest.order_item VALUES ('ord_aaa-aaa', 1, 1, 1), ('ord_bbb-bbb', 1, 1, 1), ('ord_ccc-ccc', 1, 1, 1), ('ord_ccc-ccc', 2, 2, 1), ('ord_ddd-ddd', 1, 1, 1); """, """ INSERT INTO fidesopstest.visit VALUES ('<EMAIL>', '2021-01-06 01:00:00'), ('<EMAIL>', '2021-01-06 01:00:00'); """, """ INSERT INTO fidesopstest.login VALUES (1, 1, '2021-01-01 01:00:00'), (2, 1, '2021-01-02 01:00:00'), (5, 1, '2021-01-05 01:00:00'), (6, 1, '2021-01-06 01:00:00'), (7, 2, '2021-01-06 01:00:00'); """, """ INSERT INTO fidesopstest.service_request VALUES ('ser_aaa-aaa', '<EMAIL>', '<EMAIL>', '2021-01-01', '2021-01-03', 1), ('ser_bbb-bbb', '<EMAIL>', null, '2021-01-04', null, 1), ('ser_ccc-ccc', '<EMAIL>', null, '2021-01-05', '2020-01-07', 1), ('ser_ddd-ddd', '<EMAIL>', null, '2021-05-05', '2020-05-08', 2); """, """ INSERT INTO fidesopstest.report VALUES (1, '<EMAIL>', 'Monthly Report', 2021, 8, 100), (2, '<EMAIL>', 'Monthly Report', 2021, 9, 100), (3, '<EMAIL>', 'Monthly Report', 2021, 10, 100), (4, '<EMAIL>', 'Monthly Report', 2021, 11, 100); """, ] with bigquery_integration_engine.connect() as connection: [connection.execute(stmt) for stmt in statements] logger.info(f"Finished seeding bigquery db") return
import ast import logging import os from typing import Generator, List, Dict from uuid import uuid4 import pytest from sqlalchemy.orm import Session from fidesops.models.connectionconfig import AccessLevel, ConnectionType, ConnectionConfig from fidesops.models.datasetconfig import DatasetConfig from fidesops.schemas.connection_configuration import BigQuerySchema from fidesops.service.connectors import BigQueryConnector, get_connector from .application_fixtures import integration_config logger = logging.getLogger(__name__) @pytest.fixture(scope="function") def bigquery_connection_config_without_secrets(db: Session) -> Generator: connection_config = ConnectionConfig.create( db=db, data={ "name": str(uuid4()), "key": "my_bigquery_config", "connection_type": ConnectionType.bigquery, "access": AccessLevel.write, }, ) yield connection_config connection_config.delete(db) @pytest.fixture(scope="function") def bigquery_connection_config(db: Session) -> Generator: connection_config = ConnectionConfig.create( db=db, data={ "name": str(uuid4()), "key": "my_bigquery_config", "connection_type": ConnectionType.bigquery, "access": AccessLevel.write, }, ) # Pulling from integration config file or GitHub secrets keyfile_creds = integration_config.get("bigquery", {}).get("keyfile_creds") or ast.literal_eval(os.environ.get( "BIGQUERY_KEYFILE_CREDS" )) dataset = integration_config.get("bigquery", {}).get( "dataset" ) or os.environ.get("BIGQUERY_DATASET") if keyfile_creds: schema = BigQuerySchema(keyfile_creds=keyfile_creds, dataset=dataset) connection_config.secrets = schema.dict() connection_config.save(db=db) yield connection_config connection_config.delete(db) @pytest.fixture def bigquery_example_test_dataset_config( bigquery_connection_config: ConnectionConfig, db: Session, example_datasets: List[Dict], ) -> Generator: bigquery_dataset = example_datasets[7] fides_key = bigquery_dataset["fides_key"] bigquery_connection_config.name = fides_key bigquery_connection_config.key = fides_key bigquery_connection_config.save(db=db) dataset = DatasetConfig.create( db=db, data={ "connection_config_id": bigquery_connection_config.id, "fides_key": fides_key, "dataset": bigquery_dataset, }, ) yield dataset dataset.delete(db=db) @pytest.fixture(scope="function") def bigquery_resources( bigquery_example_test_dataset_config, ): bigquery_connection_config = bigquery_example_test_dataset_config.connection_config connector = BigQueryConnector(bigquery_connection_config) bigquery_client = connector.client() with bigquery_client.connect() as connection: uuid = str(uuid4()) customer_email = f"<EMAIL>" customer_name = f"{uuid}" stmt = "select max(id) from customer;" res = connection.execute(stmt) customer_id = res.all()[0][0] + 1 stmt = "select max(id) from address;" res = connection.execute(stmt) address_id = res.all()[0][0] + 1 city = "Test City" state = "TX" stmt = f""" insert into address (id, house, street, city, state, zip) values ({address_id}, '{111}', 'Test Street', '{city}', '{state}', '55555'); """ connection.execute(stmt) stmt = f""" insert into customer (id, email, name, address_id) values ({customer_id}, '{customer_email}', '{customer_name}', {address_id}); """ connection.execute(stmt) yield { "email": customer_email, "name": customer_name, "id": customer_id, "client": bigquery_client, "address_id": address_id, "city": city, "state": state, "connector": connector, } # Remove test data and close BigQuery connection in teardown stmt = f"delete from customer where email = '{customer_email}';" connection.execute(stmt) stmt = f'delete from address where id = {address_id};' connection.execute(stmt) @pytest.fixture(scope="session") def bigquery_test_engine() -> Generator: """Return a connection to a Google BigQuery Warehouse""" connection_config = ConnectionConfig( name="My BigQuery Config", key="test_bigquery_key", connection_type=ConnectionType.bigquery, ) # Pulling from integration config file or GitHub secrets keyfile_creds = integration_config.get("bigquery", {}).get("keyfile_creds") or ast.literal_eval(os.environ.get( "BIGQUERY_KEYFILE_CREDS" )) dataset = integration_config.get("bigquery", {}).get( "dataset" ) or os.environ.get("BIGQUERY_DATASET") if keyfile_creds: schema = BigQuerySchema(keyfile_creds=keyfile_creds, dataset=dataset) connection_config.secrets = schema.dict() connector: BigQueryConnector = get_connector(connection_config) engine = connector.client() yield engine engine.dispose() def seed_bigquery_integration_db(bigquery_integration_engine) -> None: """ Currently unused. This helper function has already been run once, and data has been populated in the test BigQuery dataset. We may need this later for integration erasure tests, or in case tables are accidentally removed. """ logger.info(f"Seeding bigquery db") statements = [ """ DROP TABLE IF EXISTS fidesopstest.report; """, """ DROP TABLE IF EXISTS fidesopstest.service_request; """, """ DROP TABLE IF EXISTS fidesopstest.login; """, """ DROP TABLE IF EXISTS fidesopstest.visit; """, """ DROP TABLE IF EXISTS fidesopstest.order_item; """, """ DROP TABLE IF EXISTS fidesopstest.orders; """, """ DROP TABLE IF EXISTS fidesopstest.payment_card; """, """ DROP TABLE IF EXISTS fidesopstest.employee; """, """ DROP TABLE IF EXISTS fidesopstest.customer; """, """ DROP TABLE IF EXISTS fidesopstest.address; """, """ DROP TABLE IF EXISTS fidesopstest.product; """, """ CREATE TABLE fidesopstest.product ( id INT, name STRING, price DECIMAL(10,2) ); """, """ CREATE TABLE fidesopstest.address ( id BIGINT, house STRING, street STRING, city STRING, state STRING, zip STRING ); """, """ CREATE TABLE fidesopstest.customer ( id INT, email STRING, name STRING, created TIMESTAMP, address_id BIGINT ); """, """ CREATE TABLE fidesopstest.employee ( id INT, email STRING, name STRING, address_id BIGINT ); """, """ CREATE TABLE fidesopstest.payment_card ( id STRING, name STRING, ccn BIGINT, code SMALLINT, preferred BOOLEAN, customer_id INT, billing_address_id BIGINT ); """, """ CREATE TABLE fidesopstest.orders ( id STRING, customer_id INT, shipping_address_id BIGINT, payment_card_id STRING ); """, """ CREATE TABLE fidesopstest.order_item ( order_id STRING, item_no SMALLINT, product_id INT, quantity SMALLINT ); """, """ CREATE TABLE fidesopstest.visit ( email STRING, last_visit TIMESTAMP ); """, """ CREATE TABLE fidesopstest.login ( id INT, customer_id INT, time TIMESTAMP ); """, """ CREATE TABLE fidesopstest.service_request ( id STRING, email STRING, alt_email STRING, opened DATE, closed DATE, employee_id INT ); """, """ CREATE TABLE fidesopstest.report ( id INT, email STRING, name STRING, year INT, month INT, total_visits INT ); """, """ INSERT INTO fidesopstest.product VALUES (1, 'Example Product 1', 10.00), (2, 'Example Product 2', 20.00), (3, 'Example Product 3', 50.00); """, """ INSERT INTO fidesopstest.address VALUES (1, '123', 'Example Street', 'Exampletown', 'NY', '12345'), (2, '4', 'Example Lane', 'Exampletown', 'NY', '12321'), (3, '555', 'Example Ave', 'Example City', 'NY', '12000'); """, """ INSERT INTO fidesopstest.customer VALUES (1, '<EMAIL>', '<NAME>', '2020-04-01 11:47:42', 1), (2, '<EMAIL>', '<NAME>', '2020-04-01 11:47:42', 2); """, """ INSERT INTO fidesopstest.employee VALUES (1, '<EMAIL>', '<NAME>', 3), (2, '<EMAIL>', '<NAME>', 3); """, """ INSERT INTO fidesopstest.payment_card VALUES ('pay_aaa-aaa', 'Example Card 1', 123456789, 321, true, 1, 1), ('pay_bbb-bbb', 'Example Card 2', 987654321, 123, false, 2, 1); """, """ INSERT INTO fidesopstest.orders VALUES ('ord_aaa-aaa', 1, 2, 'pay_aaa-aaa'), ('ord_bbb-bbb', 2, 1, 'pay_bbb-bbb'), ('ord_ccc-ccc', 1, 1, 'pay_aaa-aaa'), ('ord_ddd-ddd', 1, 1, 'pay_bbb-bbb'); """, """ INSERT INTO fidesopstest.order_item VALUES ('ord_aaa-aaa', 1, 1, 1), ('ord_bbb-bbb', 1, 1, 1), ('ord_ccc-ccc', 1, 1, 1), ('ord_ccc-ccc', 2, 2, 1), ('ord_ddd-ddd', 1, 1, 1); """, """ INSERT INTO fidesopstest.visit VALUES ('<EMAIL>', '2021-01-06 01:00:00'), ('<EMAIL>', '2021-01-06 01:00:00'); """, """ INSERT INTO fidesopstest.login VALUES (1, 1, '2021-01-01 01:00:00'), (2, 1, '2021-01-02 01:00:00'), (5, 1, '2021-01-05 01:00:00'), (6, 1, '2021-01-06 01:00:00'), (7, 2, '2021-01-06 01:00:00'); """, """ INSERT INTO fidesopstest.service_request VALUES ('ser_aaa-aaa', '<EMAIL>', '<EMAIL>', '2021-01-01', '2021-01-03', 1), ('ser_bbb-bbb', '<EMAIL>', null, '2021-01-04', null, 1), ('ser_ccc-ccc', '<EMAIL>', null, '2021-01-05', '2020-01-07', 1), ('ser_ddd-ddd', '<EMAIL>', null, '2021-05-05', '2020-05-08', 2); """, """ INSERT INTO fidesopstest.report VALUES (1, '<EMAIL>', 'Monthly Report', 2021, 8, 100), (2, '<EMAIL>', 'Monthly Report', 2021, 9, 100), (3, '<EMAIL>', 'Monthly Report', 2021, 10, 100), (4, '<EMAIL>', 'Monthly Report', 2021, 11, 100); """, ] with bigquery_integration_engine.connect() as connection: [connection.execute(stmt) for stmt in statements] logger.info(f"Finished seeding bigquery db") return
en
0.444788
# Pulling from integration config file or GitHub secrets insert into address (id, house, street, city, state, zip) values ({address_id}, '{111}', 'Test Street', '{city}', '{state}', '55555'); insert into customer (id, email, name, address_id) values ({customer_id}, '{customer_email}', '{customer_name}', {address_id}); # Remove test data and close BigQuery connection in teardown Return a connection to a Google BigQuery Warehouse # Pulling from integration config file or GitHub secrets Currently unused. This helper function has already been run once, and data has been populated in the test BigQuery dataset. We may need this later for integration erasure tests, or in case tables are accidentally removed. DROP TABLE IF EXISTS fidesopstest.report; DROP TABLE IF EXISTS fidesopstest.service_request; DROP TABLE IF EXISTS fidesopstest.login; DROP TABLE IF EXISTS fidesopstest.visit; DROP TABLE IF EXISTS fidesopstest.order_item; DROP TABLE IF EXISTS fidesopstest.orders; DROP TABLE IF EXISTS fidesopstest.payment_card; DROP TABLE IF EXISTS fidesopstest.employee; DROP TABLE IF EXISTS fidesopstest.customer; DROP TABLE IF EXISTS fidesopstest.address; DROP TABLE IF EXISTS fidesopstest.product; CREATE TABLE fidesopstest.product ( id INT, name STRING, price DECIMAL(10,2) ); CREATE TABLE fidesopstest.address ( id BIGINT, house STRING, street STRING, city STRING, state STRING, zip STRING ); CREATE TABLE fidesopstest.customer ( id INT, email STRING, name STRING, created TIMESTAMP, address_id BIGINT ); CREATE TABLE fidesopstest.employee ( id INT, email STRING, name STRING, address_id BIGINT ); CREATE TABLE fidesopstest.payment_card ( id STRING, name STRING, ccn BIGINT, code SMALLINT, preferred BOOLEAN, customer_id INT, billing_address_id BIGINT ); CREATE TABLE fidesopstest.orders ( id STRING, customer_id INT, shipping_address_id BIGINT, payment_card_id STRING ); CREATE TABLE fidesopstest.order_item ( order_id STRING, item_no SMALLINT, product_id INT, quantity SMALLINT ); CREATE TABLE fidesopstest.visit ( email STRING, last_visit TIMESTAMP ); CREATE TABLE fidesopstest.login ( id INT, customer_id INT, time TIMESTAMP ); CREATE TABLE fidesopstest.service_request ( id STRING, email STRING, alt_email STRING, opened DATE, closed DATE, employee_id INT ); CREATE TABLE fidesopstest.report ( id INT, email STRING, name STRING, year INT, month INT, total_visits INT ); INSERT INTO fidesopstest.product VALUES (1, 'Example Product 1', 10.00), (2, 'Example Product 2', 20.00), (3, 'Example Product 3', 50.00); INSERT INTO fidesopstest.address VALUES (1, '123', 'Example Street', 'Exampletown', 'NY', '12345'), (2, '4', 'Example Lane', 'Exampletown', 'NY', '12321'), (3, '555', 'Example Ave', 'Example City', 'NY', '12000'); INSERT INTO fidesopstest.customer VALUES (1, '<EMAIL>', '<NAME>', '2020-04-01 11:47:42', 1), (2, '<EMAIL>', '<NAME>', '2020-04-01 11:47:42', 2); INSERT INTO fidesopstest.employee VALUES (1, '<EMAIL>', '<NAME>', 3), (2, '<EMAIL>', '<NAME>', 3); INSERT INTO fidesopstest.payment_card VALUES ('pay_aaa-aaa', 'Example Card 1', 123456789, 321, true, 1, 1), ('pay_bbb-bbb', 'Example Card 2', 987654321, 123, false, 2, 1); INSERT INTO fidesopstest.orders VALUES ('ord_aaa-aaa', 1, 2, 'pay_aaa-aaa'), ('ord_bbb-bbb', 2, 1, 'pay_bbb-bbb'), ('ord_ccc-ccc', 1, 1, 'pay_aaa-aaa'), ('ord_ddd-ddd', 1, 1, 'pay_bbb-bbb'); INSERT INTO fidesopstest.order_item VALUES ('ord_aaa-aaa', 1, 1, 1), ('ord_bbb-bbb', 1, 1, 1), ('ord_ccc-ccc', 1, 1, 1), ('ord_ccc-ccc', 2, 2, 1), ('ord_ddd-ddd', 1, 1, 1); INSERT INTO fidesopstest.visit VALUES ('<EMAIL>', '2021-01-06 01:00:00'), ('<EMAIL>', '2021-01-06 01:00:00'); INSERT INTO fidesopstest.login VALUES (1, 1, '2021-01-01 01:00:00'), (2, 1, '2021-01-02 01:00:00'), (5, 1, '2021-01-05 01:00:00'), (6, 1, '2021-01-06 01:00:00'), (7, 2, '2021-01-06 01:00:00'); INSERT INTO fidesopstest.service_request VALUES ('ser_aaa-aaa', '<EMAIL>', '<EMAIL>', '2021-01-01', '2021-01-03', 1), ('ser_bbb-bbb', '<EMAIL>', null, '2021-01-04', null, 1), ('ser_ccc-ccc', '<EMAIL>', null, '2021-01-05', '2020-01-07', 1), ('ser_ddd-ddd', '<EMAIL>', null, '2021-05-05', '2020-05-08', 2); INSERT INTO fidesopstest.report VALUES (1, '<EMAIL>', 'Monthly Report', 2021, 8, 100), (2, '<EMAIL>', 'Monthly Report', 2021, 9, 100), (3, '<EMAIL>', 'Monthly Report', 2021, 10, 100), (4, '<EMAIL>', 'Monthly Report', 2021, 11, 100);
1.947448
2
UTest/test_vgg.py
johnnylili/VideoSuperResolution
1
6612684
from VSR.Util.Utility import Vgg from VSR.DataLoader.Dataset import load_datasets from VSR.DataLoader.Loader import BatchLoader import tensorflow as tf import numpy as np try: DATASETS = load_datasets('./Data/datasets.json') except FileNotFoundError: DATASETS = load_datasets('../Data/datasets.json') data = DATASETS['91-IMAGE'] loader = BatchLoader(1, data, 'test', convert_to_gray=True, crop=False, scale=1) m = Vgg(input_shape=[None, None, 3], type='vgg19') with tf.Session() as sess: # m = Vgg(input_shape=[None, None, 3], type='vgg19') for hr, lr in loader: y = m(hr, [2,3], [2,3]) break tf.reset_default_graph() m = Vgg(input_shape=[None, None, 3], type='vgg19') with tf.Session() as sess: # m = Vgg(input_shape=[None, None, 3], type='vgg19') for hr, lr in loader: y = m(hr, [2,3], [2,3]) break # Error for not reusing VGG variables # with tf.Session() as sess: # m = Vgg(input_shape=[None, None, 3]) # for hr, lr in loader: # y = m(hr, [2,3], [2,3]) # break
from VSR.Util.Utility import Vgg from VSR.DataLoader.Dataset import load_datasets from VSR.DataLoader.Loader import BatchLoader import tensorflow as tf import numpy as np try: DATASETS = load_datasets('./Data/datasets.json') except FileNotFoundError: DATASETS = load_datasets('../Data/datasets.json') data = DATASETS['91-IMAGE'] loader = BatchLoader(1, data, 'test', convert_to_gray=True, crop=False, scale=1) m = Vgg(input_shape=[None, None, 3], type='vgg19') with tf.Session() as sess: # m = Vgg(input_shape=[None, None, 3], type='vgg19') for hr, lr in loader: y = m(hr, [2,3], [2,3]) break tf.reset_default_graph() m = Vgg(input_shape=[None, None, 3], type='vgg19') with tf.Session() as sess: # m = Vgg(input_shape=[None, None, 3], type='vgg19') for hr, lr in loader: y = m(hr, [2,3], [2,3]) break # Error for not reusing VGG variables # with tf.Session() as sess: # m = Vgg(input_shape=[None, None, 3]) # for hr, lr in loader: # y = m(hr, [2,3], [2,3]) # break
en
0.678975
# m = Vgg(input_shape=[None, None, 3], type='vgg19') # m = Vgg(input_shape=[None, None, 3], type='vgg19') # Error for not reusing VGG variables # with tf.Session() as sess: # m = Vgg(input_shape=[None, None, 3]) # for hr, lr in loader: # y = m(hr, [2,3], [2,3]) # break
2.258546
2
tests/test_api.py
jmsv/specsavers
2
6612685
<gh_stars>1-10 import unittest from requests_html import HTML class TestApi(unittest.TestCase): def setUp(self): from specsavers.api import Api self.test_token = ( "<KEY> "<KEY>" "iwiZXhwIjoxNTIzNzA4MDU5fQ.2U5GYS_SbZq" "4bEUpTA6Em0l4XF3jrMtjBOZyCxZMe3Q") Api._Api__token = self.test_token with open("tests/page_book.html", "r") as book: self.booking_page = book.read() with open("tests/page_store_select.html", "r") as store_select: self.store_select_page = store_select.read() Api.fetch_booking_page = lambda *_: HTML(html=self.booking_page) Api.fetch_store_select_page = \ lambda *_: HTML(html=self.store_select_page) self.api = Api() def test_getting_token_from_html(self): token = self.api.fetch_token() self.assertEqual(token, self.test_token) def test_parsing_for_store_names(self): store_names = self.api.list_of_store_names(1234, 5678) self.assertEqual(store_names, ["woolwich", "barking", "eastham"]) def test_(self): ...
import unittest from requests_html import HTML class TestApi(unittest.TestCase): def setUp(self): from specsavers.api import Api self.test_token = ( "<KEY> "<KEY>" "iwiZXhwIjoxNTIzNzA4MDU5fQ.2U5GYS_SbZq" "4bEUpTA6Em0l4XF3jrMtjBOZyCxZMe3Q") Api._Api__token = self.test_token with open("tests/page_book.html", "r") as book: self.booking_page = book.read() with open("tests/page_store_select.html", "r") as store_select: self.store_select_page = store_select.read() Api.fetch_booking_page = lambda *_: HTML(html=self.booking_page) Api.fetch_store_select_page = \ lambda *_: HTML(html=self.store_select_page) self.api = Api() def test_getting_token_from_html(self): token = self.api.fetch_token() self.assertEqual(token, self.test_token) def test_parsing_for_store_names(self): store_names = self.api.list_of_store_names(1234, 5678) self.assertEqual(store_names, ["woolwich", "barking", "eastham"]) def test_(self): ...
none
1
3.096768
3
pydeezer/__init__.py
steinitzu/pydeezer
2
6612686
<filename>pydeezer/__init__.py # -*- coding: utf-8 -*- import requests try: # Try for python 2.7 from urllib import urlencode except ImportError: # Assume python 3 from urllib.parse import urlencode """ Deezer Python Client Resources: http://developers.deezer.com/api TODO: * Error handling * Tokens refreshing """ class DeezerClient(object): def __init__(self, application_key, secret_key, redirect_uri, base_url=None, base_auth_url=None, perms=None, access_token=None, requests_session=None): # required at init self.application_key = application_key self.secret_key = secret_key self.redirect_uri = redirect_uri self.base_url = base_url or 'https://api.deezer.com' self.base_auth_url = (base_auth_url or 'https://connect.deezer.com/oauth') self.perms = perms # not required self.access_token = access_token if requests_session: self._session = requests_session else: self._session = requests.api def _make_request(self, method, base_url, endpoint, params={}): params['request_method'] = method if base_url == self.base_url: params['access_token'] = self.access_token url = base_url + "/%s" % endpoint result = self._session.get(url, params=params) return result """Auth flow http://developers.deezer.com/api/oauth """ def get_auth_url(self): params = {} params['app_id'] = self.application_key params['redirect_uri'] = self.redirect_uri params['perms'] = self.perms endpoint = '/auth.php' return self.base_auth_url + "%s?%s" % (endpoint, urlencode(params)) def get_auth_token(self, code): params = {} params['app_id'] = self.application_key params['secret'] = self.secret_key params['code'] = code result = self._make_request( method='GET', base_url=self.base_auth_url, endpoint='/access_token.php', params=params ) auth_token_string = result.text auth_token = self._parse_auth_token(auth_token_string) return auth_token def refresh_token(self): raise NotImplementedError def _parse_auth_token(self, auth_token_string): params = auth_token_string.split('&') result = {} for param in params: key, value = param.split('=') result[key] = value return result """api endpoints""" def me(self): result = self._make_request( method='GET', base_url=self.base_url, endpoint='/user/me', ) return result def search_track(self, query, params={}): """http://developers.deezer.com/api/search/track """ params['q'] = query result = self._make_request( method='GET', base_url=self.base_url, endpoint='/search/track', params=params, ) result = result and result.json() if not result: return return result def get_track(self, query, params={}): """http://developers.deezer.com/api/track/ """ result = self._make_request( method='GET', base_url=self.base_url, endpoint="/track/%s" % query, ) result = result and result.json() if not result: return return result def playlist_create(self, title): """http://developers.deezer.com/api/playlist#actions """ params = {} params['title'] = title result = self._make_request( method='POST', base_url=self.base_url, endpoint='/user/me/playlists', params=params, ) return result def playlist_info(self, playlist_id): params = {} endpoint = '/playlist/%s' % playlist_id result = self._make_request( method='GET', base_url=self.base_url, endpoint=endpoint, ) return result def playlist_add_tracks(self, playlist_id, track_ids): """http://developers.deezer.com/api/track#actions """ params = {} track_ids = ",".join([str(track_id) for track_id in track_ids]) params['songs'] = track_ids endpoint = '/playlist/%s/tracks' % playlist_id result = self._make_request( method='POST', base_url=self.base_url, endpoint=endpoint, params=params, ) return result def playlist_remove_tracks(self, playlist_id, track_ids): """http://developers.deezer.com/api/track#actions """ params = {} track_ids = ",".join([str(track_id) for track_id in track_ids]) params['songs'] = track_ids endpoint = '/playlist/%s/tracks' % playlist_id result = self._make_request( method='DELETE', base_url=self.base_url, endpoint=endpoint, params=params, ) return result def playlist_delete(self, playlist_id): endpoint = '/playlist/%s' % playlist_id result = self._make_request( method='DELETE', base_url=self.base_url, endpoint=endpoint) return result def user_playlists(self, user_id='me'): endpoint = '/user/%s/playlists' % user_id result = self._make_request( 'GET', base_url=self.base_url, endpoint=endpoint) return result def user_history(self): result = self._make_request( method='GET', base_url=self.base_url, endpoint='/user/me/history', params={} ) result = result.json() return result
<filename>pydeezer/__init__.py # -*- coding: utf-8 -*- import requests try: # Try for python 2.7 from urllib import urlencode except ImportError: # Assume python 3 from urllib.parse import urlencode """ Deezer Python Client Resources: http://developers.deezer.com/api TODO: * Error handling * Tokens refreshing """ class DeezerClient(object): def __init__(self, application_key, secret_key, redirect_uri, base_url=None, base_auth_url=None, perms=None, access_token=None, requests_session=None): # required at init self.application_key = application_key self.secret_key = secret_key self.redirect_uri = redirect_uri self.base_url = base_url or 'https://api.deezer.com' self.base_auth_url = (base_auth_url or 'https://connect.deezer.com/oauth') self.perms = perms # not required self.access_token = access_token if requests_session: self._session = requests_session else: self._session = requests.api def _make_request(self, method, base_url, endpoint, params={}): params['request_method'] = method if base_url == self.base_url: params['access_token'] = self.access_token url = base_url + "/%s" % endpoint result = self._session.get(url, params=params) return result """Auth flow http://developers.deezer.com/api/oauth """ def get_auth_url(self): params = {} params['app_id'] = self.application_key params['redirect_uri'] = self.redirect_uri params['perms'] = self.perms endpoint = '/auth.php' return self.base_auth_url + "%s?%s" % (endpoint, urlencode(params)) def get_auth_token(self, code): params = {} params['app_id'] = self.application_key params['secret'] = self.secret_key params['code'] = code result = self._make_request( method='GET', base_url=self.base_auth_url, endpoint='/access_token.php', params=params ) auth_token_string = result.text auth_token = self._parse_auth_token(auth_token_string) return auth_token def refresh_token(self): raise NotImplementedError def _parse_auth_token(self, auth_token_string): params = auth_token_string.split('&') result = {} for param in params: key, value = param.split('=') result[key] = value return result """api endpoints""" def me(self): result = self._make_request( method='GET', base_url=self.base_url, endpoint='/user/me', ) return result def search_track(self, query, params={}): """http://developers.deezer.com/api/search/track """ params['q'] = query result = self._make_request( method='GET', base_url=self.base_url, endpoint='/search/track', params=params, ) result = result and result.json() if not result: return return result def get_track(self, query, params={}): """http://developers.deezer.com/api/track/ """ result = self._make_request( method='GET', base_url=self.base_url, endpoint="/track/%s" % query, ) result = result and result.json() if not result: return return result def playlist_create(self, title): """http://developers.deezer.com/api/playlist#actions """ params = {} params['title'] = title result = self._make_request( method='POST', base_url=self.base_url, endpoint='/user/me/playlists', params=params, ) return result def playlist_info(self, playlist_id): params = {} endpoint = '/playlist/%s' % playlist_id result = self._make_request( method='GET', base_url=self.base_url, endpoint=endpoint, ) return result def playlist_add_tracks(self, playlist_id, track_ids): """http://developers.deezer.com/api/track#actions """ params = {} track_ids = ",".join([str(track_id) for track_id in track_ids]) params['songs'] = track_ids endpoint = '/playlist/%s/tracks' % playlist_id result = self._make_request( method='POST', base_url=self.base_url, endpoint=endpoint, params=params, ) return result def playlist_remove_tracks(self, playlist_id, track_ids): """http://developers.deezer.com/api/track#actions """ params = {} track_ids = ",".join([str(track_id) for track_id in track_ids]) params['songs'] = track_ids endpoint = '/playlist/%s/tracks' % playlist_id result = self._make_request( method='DELETE', base_url=self.base_url, endpoint=endpoint, params=params, ) return result def playlist_delete(self, playlist_id): endpoint = '/playlist/%s' % playlist_id result = self._make_request( method='DELETE', base_url=self.base_url, endpoint=endpoint) return result def user_playlists(self, user_id='me'): endpoint = '/user/%s/playlists' % user_id result = self._make_request( 'GET', base_url=self.base_url, endpoint=endpoint) return result def user_history(self): result = self._make_request( method='GET', base_url=self.base_url, endpoint='/user/me/history', params={} ) result = result.json() return result
en
0.374775
# -*- coding: utf-8 -*- # Try for python 2.7 # Assume python 3 Deezer Python Client Resources: http://developers.deezer.com/api TODO: * Error handling * Tokens refreshing # required at init # not required Auth flow http://developers.deezer.com/api/oauth api endpoints http://developers.deezer.com/api/search/track http://developers.deezer.com/api/track/ http://developers.deezer.com/api/playlist#actions http://developers.deezer.com/api/track#actions http://developers.deezer.com/api/track#actions
2.907782
3
education4less/scholarships/models.py
xarielx/education4less
1
6612687
<reponame>xarielx/education4less from django.db import models from django.utils import timezone from django.contrib.auth.models import User # scholarship_name scholarship_link award_amount geographic_requisite enrollment_requisite major_requisite description class Post(models.Model): title = models.CharField(max_length=100, default="empty") content = models.TextField(default="empty") date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, default="ariel") def __str__(self): return self.title
from django.db import models from django.utils import timezone from django.contrib.auth.models import User # scholarship_name scholarship_link award_amount geographic_requisite enrollment_requisite major_requisite description class Post(models.Model): title = models.CharField(max_length=100, default="empty") content = models.TextField(default="empty") date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, default="ariel") def __str__(self): return self.title
en
0.521254
# scholarship_name scholarship_link award_amount geographic_requisite enrollment_requisite major_requisite description
2.21207
2
main.py
veronicamorfi/tied_weights_training
1
6612688
<filename>main.py<gh_stars>1-10 ################################# ### Author: <NAME> ### Affiliation: C4DM, Queen Mary University of London ### ### Version date: July 8th ### ### First presented in: <NAME>. and <NAME>. (2018). Deep learning for audio event detection and tagging on low-resource datasets. Applied Sciences, 8(8):1397. ### Dataset: NIPS4Bplus https://figshare.com/articles/Transcriptions_of_NIPS4B_2013_Bird_Challenge_Training_Dataset/6798548 ### ################################# import librosa import numpy as np import pandas import pickle import os from os import listdir from os.path import isfile, join import matplotlib.pyplot as plt import h5py import tensorflow as tf from keras.callbacks import TensorBoard, ModelCheckpoint, LearningRateScheduler, ReduceLROnPlateau, Callback import keras.backend as K from keras.backend.tensorflow_backend import set_session import math ############################## ### data and target labels ### ############################## # load data in melspec form f = open('melspecs.pckl', 'r') # data_shape = (no_recs, mel_bins, time_frames) MS = pickle.load(f) f.close() # load who labels; contain info about the species present in a recording fwe = open('labels_who.pckl', 'r') # who_labels_shape = (no_recs, no_species) weaklabels = pickle.load(fwe) f.close() # load when labels; recordings with any bird have 1 in all time frames, recordings with no birds have 0 in all time frames fst = open('labels_strong.pckl', 'r') # when_labels_shape = (no_recs, time_frames) stronglabels = pickle.load(fst) f.close() ########################################### ### split to train/val and testing sets ### ########################################### # train and validation sets: recordings start-498 including recordings from 499-end without full temporal annotations (total of 513 recordings) # train and validation sets shape: (513, mel_bins, time_frames) MS_train = MS[:499] MS_train = np.concatenate((MS_train, MS[501:502], MS[514:515], MS[540:541], MS[544:545], MS[552:553], MS[567:568], MS[575:576], MS[587:588], MS[591:592], MS[599:600], MS[614:615], MS[649:651], MS[665:666]), axis=0) weaklabels_train = weaklabels[:499] weaklabels_train = np.concatenate((weaklabels_train, weaklabels[501:502], weaklabels[514:515], weaklabels[540:541], weaklabels[544:545], weaklabels[552:553], weaklabels[567:568], weaklabels[575:576], weaklabels[587:588], weaklabels[591:592], weaklabels[599:600], weaklabels[614:615], weaklabels[649:651], weaklabels[665:666]), axis=0) stronglabels_train = stronglabels[:499] stronglabels_train = np.concatenate((stronglabels_train, stronglabels[501:502], stronglabels[514:515], stronglabels[540:541], stronglabels[544:545], stronglabels[552:553], stronglabels[567:568], stronglabels[575:576], stronglabels[587:588], stronglabels[591:592], stronglabels[599:600], stronglabels[614:615], stronglabels[649:651], stronglabels[665:666]), axis=0) # test set: recordings 499-end excluding ones without full temporal annotations (total of 174 recordings) # test set shape: (174, mel_bins, time_frames) MS_test = MS[499:501] MS_test = np.concatenate((MS_test, MS[502:514], MS[515:540], MS[541:544], MS[545:552], MS[553:567], MS[568:575], MS[576:587], MS[588:591], MS[592:599], MS[600:614], MS[615:649], MS[651:665], MS[666:]), axis=0) weaklabels_test = weaklabels[499:501] weaklabels_test = np.concatenate((weaklabels_test, weaklabels[502:514], weaklabels[515:540], weaklabels[541:544], weaklabels[545:552], weaklabels[553:567], weaklabels[568:575], weaklabels[576:587], weaklabels[588:591], weaklabels[592:599], weaklabels[600:614], weaklabels[615:649], weaklabels[651:665], weaklabels[666:]), axis=0) stronglabels_test = stronglabels[499:501] stronglabels_test = np.concatenate((stronglabels_test, stronglabels[502:514], stronglabels[515:540], stronglabels[541:544], stronglabels[545:552], stronglabels[553:567], stronglabels[568:575], stronglabels[576:587], stronglabels[588:591], stronglabels[592:599], stronglabels[600:614], stronglabels[615:649], stronglabels[651:665], stronglabels[666:]), axis=0) ##################### ### Normalization ### ##################### # train data (total of 450 recordings) temp = np.reshape(MS_train[0:450], (-1,40)).T meanT = np.mean(temp, axis=1) meanT = meanT.reshape((-1,1)) stdT = np.std(temp, axis=1) stdT = stdT.reshape((-1,1)) MS_train_norm = (temp-meanT)/stdT MS_train_norm = MS_train_norm.T MS_train_norm = np.reshape(MS_train_norm, MS_train[0:450].shape) # validation data (total of 63 recordings) MS_val = MS_train[450:] tempv = np.reshape(MS_val, (-1, 40)).T MS_val_norm = (tempv-meanT)/stdT MS_val_norm = MS_val_norm.T MS_val_norm = np.reshape(MS_val_norm, MS_val.shape) # test data tempt = np.reshape(MS_test,(-1,40)).T MS_test_norm = (tempt-meanT)/stdT MS_test_norm = MS_test_norm.T MS_test_norm = np.reshape(MS_test_norm, MS_test.shape) ########################## ### network input prep ### ########################## # reshape TEMPt = np.empty((MS_train_norm.shape[0], MS_train_norm.shape[2], MS_train_norm.shape[1])) for i in range(len(MS_train_norm)): TEMPt[i] = MS_train_norm[i].T MS_train_norm = TEMPt MS_train_norm = np.expand_dims(MS_train_norm, axis=3) TEMPv = np.empty((MS_val_norm.shape[0], MS_val_norm.shape[2], MS_val_norm.shape[1])) for i in range(len(MS_val_norm)): TEMPv[i] = MS_val_norm[i].T MS_val_norm = TEMPv MS_val_norm = np.expand_dims(MS_val_norm, axis=3) TEMPte = np.empty((MS_test_norm.shape[0], MS_test_norm.shape[2], MS_test_norm.shape[1])) for i in range(len(MS_test_norm)): TEMPte[i] = MS_test_norm[i].T MS_test_norm = TEMPte MS_test_norm = np.expand_dims(MS_test_norm, axis=3) # split train and validation labels stronglabels_train = stronglabels_train[0:450] weaklabels_train = weaklabels_train[0:450] stronglabels_val = stronglabels_train[450:] weaklabels_val = weaklabels_train[450:] ##################################################### ### positive-negative separation for WHEN network ### ##################################################### # Separate positive and negative recordings and their labels (only for train set) strongpos_labels = [] # all ones (temporal) strongneg_labels = [] # all zeros (temporal) weakpos_labels = [] # at least one one (tags) weakneg_labels = [] # all zeros (tags) pos_MS_train_norm = [] neg_MS_train_norm = [] for i in range(len(stronglabels_train)): if stronglabels_train[i][0] == 0: weakneg_labels.append(weaklabels_train[i]) strongneg_labels.append(stronglabels_train[i]) neg_MS_train_norm.append(MS_train_norm[i]) else: weakpos_labels.append(weaklabels_train[i]) strongpos_labels.append(stronglabels_train[i]) pos_MS_train_norm.append(MS_train_norm[i]) strongpos_labels = np.asarray(strongpos_labels) strongneg_labels = np.asarray(strongneg_labels) weakpos_labels = np.asarray(weakpos_labels) weakneg_labels = np.asarray(weakneg_labels) pos_MS_train_norm = np.asarray(pos_MS_train_norm) # totals to 385 recs neg_MS_train_norm = np.asarray(neg_MS_train_norm) # totals to 65 recs ############################ ### Network architecture ### ############################ def convBNpr(a, num_filters, kernel): c1 = Conv2D(filters=num_filters, kernel_size=kernel, strides=(1, 1), padding='same', use_bias=False, kernel_initializer=glorot_uniform(seed=123),kernel_regularizer=regularizers.l2(0.001))(a) c1 = BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001)(c1) c1 = Activation('relu')(c1) return c1 def A(input_shape): a = Input(shape=(input_shape)) # CNN c1 = convBNpr(a, 64, (3,3)) c1 = convBNpr(c1, 64, (3,3)) p1 = MaxPooling2D(pool_size=(1, 5))(c1) c2 = convBNpr(p1, 64, (3,3)) c2 = convBNpr(c2, 64, (3,3)) p2 = MaxPooling2D(pool_size=(1, 4))(c2) c3 = convBNpr(p2, 64, (3,3)) c3 = convBNpr(c3, 64, (3,3)) p3 = MaxPooling2D(pool_size=(1, 2))(c3) model = Model(inputs=a, outputs=[p3]) return model def B(input_shape): p3 = Input(shape=(input_shape)) # Reshape b = Reshape((input_shape[0],-1))(p3) # GRU r1 = Bidirectional(GRU(units=64, kernel_regularizer=regularizers.l2(0.01), return_sequences=True))(b) r2 = Bidirectional(GRU(units=64, kernel_regularizer=regularizers.l2(0.01), return_sequences=True))(r1) # Dense d1 = TimeDistributed(Dense(87, activation='relu', kernel_regularizer=regularizers.l2(0.01)))(r2) # WHEN labels d2 = TimeDistributed(Dense(1, activation='sigmoid', kernel_regularizer=regularizers.l2(0.01)))(d1) f1 = Flatten()(d2) model = Model(inputs=p3, outputs=[f1]) return model def C(input_shape, species): p3 = Input(shape=(input_shape)) a1 = GlobalAveragePooling2D()(p3) # WHO labels d5 = Dense(species, activation='sigmoid', kernel_regularizer=regularizers.l2(0.001), bias_initializer=random_normal(mean=-4.60, stddev=0.05, seed=123))(a1) # bias initialiser specific to our train data model = Model(inputs=p3, outputs=[d5]) return model ########################## ### WHEN Loss function ### ########################## def WHENLoss(yTrue,yPred): # MMM loss function # a:mean=0.5, b:max=1 and c:min=0 a = K.binary_crossentropy(tf.scalar_mul(0.5,K.max(yTrue, axis=-1)),K.mean(yPred, axis=-1)) b = K.binary_crossentropy(K.max(yTrue, axis=-1), K.max(yPred, axis=-1)) c = K.binary_crossentropy(K.min(tf.scalar_mul(0.0, yTrue), axis=-1), K.min(yPred, axis=-1)) l_when = tf.scalar_mul(0.33,(a+b+c)) return l_when ##################### ### Learning rate ### ##################### def step_decay(epoch): initial_lrate = 1e-5 # 1e-3, 1e-4 drop = 0.5 epochs_drop = 20.0 min_lrate = 1e-8 lrate = np.maximum(initial_lrate * math.pow(drop, math.floor((1+epoch)/epochs_drop)),min_lrate) return lrate class MyLearningRateScheduler(Callback): def __init__(self, schedule, verbose=0, ep=0): super(MyLearningRateScheduler, self).__init__() self.schedule = schedule self.verbose = verbose self.ep = ep def on_epoch_begin(self, epoch, logs=None): if not hasattr(self.model.optimizer, 'lr'): raise ValueError('Optimizer must have a "lr" attribute.') lr = self.schedule(self.ep) if not isinstance(lr, (float, np.float32, np.float64)): raise ValueError('The output of the "schedule" function ' 'should be float.') K.set_value(self.model.optimizer.lr, lr) if self.verbose > 0: print('\nEpoch %05d: LearningRateScheduler reducing learning ' 'rate to %s.' % (self.ep + 1, lr)) self.ep += 1 ############# ### Model ### ############# # GPU setup os.environ["CUDA_VISIBLE_DEVICES"]="0" # which GPU to use config = tf.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.3 # what % of the GPU to use set_session(tf.Session(config=config)) # define and compile models adam1 = Adam(lr = 1e-5) adam2 = Adam(lr = 1e-5) model_A = A((432, 40, 1)) model_A.summary() model_B = B((432, 1, 64)) # input of B is output of A model_B.summary() model_C = C((432, 1, 64), 87) # input of C is output of A model_C.summary() mel_input = Input(shape=((432, 40, 1))) a_out_bc_input = model_A([mel_input]) b_out = model_B([a_out_bc_input]) c_out = model_C([a_out_bc_input]) model_when = Model([mel_input], b_out) # melspec input --> A --> B --> WHEN prediction model_who = Model([mel_input], c_out) # melspec input --> A --> C --> WHO prediction model_when.summary() model_who.summary() model_when.compile(loss=[WHENLoss], optimizer=adam1) model_who.compile(loss=['binary_crossentropy'], optimizer=adam2) ################# ### Callbacks ### ################# reduce_lr_who = MyLearningRateScheduler(step_decay, verbose=1) reduce_lr_when = MyLearningRateScheduler(step_decay, verbose=1) tbCallback_who = TensorBoard(log_dir='../logs/TB_who', write_graph=True) tbCallback_when = TensorBoard(log_dir='../logs/TB_when', write_graph=True) # saving weights every 10 epochs, because there is no way to properly early stop for WHEN network cpCallback_who = ModelCheckpoint('./checkpoints/who/weights_who_{epoch:02d}-{val_loss:.2f}.h5', monitor='val_loss', save_best_only=False, save_weights_only=True, mode='min', period=10) cpCallback_when = ModelCheckpoint('./checkpoints/when/weights_when_{epoch:02d}-{val_loss:.2f}.h5', monitor='val_loss', save_best_only=False, save_weights_only=True, mode='min', period=10) ############################### ### WHEN training generator ### ############################### def train_generator(pos_MS_train_norm, neg_MS_train_norm, pos_labels, neg_labels, batchsize=4): # actual batchsize is 4*2=8 while 1: indexes = np.arange(len(pos_MS_train_norm)) np.random.shuffle(indexes) imax = int(len(indexes)/batchsize) for i in range(imax): pos_out_data = [] pos_out_labels =[] neg_out_data = [] neg_out_labels =[] for k in indexes[i*batchsize:(i+1)*batchsize]: pos_out_data.append(pos_MS_train_norm[k]) pos_out_labels.append(pos_labels[k]) neg_ind = np.arange(len(neg_MS_train_norm)) np.random.shuffle(neg_ind) for n in range(batchsize): ind = neg_ind[n] neg_out_data.append(neg_MS_train_norm[ind]) neg_out_labels.append(neg_labels[ind]) out_data = [] out_labels = [] for m in range(batchsize): out_data.append(pos_out_data[m]) out_data.append(neg_out_data[m]) out_labels.append(pos_labels[m]) out_labels.append(neg_labels[m]) yield np.asarray(out_data), np.asarray(out_labels) ################ ### Training ### ################ for epoch in range(1500): model_when.fit_generator(train_generator(pos_MS_train_norm, neg_MS_train_norm, strongpos_labels, strongneg_labels), steps_per_epoch=len(pos_MS_train_norm)/4, epochs=epoch+1, verbose=1, callbacks=[tbCallback_when, reduce_lr_when, cpCallback_when], validation_data=(MS_val_norm, stronglabels_val), initial_epoch=epoch) model_who.fit(x=MS_train_norm, y=weaklabels_train, batch_size=8, epochs=epoch+1, callbacks=[tbCallback_who, reduce_lr_who, cpCallback_who], validation_split=0, validation_data=(MS_val_norm, weaklabels_val), shuffle=True, verbose=1, initial_epoch=epoch) ############### ### Testing ### ############### path2weights_when = './checkpoints/when/' saved_weights_when = [f for f in listdir(path2weights_when) if isfile(join(path2weights_when, f))] path2weights_who = './checkpoints/who/' saved_weights_who = [f for f in listdir(path2weights_who) if isfile(join(path2weights_who, f))] # predictions from every 10 epochs t_predictions_when = [] t_predictions_who = [] for w in saved_weights_when: # load weights of trained network model_when.load_weights(path2weights_when+w) # predict on testing set t_predictions_when.append(model_when.predict(x=MS_test_norm, batch_size=1, verbose=1)) for w in saved_weights_who: # load weights of trained network model_who.load_weights(path2weights_who+w) # predict on testing set t_predictions_who.append(model_who.predict(x=MS_test_norm, batch_size=1, verbose=1)) fw = open('./predictions/when.pckl', 'w') pickle.dump(t_predictions_when, fw) fw.close() fw = open('./predictions/who.pckl', 'w') pickle.dump(t_predictions_who, fw) fw.close()
<filename>main.py<gh_stars>1-10 ################################# ### Author: <NAME> ### Affiliation: C4DM, Queen Mary University of London ### ### Version date: July 8th ### ### First presented in: <NAME>. and <NAME>. (2018). Deep learning for audio event detection and tagging on low-resource datasets. Applied Sciences, 8(8):1397. ### Dataset: NIPS4Bplus https://figshare.com/articles/Transcriptions_of_NIPS4B_2013_Bird_Challenge_Training_Dataset/6798548 ### ################################# import librosa import numpy as np import pandas import pickle import os from os import listdir from os.path import isfile, join import matplotlib.pyplot as plt import h5py import tensorflow as tf from keras.callbacks import TensorBoard, ModelCheckpoint, LearningRateScheduler, ReduceLROnPlateau, Callback import keras.backend as K from keras.backend.tensorflow_backend import set_session import math ############################## ### data and target labels ### ############################## # load data in melspec form f = open('melspecs.pckl', 'r') # data_shape = (no_recs, mel_bins, time_frames) MS = pickle.load(f) f.close() # load who labels; contain info about the species present in a recording fwe = open('labels_who.pckl', 'r') # who_labels_shape = (no_recs, no_species) weaklabels = pickle.load(fwe) f.close() # load when labels; recordings with any bird have 1 in all time frames, recordings with no birds have 0 in all time frames fst = open('labels_strong.pckl', 'r') # when_labels_shape = (no_recs, time_frames) stronglabels = pickle.load(fst) f.close() ########################################### ### split to train/val and testing sets ### ########################################### # train and validation sets: recordings start-498 including recordings from 499-end without full temporal annotations (total of 513 recordings) # train and validation sets shape: (513, mel_bins, time_frames) MS_train = MS[:499] MS_train = np.concatenate((MS_train, MS[501:502], MS[514:515], MS[540:541], MS[544:545], MS[552:553], MS[567:568], MS[575:576], MS[587:588], MS[591:592], MS[599:600], MS[614:615], MS[649:651], MS[665:666]), axis=0) weaklabels_train = weaklabels[:499] weaklabels_train = np.concatenate((weaklabels_train, weaklabels[501:502], weaklabels[514:515], weaklabels[540:541], weaklabels[544:545], weaklabels[552:553], weaklabels[567:568], weaklabels[575:576], weaklabels[587:588], weaklabels[591:592], weaklabels[599:600], weaklabels[614:615], weaklabels[649:651], weaklabels[665:666]), axis=0) stronglabels_train = stronglabels[:499] stronglabels_train = np.concatenate((stronglabels_train, stronglabels[501:502], stronglabels[514:515], stronglabels[540:541], stronglabels[544:545], stronglabels[552:553], stronglabels[567:568], stronglabels[575:576], stronglabels[587:588], stronglabels[591:592], stronglabels[599:600], stronglabels[614:615], stronglabels[649:651], stronglabels[665:666]), axis=0) # test set: recordings 499-end excluding ones without full temporal annotations (total of 174 recordings) # test set shape: (174, mel_bins, time_frames) MS_test = MS[499:501] MS_test = np.concatenate((MS_test, MS[502:514], MS[515:540], MS[541:544], MS[545:552], MS[553:567], MS[568:575], MS[576:587], MS[588:591], MS[592:599], MS[600:614], MS[615:649], MS[651:665], MS[666:]), axis=0) weaklabels_test = weaklabels[499:501] weaklabels_test = np.concatenate((weaklabels_test, weaklabels[502:514], weaklabels[515:540], weaklabels[541:544], weaklabels[545:552], weaklabels[553:567], weaklabels[568:575], weaklabels[576:587], weaklabels[588:591], weaklabels[592:599], weaklabels[600:614], weaklabels[615:649], weaklabels[651:665], weaklabels[666:]), axis=0) stronglabels_test = stronglabels[499:501] stronglabels_test = np.concatenate((stronglabels_test, stronglabels[502:514], stronglabels[515:540], stronglabels[541:544], stronglabels[545:552], stronglabels[553:567], stronglabels[568:575], stronglabels[576:587], stronglabels[588:591], stronglabels[592:599], stronglabels[600:614], stronglabels[615:649], stronglabels[651:665], stronglabels[666:]), axis=0) ##################### ### Normalization ### ##################### # train data (total of 450 recordings) temp = np.reshape(MS_train[0:450], (-1,40)).T meanT = np.mean(temp, axis=1) meanT = meanT.reshape((-1,1)) stdT = np.std(temp, axis=1) stdT = stdT.reshape((-1,1)) MS_train_norm = (temp-meanT)/stdT MS_train_norm = MS_train_norm.T MS_train_norm = np.reshape(MS_train_norm, MS_train[0:450].shape) # validation data (total of 63 recordings) MS_val = MS_train[450:] tempv = np.reshape(MS_val, (-1, 40)).T MS_val_norm = (tempv-meanT)/stdT MS_val_norm = MS_val_norm.T MS_val_norm = np.reshape(MS_val_norm, MS_val.shape) # test data tempt = np.reshape(MS_test,(-1,40)).T MS_test_norm = (tempt-meanT)/stdT MS_test_norm = MS_test_norm.T MS_test_norm = np.reshape(MS_test_norm, MS_test.shape) ########################## ### network input prep ### ########################## # reshape TEMPt = np.empty((MS_train_norm.shape[0], MS_train_norm.shape[2], MS_train_norm.shape[1])) for i in range(len(MS_train_norm)): TEMPt[i] = MS_train_norm[i].T MS_train_norm = TEMPt MS_train_norm = np.expand_dims(MS_train_norm, axis=3) TEMPv = np.empty((MS_val_norm.shape[0], MS_val_norm.shape[2], MS_val_norm.shape[1])) for i in range(len(MS_val_norm)): TEMPv[i] = MS_val_norm[i].T MS_val_norm = TEMPv MS_val_norm = np.expand_dims(MS_val_norm, axis=3) TEMPte = np.empty((MS_test_norm.shape[0], MS_test_norm.shape[2], MS_test_norm.shape[1])) for i in range(len(MS_test_norm)): TEMPte[i] = MS_test_norm[i].T MS_test_norm = TEMPte MS_test_norm = np.expand_dims(MS_test_norm, axis=3) # split train and validation labels stronglabels_train = stronglabels_train[0:450] weaklabels_train = weaklabels_train[0:450] stronglabels_val = stronglabels_train[450:] weaklabels_val = weaklabels_train[450:] ##################################################### ### positive-negative separation for WHEN network ### ##################################################### # Separate positive and negative recordings and their labels (only for train set) strongpos_labels = [] # all ones (temporal) strongneg_labels = [] # all zeros (temporal) weakpos_labels = [] # at least one one (tags) weakneg_labels = [] # all zeros (tags) pos_MS_train_norm = [] neg_MS_train_norm = [] for i in range(len(stronglabels_train)): if stronglabels_train[i][0] == 0: weakneg_labels.append(weaklabels_train[i]) strongneg_labels.append(stronglabels_train[i]) neg_MS_train_norm.append(MS_train_norm[i]) else: weakpos_labels.append(weaklabels_train[i]) strongpos_labels.append(stronglabels_train[i]) pos_MS_train_norm.append(MS_train_norm[i]) strongpos_labels = np.asarray(strongpos_labels) strongneg_labels = np.asarray(strongneg_labels) weakpos_labels = np.asarray(weakpos_labels) weakneg_labels = np.asarray(weakneg_labels) pos_MS_train_norm = np.asarray(pos_MS_train_norm) # totals to 385 recs neg_MS_train_norm = np.asarray(neg_MS_train_norm) # totals to 65 recs ############################ ### Network architecture ### ############################ def convBNpr(a, num_filters, kernel): c1 = Conv2D(filters=num_filters, kernel_size=kernel, strides=(1, 1), padding='same', use_bias=False, kernel_initializer=glorot_uniform(seed=123),kernel_regularizer=regularizers.l2(0.001))(a) c1 = BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001)(c1) c1 = Activation('relu')(c1) return c1 def A(input_shape): a = Input(shape=(input_shape)) # CNN c1 = convBNpr(a, 64, (3,3)) c1 = convBNpr(c1, 64, (3,3)) p1 = MaxPooling2D(pool_size=(1, 5))(c1) c2 = convBNpr(p1, 64, (3,3)) c2 = convBNpr(c2, 64, (3,3)) p2 = MaxPooling2D(pool_size=(1, 4))(c2) c3 = convBNpr(p2, 64, (3,3)) c3 = convBNpr(c3, 64, (3,3)) p3 = MaxPooling2D(pool_size=(1, 2))(c3) model = Model(inputs=a, outputs=[p3]) return model def B(input_shape): p3 = Input(shape=(input_shape)) # Reshape b = Reshape((input_shape[0],-1))(p3) # GRU r1 = Bidirectional(GRU(units=64, kernel_regularizer=regularizers.l2(0.01), return_sequences=True))(b) r2 = Bidirectional(GRU(units=64, kernel_regularizer=regularizers.l2(0.01), return_sequences=True))(r1) # Dense d1 = TimeDistributed(Dense(87, activation='relu', kernel_regularizer=regularizers.l2(0.01)))(r2) # WHEN labels d2 = TimeDistributed(Dense(1, activation='sigmoid', kernel_regularizer=regularizers.l2(0.01)))(d1) f1 = Flatten()(d2) model = Model(inputs=p3, outputs=[f1]) return model def C(input_shape, species): p3 = Input(shape=(input_shape)) a1 = GlobalAveragePooling2D()(p3) # WHO labels d5 = Dense(species, activation='sigmoid', kernel_regularizer=regularizers.l2(0.001), bias_initializer=random_normal(mean=-4.60, stddev=0.05, seed=123))(a1) # bias initialiser specific to our train data model = Model(inputs=p3, outputs=[d5]) return model ########################## ### WHEN Loss function ### ########################## def WHENLoss(yTrue,yPred): # MMM loss function # a:mean=0.5, b:max=1 and c:min=0 a = K.binary_crossentropy(tf.scalar_mul(0.5,K.max(yTrue, axis=-1)),K.mean(yPred, axis=-1)) b = K.binary_crossentropy(K.max(yTrue, axis=-1), K.max(yPred, axis=-1)) c = K.binary_crossentropy(K.min(tf.scalar_mul(0.0, yTrue), axis=-1), K.min(yPred, axis=-1)) l_when = tf.scalar_mul(0.33,(a+b+c)) return l_when ##################### ### Learning rate ### ##################### def step_decay(epoch): initial_lrate = 1e-5 # 1e-3, 1e-4 drop = 0.5 epochs_drop = 20.0 min_lrate = 1e-8 lrate = np.maximum(initial_lrate * math.pow(drop, math.floor((1+epoch)/epochs_drop)),min_lrate) return lrate class MyLearningRateScheduler(Callback): def __init__(self, schedule, verbose=0, ep=0): super(MyLearningRateScheduler, self).__init__() self.schedule = schedule self.verbose = verbose self.ep = ep def on_epoch_begin(self, epoch, logs=None): if not hasattr(self.model.optimizer, 'lr'): raise ValueError('Optimizer must have a "lr" attribute.') lr = self.schedule(self.ep) if not isinstance(lr, (float, np.float32, np.float64)): raise ValueError('The output of the "schedule" function ' 'should be float.') K.set_value(self.model.optimizer.lr, lr) if self.verbose > 0: print('\nEpoch %05d: LearningRateScheduler reducing learning ' 'rate to %s.' % (self.ep + 1, lr)) self.ep += 1 ############# ### Model ### ############# # GPU setup os.environ["CUDA_VISIBLE_DEVICES"]="0" # which GPU to use config = tf.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.3 # what % of the GPU to use set_session(tf.Session(config=config)) # define and compile models adam1 = Adam(lr = 1e-5) adam2 = Adam(lr = 1e-5) model_A = A((432, 40, 1)) model_A.summary() model_B = B((432, 1, 64)) # input of B is output of A model_B.summary() model_C = C((432, 1, 64), 87) # input of C is output of A model_C.summary() mel_input = Input(shape=((432, 40, 1))) a_out_bc_input = model_A([mel_input]) b_out = model_B([a_out_bc_input]) c_out = model_C([a_out_bc_input]) model_when = Model([mel_input], b_out) # melspec input --> A --> B --> WHEN prediction model_who = Model([mel_input], c_out) # melspec input --> A --> C --> WHO prediction model_when.summary() model_who.summary() model_when.compile(loss=[WHENLoss], optimizer=adam1) model_who.compile(loss=['binary_crossentropy'], optimizer=adam2) ################# ### Callbacks ### ################# reduce_lr_who = MyLearningRateScheduler(step_decay, verbose=1) reduce_lr_when = MyLearningRateScheduler(step_decay, verbose=1) tbCallback_who = TensorBoard(log_dir='../logs/TB_who', write_graph=True) tbCallback_when = TensorBoard(log_dir='../logs/TB_when', write_graph=True) # saving weights every 10 epochs, because there is no way to properly early stop for WHEN network cpCallback_who = ModelCheckpoint('./checkpoints/who/weights_who_{epoch:02d}-{val_loss:.2f}.h5', monitor='val_loss', save_best_only=False, save_weights_only=True, mode='min', period=10) cpCallback_when = ModelCheckpoint('./checkpoints/when/weights_when_{epoch:02d}-{val_loss:.2f}.h5', monitor='val_loss', save_best_only=False, save_weights_only=True, mode='min', period=10) ############################### ### WHEN training generator ### ############################### def train_generator(pos_MS_train_norm, neg_MS_train_norm, pos_labels, neg_labels, batchsize=4): # actual batchsize is 4*2=8 while 1: indexes = np.arange(len(pos_MS_train_norm)) np.random.shuffle(indexes) imax = int(len(indexes)/batchsize) for i in range(imax): pos_out_data = [] pos_out_labels =[] neg_out_data = [] neg_out_labels =[] for k in indexes[i*batchsize:(i+1)*batchsize]: pos_out_data.append(pos_MS_train_norm[k]) pos_out_labels.append(pos_labels[k]) neg_ind = np.arange(len(neg_MS_train_norm)) np.random.shuffle(neg_ind) for n in range(batchsize): ind = neg_ind[n] neg_out_data.append(neg_MS_train_norm[ind]) neg_out_labels.append(neg_labels[ind]) out_data = [] out_labels = [] for m in range(batchsize): out_data.append(pos_out_data[m]) out_data.append(neg_out_data[m]) out_labels.append(pos_labels[m]) out_labels.append(neg_labels[m]) yield np.asarray(out_data), np.asarray(out_labels) ################ ### Training ### ################ for epoch in range(1500): model_when.fit_generator(train_generator(pos_MS_train_norm, neg_MS_train_norm, strongpos_labels, strongneg_labels), steps_per_epoch=len(pos_MS_train_norm)/4, epochs=epoch+1, verbose=1, callbacks=[tbCallback_when, reduce_lr_when, cpCallback_when], validation_data=(MS_val_norm, stronglabels_val), initial_epoch=epoch) model_who.fit(x=MS_train_norm, y=weaklabels_train, batch_size=8, epochs=epoch+1, callbacks=[tbCallback_who, reduce_lr_who, cpCallback_who], validation_split=0, validation_data=(MS_val_norm, weaklabels_val), shuffle=True, verbose=1, initial_epoch=epoch) ############### ### Testing ### ############### path2weights_when = './checkpoints/when/' saved_weights_when = [f for f in listdir(path2weights_when) if isfile(join(path2weights_when, f))] path2weights_who = './checkpoints/who/' saved_weights_who = [f for f in listdir(path2weights_who) if isfile(join(path2weights_who, f))] # predictions from every 10 epochs t_predictions_when = [] t_predictions_who = [] for w in saved_weights_when: # load weights of trained network model_when.load_weights(path2weights_when+w) # predict on testing set t_predictions_when.append(model_when.predict(x=MS_test_norm, batch_size=1, verbose=1)) for w in saved_weights_who: # load weights of trained network model_who.load_weights(path2weights_who+w) # predict on testing set t_predictions_who.append(model_who.predict(x=MS_test_norm, batch_size=1, verbose=1)) fw = open('./predictions/when.pckl', 'w') pickle.dump(t_predictions_when, fw) fw.close() fw = open('./predictions/who.pckl', 'w') pickle.dump(t_predictions_who, fw) fw.close()
en
0.390906
################################# ### Author: <NAME> ### Affiliation: C4DM, Queen Mary University of London ### ### Version date: July 8th ### ### First presented in: <NAME>. and <NAME>. (2018). Deep learning for audio event detection and tagging on low-resource datasets. Applied Sciences, 8(8):1397. ### Dataset: NIPS4Bplus https://figshare.com/articles/Transcriptions_of_NIPS4B_2013_Bird_Challenge_Training_Dataset/6798548 ### ################################# ############################## ### data and target labels ### ############################## # load data in melspec form # data_shape = (no_recs, mel_bins, time_frames) # load who labels; contain info about the species present in a recording # who_labels_shape = (no_recs, no_species) # load when labels; recordings with any bird have 1 in all time frames, recordings with no birds have 0 in all time frames # when_labels_shape = (no_recs, time_frames) ########################################### ### split to train/val and testing sets ### ########################################### # train and validation sets: recordings start-498 including recordings from 499-end without full temporal annotations (total of 513 recordings) # train and validation sets shape: (513, mel_bins, time_frames) # test set: recordings 499-end excluding ones without full temporal annotations (total of 174 recordings) # test set shape: (174, mel_bins, time_frames) ##################### ### Normalization ### ##################### # train data (total of 450 recordings) # validation data (total of 63 recordings) # test data ########################## ### network input prep ### ########################## # reshape # split train and validation labels ##################################################### ### positive-negative separation for WHEN network ### ##################################################### # Separate positive and negative recordings and their labels (only for train set) # all ones (temporal) # all zeros (temporal) # at least one one (tags) # all zeros (tags) # totals to 385 recs # totals to 65 recs ############################ ### Network architecture ### ############################ # CNN # Reshape # GRU # Dense # WHEN labels # WHO labels # bias initialiser specific to our train data ########################## ### WHEN Loss function ### ########################## # MMM loss function # a:mean=0.5, b:max=1 and c:min=0 ##################### ### Learning rate ### ##################### # 1e-3, 1e-4 ############# ### Model ### ############# # GPU setup # which GPU to use # what % of the GPU to use # define and compile models # input of B is output of A # input of C is output of A # melspec input --> A --> B --> WHEN prediction # melspec input --> A --> C --> WHO prediction ################# ### Callbacks ### ################# # saving weights every 10 epochs, because there is no way to properly early stop for WHEN network ############################### ### WHEN training generator ### ############################### # actual batchsize is 4*2=8 ################ ### Training ### ################ ############### ### Testing ### ############### # predictions from every 10 epochs # load weights of trained network # predict on testing set # load weights of trained network # predict on testing set
2.32619
2
remote/demo2.py
Jianglinhe/Spider
0
6612689
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ @Time: 19-6-4 上午9:37 @Author: hezhiqiang @FileName: demo2.py @IDE: PyCharm """ import requests headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' } # 设置带参数的请求 params = { 'wd': '中国' } response = requests.get(url='https://www.baidu.com/s', headers=headers, params=params) # s后面可以带?,也可以不带?,自动添加? print(response.request.url) # 查看请求的url地址 https://www.baidu.com/s?wd=%E4%B8%AD%E5%9B%BD 经过url编码的 resp = requests.get(url='https://www.baidu.com/s?wd={}'.format('中国'), headers=headers) # 使用字符串格式化的方法来实现url地址的拼接 print(resp.status_code) print(resp.request.url)
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ @Time: 19-6-4 上午9:37 @Author: hezhiqiang @FileName: demo2.py @IDE: PyCharm """ import requests headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' } # 设置带参数的请求 params = { 'wd': '中国' } response = requests.get(url='https://www.baidu.com/s', headers=headers, params=params) # s后面可以带?,也可以不带?,自动添加? print(response.request.url) # 查看请求的url地址 https://www.baidu.com/s?wd=%E4%B8%AD%E5%9B%BD 经过url编码的 resp = requests.get(url='https://www.baidu.com/s?wd={}'.format('中国'), headers=headers) # 使用字符串格式化的方法来实现url地址的拼接 print(resp.status_code) print(resp.request.url)
zh
0.652375
#!/usr/bin/env python3 # -*- coding:utf-8 -*- @Time: 19-6-4 上午9:37 @Author: hezhiqiang @FileName: demo2.py @IDE: PyCharm # 设置带参数的请求 # s后面可以带?,也可以不带?,自动添加? # 查看请求的url地址 https://www.baidu.com/s?wd=%E4%B8%AD%E5%9B%BD 经过url编码的 # 使用字符串格式化的方法来实现url地址的拼接
2.958637
3
hublib/ui/test/test_number.py
hzclarksm/hublib
6
6612690
<reponame>hzclarksm/hublib<gh_stars>1-10 from __future__ import print_function import pytest import sys import ipywidgets as widgets #----------------------------------------------------------------------------- # Utility stuff #----------------------------------------------------------------------------- from . import setup_test_comm, teardown_test_comm import hublib.ui as ui def setup(): setup_test_comm() def teardown(): teardown_test_comm() class TestNumber: @classmethod def setup_class(cls): setup_test_comm() @classmethod def teardown_class(cls): teardown_test_comm() def test_val(self): x = ui.Number( name='XX', desc='Mystery Parameter', units='m', min=0, max=10, value='5 m' ) assert x.value == 5 assert x.str == '5 m' x.value = '7.1 m' assert x.value == 7.1 assert x.str == '7.1 m' x.value = 0.2 assert x.value == 0.2 assert x.str == '0.2 m' def test_val2(self): # initial value has no units x = ui.Number( name='XX', desc='Mystery Parameter', units='m', min=0, max=10, value=5 ) assert x.value == 5 assert x.str == '5 m' x.value = '7.1 m' assert x.value == 7.1 assert x.str == '7.1 m' x.value = '0.2' assert x.value == 0.2 assert x.str == '0.2 m' def test_val_unitless(self): # Number without units x = ui.Number( name='XX', desc='Mystery Parameter', min=0, max=10, value=5 ) assert x.value == 5 assert x.str == '5' # simulate pressing enter x.cb('') assert x.value == 5 assert x.str == '5' x.value = 4.4 assert x.value == 4.4 assert x.str == '4.4' x.cb('') assert x.value == 4.4 assert x.str == '4.4' # try some bad values with pytest.raises(ValueError): x.value = '4 m' with pytest.raises(ValueError): x.value = 'foo' with pytest.raises(ValueError): x.value = None def test_val_no_minmax(self): # Number without units x = ui.Number( name='XX', desc='Mystery Parameter', value=5 ) x.value = 50000 assert x.value == 50000 assert x.str == '50000' x.value = -400000 assert x.value == -400000 assert x.str == '-400000' # try some bad values with pytest.raises(ValueError): x.value = '4 m' with pytest.raises(ValueError): x.value = 'foo' with pytest.raises(ValueError): x.value = None def test_val_convert(self): x = ui.Number( name='XX', desc='Mystery Parameter', units='m', min=0, max=10, value='5 m' ) x.value = '10 cm' assert x.value == 0.1 assert x.str == '0.1 m' def test_val_min(self): x = ui.Number( name='XX', desc='Mystery Parameter', units='m', min=5, max=10, value=8 ) with pytest.raises(ValueError): x.value = 1 with pytest.raises(ValueError): x.value = '1 m' # 500 cm = 5 m, so OK x.value = '500 cm' assert x.value == 5 # 499 cm NOT OK with pytest.raises(ValueError): x.value = '499 cm' def test_val_max(self): x = ui.Number( name='XX', desc='Mystery Parameter', units='m', min=5, max=10, value=8 ) with pytest.raises(ValueError): x.value = 10.001 with pytest.raises(ValueError): x.value = '11 m' # 1000 cm = 10 m, so OK x.value = '1000 cm' assert x.value == 10 # 1001 cm NOT OK with pytest.raises(ValueError): x.value = '1001 cm' def test_change_minmax(self): x = ui.Number( name='XX', desc='Mystery Parameter', units='m', min=5, max=10, value=8 ) assert x.min == 5 assert x.max == 10 x.min = 1 assert x.min == 1 x.max = 100 assert x.max == 100 def test_disable(self): x = ui.Number( name='XX', desc='Mystery Parameter', units='m', min=5, max=10, value=8 ) assert x.disabled is False x.disabled = True assert x.disabled is True x.disabled = False assert x.disabled is False
from __future__ import print_function import pytest import sys import ipywidgets as widgets #----------------------------------------------------------------------------- # Utility stuff #----------------------------------------------------------------------------- from . import setup_test_comm, teardown_test_comm import hublib.ui as ui def setup(): setup_test_comm() def teardown(): teardown_test_comm() class TestNumber: @classmethod def setup_class(cls): setup_test_comm() @classmethod def teardown_class(cls): teardown_test_comm() def test_val(self): x = ui.Number( name='XX', desc='Mystery Parameter', units='m', min=0, max=10, value='5 m' ) assert x.value == 5 assert x.str == '5 m' x.value = '7.1 m' assert x.value == 7.1 assert x.str == '7.1 m' x.value = 0.2 assert x.value == 0.2 assert x.str == '0.2 m' def test_val2(self): # initial value has no units x = ui.Number( name='XX', desc='Mystery Parameter', units='m', min=0, max=10, value=5 ) assert x.value == 5 assert x.str == '5 m' x.value = '7.1 m' assert x.value == 7.1 assert x.str == '7.1 m' x.value = '0.2' assert x.value == 0.2 assert x.str == '0.2 m' def test_val_unitless(self): # Number without units x = ui.Number( name='XX', desc='Mystery Parameter', min=0, max=10, value=5 ) assert x.value == 5 assert x.str == '5' # simulate pressing enter x.cb('') assert x.value == 5 assert x.str == '5' x.value = 4.4 assert x.value == 4.4 assert x.str == '4.4' x.cb('') assert x.value == 4.4 assert x.str == '4.4' # try some bad values with pytest.raises(ValueError): x.value = '4 m' with pytest.raises(ValueError): x.value = 'foo' with pytest.raises(ValueError): x.value = None def test_val_no_minmax(self): # Number without units x = ui.Number( name='XX', desc='Mystery Parameter', value=5 ) x.value = 50000 assert x.value == 50000 assert x.str == '50000' x.value = -400000 assert x.value == -400000 assert x.str == '-400000' # try some bad values with pytest.raises(ValueError): x.value = '4 m' with pytest.raises(ValueError): x.value = 'foo' with pytest.raises(ValueError): x.value = None def test_val_convert(self): x = ui.Number( name='XX', desc='Mystery Parameter', units='m', min=0, max=10, value='5 m' ) x.value = '10 cm' assert x.value == 0.1 assert x.str == '0.1 m' def test_val_min(self): x = ui.Number( name='XX', desc='Mystery Parameter', units='m', min=5, max=10, value=8 ) with pytest.raises(ValueError): x.value = 1 with pytest.raises(ValueError): x.value = '1 m' # 500 cm = 5 m, so OK x.value = '500 cm' assert x.value == 5 # 499 cm NOT OK with pytest.raises(ValueError): x.value = '499 cm' def test_val_max(self): x = ui.Number( name='XX', desc='Mystery Parameter', units='m', min=5, max=10, value=8 ) with pytest.raises(ValueError): x.value = 10.001 with pytest.raises(ValueError): x.value = '11 m' # 1000 cm = 10 m, so OK x.value = '1000 cm' assert x.value == 10 # 1001 cm NOT OK with pytest.raises(ValueError): x.value = '1001 cm' def test_change_minmax(self): x = ui.Number( name='XX', desc='Mystery Parameter', units='m', min=5, max=10, value=8 ) assert x.min == 5 assert x.max == 10 x.min = 1 assert x.min == 1 x.max = 100 assert x.max == 100 def test_disable(self): x = ui.Number( name='XX', desc='Mystery Parameter', units='m', min=5, max=10, value=8 ) assert x.disabled is False x.disabled = True assert x.disabled is True x.disabled = False assert x.disabled is False
en
0.311147
#----------------------------------------------------------------------------- # Utility stuff #----------------------------------------------------------------------------- # initial value has no units # Number without units # simulate pressing enter # try some bad values # Number without units # try some bad values # 500 cm = 5 m, so OK # 499 cm NOT OK # 1000 cm = 10 m, so OK # 1001 cm NOT OK
2.310595
2
pypptkit/main.py
veltzer/pypptkit
0
6612691
""" main entry point """ import pylogconf.core from pptx import Presentation from pptx.enum.shapes import MSO_SHAPE_TYPE from pytconf import register_endpoint, get_free_args, register_main, config_arg_parse_and_launch from pyvardump import dump_print from pypptkit.static import DESCRIPTION, APP_NAME, VERSION_STR from pypptkit.utils import get_sorted_refs, download @register_endpoint( allow_free_args=True, description="Extract text from ppt files", ) def extract_text() -> None: for filename in get_free_args(): presentation = Presentation(filename) for slide_number, slide in enumerate(presentation.slides): print(f"slide number {slide_number}") if slide.name != "": print(f"slide.name {slide.name}") # This block extracts hyperlinks for v in slide.part.rels.values(): target: str = v.target_ref if target.startswith(".."): continue print(v.target_ref) for shape in slide.shapes: # pylint: disable=no-member if shape.shape_type == MSO_SHAPE_TYPE.PLACEHOLDER: print(shape.shape_type) print(shape.text) if shape.shape_type == MSO_SHAPE_TYPE.TEXT_BOX: print(shape.shape_type) print(shape.text) if shape.shape_type == MSO_SHAPE_TYPE.TABLE: print(shape.shape_type) for row in shape.table.rows: for cell in row.cells: print(cell.text) @register_endpoint( allow_free_args=True, description="Extract links from ppt files", ) def extract_links() -> None: refs = get_sorted_refs(get_free_args()) for ref in refs: print(ref) @register_endpoint( allow_free_args=True, description="Download links from ppt files", ) def download_links() -> None: refs = get_sorted_refs(get_free_args()) for ref in refs: download(ref) @register_endpoint( allow_free_args=True, description="Dump object of ppt files", ) def dump_slides() -> None: for filename in get_free_args(): print(f"filename {filename}") presentation = Presentation(filename) for number, slide in enumerate(presentation.slides): print(f"slide {number}") dump_print(slide) @register_main( main_description=DESCRIPTION, app_name=APP_NAME, version=VERSION_STR, ) def main(): pylogconf.core.setup() config_arg_parse_and_launch() if __name__ == '__main__': main()
""" main entry point """ import pylogconf.core from pptx import Presentation from pptx.enum.shapes import MSO_SHAPE_TYPE from pytconf import register_endpoint, get_free_args, register_main, config_arg_parse_and_launch from pyvardump import dump_print from pypptkit.static import DESCRIPTION, APP_NAME, VERSION_STR from pypptkit.utils import get_sorted_refs, download @register_endpoint( allow_free_args=True, description="Extract text from ppt files", ) def extract_text() -> None: for filename in get_free_args(): presentation = Presentation(filename) for slide_number, slide in enumerate(presentation.slides): print(f"slide number {slide_number}") if slide.name != "": print(f"slide.name {slide.name}") # This block extracts hyperlinks for v in slide.part.rels.values(): target: str = v.target_ref if target.startswith(".."): continue print(v.target_ref) for shape in slide.shapes: # pylint: disable=no-member if shape.shape_type == MSO_SHAPE_TYPE.PLACEHOLDER: print(shape.shape_type) print(shape.text) if shape.shape_type == MSO_SHAPE_TYPE.TEXT_BOX: print(shape.shape_type) print(shape.text) if shape.shape_type == MSO_SHAPE_TYPE.TABLE: print(shape.shape_type) for row in shape.table.rows: for cell in row.cells: print(cell.text) @register_endpoint( allow_free_args=True, description="Extract links from ppt files", ) def extract_links() -> None: refs = get_sorted_refs(get_free_args()) for ref in refs: print(ref) @register_endpoint( allow_free_args=True, description="Download links from ppt files", ) def download_links() -> None: refs = get_sorted_refs(get_free_args()) for ref in refs: download(ref) @register_endpoint( allow_free_args=True, description="Dump object of ppt files", ) def dump_slides() -> None: for filename in get_free_args(): print(f"filename {filename}") presentation = Presentation(filename) for number, slide in enumerate(presentation.slides): print(f"slide {number}") dump_print(slide) @register_main( main_description=DESCRIPTION, app_name=APP_NAME, version=VERSION_STR, ) def main(): pylogconf.core.setup() config_arg_parse_and_launch() if __name__ == '__main__': main()
en
0.617765
main entry point # This block extracts hyperlinks # pylint: disable=no-member
2.516994
3
augmentation/datasets/custom/tfrecords.py
SaraR-1/model-patching
28
6612692
<filename>augmentation/datasets/custom/tfrecords.py import tensorflow as tf import os import augmentation.datasets.utils # Basic feature construction, taken from the tutorial on TFRecords def _bytestring_feature(list_of_bytestrings): return tf.train.Feature(bytes_list=tf.train.BytesList(value=list_of_bytestrings)) def _int_feature(list_of_ints): return tf.train.Feature(int64_list=tf.train.Int64List(value=list_of_ints)) def _float_feature(list_of_floats): return tf.train.Feature(float_list=tf.train.FloatList(value=list_of_floats)) def image_label_to_tfrecord(img_bytes, label): # Construct a TFRecord Example using an (image, label) pair feature = {"image": _bytestring_feature([img_bytes]), "label": _int_feature([int(label)])} return tf.train.Example(features=tf.train.Features(feature=feature)) def read_image_label_tfrecord(example, batched=True, parallelism=8): # Read a TFRecord Example that contains an (image, label) pair features = {"image": tf.io.FixedLenFeature([], tf.string), "label": tf.io.FixedLenFeature([], tf.int64)} if batched: # Parse the TFRecord example = tf.io.parse_example(example, features) # Decode the image image = tf.map_fn(augmentation.datasets.utils.decode_raw_image, example['image'], dtype=tf.uint8, back_prop=False, parallel_iterations=parallelism) else: # Parse the TFRecord example = tf.io.parse_single_example(example, features) # Decode the image image = augmentation.datasets.utils.decode_raw_image(example['image']) # Get all the other tags label = example['label'] return image, label
<filename>augmentation/datasets/custom/tfrecords.py import tensorflow as tf import os import augmentation.datasets.utils # Basic feature construction, taken from the tutorial on TFRecords def _bytestring_feature(list_of_bytestrings): return tf.train.Feature(bytes_list=tf.train.BytesList(value=list_of_bytestrings)) def _int_feature(list_of_ints): return tf.train.Feature(int64_list=tf.train.Int64List(value=list_of_ints)) def _float_feature(list_of_floats): return tf.train.Feature(float_list=tf.train.FloatList(value=list_of_floats)) def image_label_to_tfrecord(img_bytes, label): # Construct a TFRecord Example using an (image, label) pair feature = {"image": _bytestring_feature([img_bytes]), "label": _int_feature([int(label)])} return tf.train.Example(features=tf.train.Features(feature=feature)) def read_image_label_tfrecord(example, batched=True, parallelism=8): # Read a TFRecord Example that contains an (image, label) pair features = {"image": tf.io.FixedLenFeature([], tf.string), "label": tf.io.FixedLenFeature([], tf.int64)} if batched: # Parse the TFRecord example = tf.io.parse_example(example, features) # Decode the image image = tf.map_fn(augmentation.datasets.utils.decode_raw_image, example['image'], dtype=tf.uint8, back_prop=False, parallel_iterations=parallelism) else: # Parse the TFRecord example = tf.io.parse_single_example(example, features) # Decode the image image = augmentation.datasets.utils.decode_raw_image(example['image']) # Get all the other tags label = example['label'] return image, label
en
0.63269
# Basic feature construction, taken from the tutorial on TFRecords # Construct a TFRecord Example using an (image, label) pair # Read a TFRecord Example that contains an (image, label) pair # Parse the TFRecord # Decode the image # Parse the TFRecord # Decode the image # Get all the other tags
3.141407
3
checker/fault.py
mezgoodle/numericalMethods_labs
1
6612693
from math import sqrt def get_fault(x: list, xm: list) -> float: """ Function for finding get_fault :param x: my solution vector :param xm: NumPy solution vector :return: fault """ sum_k = 0 n = len(x) for k in range(1, n): sum_k += (x[k] - xm[k]) ** 2 result = sqrt(sum_k / n) return result
from math import sqrt def get_fault(x: list, xm: list) -> float: """ Function for finding get_fault :param x: my solution vector :param xm: NumPy solution vector :return: fault """ sum_k = 0 n = len(x) for k in range(1, n): sum_k += (x[k] - xm[k]) ** 2 result = sqrt(sum_k / n) return result
en
0.617049
Function for finding get_fault :param x: my solution vector :param xm: NumPy solution vector :return: fault
3.786966
4
tests/common/test_local_file.py
abeja-inc/abeja-platform-sdk
2
6612694
<reponame>abeja-inc/abeja-platform-sdk<filename>tests/common/test_local_file.py from abeja.common import local_file from abeja.common.local_file import use_text_cache, use_binary_cache, use_iter_content_cache, use_iter_lines_cache from abeja.common.config import DEFAULT_CHUNK_SIZE import pytest import secrets import errno from functools import partial import builtins ORIGINAL_OPEN = builtins.open class MockIO: def __init__(self, file, raise_stale=False): self.file = file self.raise_stale = raise_stale def read(self, size=-1): if self.raise_stale: raise OSError(errno.ESTALE, 'Stale file handle') else: return self.file.read(size) def __iter__(self): return self def __next__(self): if self.raise_stale: raise OSError(errno.ESTALE, 'Stale file handle') else: line = self.file.readline() if line == '': raise StopIteration() else: return line def __enter__(self): self.file.__enter__() return self def __exit__(self, exc_type, exc_value, traceback): return self.file.__exit__(exc_type, exc_value, traceback) def mock_open_factory(): global first_invocation first_invocation = True def mock_open(path, mode): global first_invocation if mode.startswith('r'): raise_stale = first_invocation first_invocation = False return MockIO(ORIGINAL_OPEN(path, mode), raise_stale=raise_stale) else: return ORIGINAL_OPEN(path, mode) return mock_open class SourceURI: def __init__(self, uri: str) -> None: self.uri = uri @pytest.fixture def mount_dir(monkeypatch, tmpdir): monkeypatch.setattr(local_file, 'MOUNT_DIR', str(tmpdir)) return tmpdir @pytest.fixture def fake_file_factory(mount_dir, tmp_path): def factory(content): filename = 'testfile' obj = SourceURI(f'http://example.com/files/{filename}') original = tmp_path / filename if isinstance(content, str): mode = 'r' original.write_text(content) else: mode = 'rb' original.write_bytes(content) return open(str(original), mode), obj return factory @pytest.fixture def read_file_factory(fake_file_factory, monkeypatch): def factory(cache_func, content): f, obj = fake_file_factory(content) with f: decorated = cache_func(f.read) with monkeypatch.context() as m: m.setattr(builtins, 'open', mock_open_factory()) return decorated(obj), decorated(obj) return factory @pytest.fixture def read_iter_factory(fake_file_factory, monkeypatch): def factory(cache_func, content): f, obj = fake_file_factory(content) def make_iter(chunk_size=DEFAULT_CHUNK_SIZE): sentinel = '' if isinstance(content, str) else b'' return iter(partial(f.read, chunk_size), sentinel) # We don't test raising "Stale file handle" error for iterator with f: decorated = cache_func(make_iter) return decorated(obj), decorated(obj) return factory def test_use_text_cache(read_file_factory): content = 'Hello, World!' saved, cached = read_file_factory(use_text_cache, content) assert saved == content assert cached == content def test_use_binary_cache(read_file_factory): content = b'test' saved, cached = read_file_factory(use_binary_cache, content) assert saved == content assert cached == content def test_use_iter_content_cache(read_iter_factory): content = secrets.token_bytes(int(DEFAULT_CHUNK_SIZE * 3.7)) saved, cached = read_iter_factory(use_iter_content_cache, content) assert b''.join(list(saved)) == content assert b''.join(list(cached)) == content def test_use_iter_lines_cache(read_iter_factory): content = '1\n2\n3' saved, cached = read_iter_factory(use_iter_lines_cache, content) assert list(saved) == ['1\n', '2\n', '3'] assert list(cached) == ['1\n', '2\n', '3']
from abeja.common import local_file from abeja.common.local_file import use_text_cache, use_binary_cache, use_iter_content_cache, use_iter_lines_cache from abeja.common.config import DEFAULT_CHUNK_SIZE import pytest import secrets import errno from functools import partial import builtins ORIGINAL_OPEN = builtins.open class MockIO: def __init__(self, file, raise_stale=False): self.file = file self.raise_stale = raise_stale def read(self, size=-1): if self.raise_stale: raise OSError(errno.ESTALE, 'Stale file handle') else: return self.file.read(size) def __iter__(self): return self def __next__(self): if self.raise_stale: raise OSError(errno.ESTALE, 'Stale file handle') else: line = self.file.readline() if line == '': raise StopIteration() else: return line def __enter__(self): self.file.__enter__() return self def __exit__(self, exc_type, exc_value, traceback): return self.file.__exit__(exc_type, exc_value, traceback) def mock_open_factory(): global first_invocation first_invocation = True def mock_open(path, mode): global first_invocation if mode.startswith('r'): raise_stale = first_invocation first_invocation = False return MockIO(ORIGINAL_OPEN(path, mode), raise_stale=raise_stale) else: return ORIGINAL_OPEN(path, mode) return mock_open class SourceURI: def __init__(self, uri: str) -> None: self.uri = uri @pytest.fixture def mount_dir(monkeypatch, tmpdir): monkeypatch.setattr(local_file, 'MOUNT_DIR', str(tmpdir)) return tmpdir @pytest.fixture def fake_file_factory(mount_dir, tmp_path): def factory(content): filename = 'testfile' obj = SourceURI(f'http://example.com/files/{filename}') original = tmp_path / filename if isinstance(content, str): mode = 'r' original.write_text(content) else: mode = 'rb' original.write_bytes(content) return open(str(original), mode), obj return factory @pytest.fixture def read_file_factory(fake_file_factory, monkeypatch): def factory(cache_func, content): f, obj = fake_file_factory(content) with f: decorated = cache_func(f.read) with monkeypatch.context() as m: m.setattr(builtins, 'open', mock_open_factory()) return decorated(obj), decorated(obj) return factory @pytest.fixture def read_iter_factory(fake_file_factory, monkeypatch): def factory(cache_func, content): f, obj = fake_file_factory(content) def make_iter(chunk_size=DEFAULT_CHUNK_SIZE): sentinel = '' if isinstance(content, str) else b'' return iter(partial(f.read, chunk_size), sentinel) # We don't test raising "Stale file handle" error for iterator with f: decorated = cache_func(make_iter) return decorated(obj), decorated(obj) return factory def test_use_text_cache(read_file_factory): content = 'Hello, World!' saved, cached = read_file_factory(use_text_cache, content) assert saved == content assert cached == content def test_use_binary_cache(read_file_factory): content = b'test' saved, cached = read_file_factory(use_binary_cache, content) assert saved == content assert cached == content def test_use_iter_content_cache(read_iter_factory): content = secrets.token_bytes(int(DEFAULT_CHUNK_SIZE * 3.7)) saved, cached = read_iter_factory(use_iter_content_cache, content) assert b''.join(list(saved)) == content assert b''.join(list(cached)) == content def test_use_iter_lines_cache(read_iter_factory): content = '1\n2\n3' saved, cached = read_iter_factory(use_iter_lines_cache, content) assert list(saved) == ['1\n', '2\n', '3'] assert list(cached) == ['1\n', '2\n', '3']
en
0.821992
# We don't test raising "Stale file handle" error for iterator
1.851533
2
collection-processing/MIR-1K_fileprocessing/mir-1k_fileprocessing.py
unmix-io/tools
1
6612695
<reponame>unmix-io/tools """ Filreader enriching files with synonyms out of wordnet """ import sys from os import listdir, rename, makedirs, remove from os.path import join, isfile, dirname, exists import shutil from pydub import AudioSegment import subprocess __author__ = "<EMAIL>" temp_path = "./temp" #Beispiel ffmpeg mp4 streams auftrennen und zusammenmergen: ffmpeg -i test.mp4 -filter_complex "[0:1][0:2]amerge=inputs=2[ab]" -map [ab] 1.wav #Hier wurden streams 2 und 3 gemerged def normalize(file, destination, db = -20.0): def match_target_amplitude(sound, target_dBFS): change_in_dBFS = target_dBFS - sound.dBFS return sound.apply_gain(change_in_dBFS) sound = AudioSegment.from_file(file, "wav") normalized_sound = match_target_amplitude(sound, db) normalized_sound.export(destination, format="wav") def calculate_ratio_instr_vocs(instr, voc): instrlevel = AudioSegment.from_file(instr, "wav").dBFS voclevel = AudioSegment.from_file(voc, "wav").dBFS targetDB_VOC = -20 + (-20 * (voclevel / instrlevel - 1)) return targetDB_VOC def copy_files(sourcedir, outputdir, maxCopy, override): src_files= listdir(sourcedir) for file in src_files: if maxCopy == 0: break old_file = join(sourcedir, file) new_folder = join(outputdir, file) new_songname_instr = 'instrumental_' + file new_songname_vocals = 'vocals_' + file new_songfile_instr = join(new_folder, new_songname_instr) new_songfile_vocals = join(new_folder, new_songname_vocals) if not exists(new_folder): makedirs(new_folder) if exists(new_songfile_instr) and override: remove(new_songfile_instr) if exists(new_songfile_vocals) and override: remove(new_songfile_vocals) if (not exists(new_songfile_vocals) and not exists(new_songfile_instr)) or override: cmd = "ffmpeg -i \"" + old_file + "\" -filter_complex \"[0:a]channelsplit=channel_layout=stereo[l][r]\" -map [l] -ac 2 -ar 44100 \"" + join(temp_path, new_songname_instr) + "\" -map [r] -ac 2 -ar 44100 \"" + join(temp_path, new_songname_vocals) + "\"" subprocess.check_call(cmd, shell=True) # cwd = cwd vocal_volume = calculate_ratio_instr_vocs(join(temp_path, new_songname_instr), join(temp_path, new_songname_vocals)) normalize(join(temp_path, new_songname_instr), new_songfile_instr, -20) normalize(join(temp_path, new_songname_vocals), new_songfile_vocals, vocal_volume) print("\n" + new_songname_vocals + " and " + new_songname_instr + " converted" + "\n") remove(join(temp_path, new_songname_vocals)) remove(join(temp_path, new_songname_instr)) maxCopy -= 1 if __name__ == '__main__': #Call script with scriptname maxfiles override #Example call: musdb18_fileprocessing.py 20 True #This will convert the first twenty files in the source dir and override already existing files in the outputdir maxCopy = -1 override = True unmix_server = '//192.168.1.29/unmix-server' print('Argument List:', str(sys.argv)) if sys.argv.__len__() == 2: unmix_server = sys.argv[1] sources = unmix_server + "/1_sources/MIR-1K/UndividedWavfile" destination = unmix_server + "/2_prepared/MIR-1K" if not exists(temp_path): makedirs(temp_path) copy_files(sources, destination, maxCopy, override) print('Finished converting')
""" Filreader enriching files with synonyms out of wordnet """ import sys from os import listdir, rename, makedirs, remove from os.path import join, isfile, dirname, exists import shutil from pydub import AudioSegment import subprocess __author__ = "<EMAIL>" temp_path = "./temp" #Beispiel ffmpeg mp4 streams auftrennen und zusammenmergen: ffmpeg -i test.mp4 -filter_complex "[0:1][0:2]amerge=inputs=2[ab]" -map [ab] 1.wav #Hier wurden streams 2 und 3 gemerged def normalize(file, destination, db = -20.0): def match_target_amplitude(sound, target_dBFS): change_in_dBFS = target_dBFS - sound.dBFS return sound.apply_gain(change_in_dBFS) sound = AudioSegment.from_file(file, "wav") normalized_sound = match_target_amplitude(sound, db) normalized_sound.export(destination, format="wav") def calculate_ratio_instr_vocs(instr, voc): instrlevel = AudioSegment.from_file(instr, "wav").dBFS voclevel = AudioSegment.from_file(voc, "wav").dBFS targetDB_VOC = -20 + (-20 * (voclevel / instrlevel - 1)) return targetDB_VOC def copy_files(sourcedir, outputdir, maxCopy, override): src_files= listdir(sourcedir) for file in src_files: if maxCopy == 0: break old_file = join(sourcedir, file) new_folder = join(outputdir, file) new_songname_instr = 'instrumental_' + file new_songname_vocals = 'vocals_' + file new_songfile_instr = join(new_folder, new_songname_instr) new_songfile_vocals = join(new_folder, new_songname_vocals) if not exists(new_folder): makedirs(new_folder) if exists(new_songfile_instr) and override: remove(new_songfile_instr) if exists(new_songfile_vocals) and override: remove(new_songfile_vocals) if (not exists(new_songfile_vocals) and not exists(new_songfile_instr)) or override: cmd = "ffmpeg -i \"" + old_file + "\" -filter_complex \"[0:a]channelsplit=channel_layout=stereo[l][r]\" -map [l] -ac 2 -ar 44100 \"" + join(temp_path, new_songname_instr) + "\" -map [r] -ac 2 -ar 44100 \"" + join(temp_path, new_songname_vocals) + "\"" subprocess.check_call(cmd, shell=True) # cwd = cwd vocal_volume = calculate_ratio_instr_vocs(join(temp_path, new_songname_instr), join(temp_path, new_songname_vocals)) normalize(join(temp_path, new_songname_instr), new_songfile_instr, -20) normalize(join(temp_path, new_songname_vocals), new_songfile_vocals, vocal_volume) print("\n" + new_songname_vocals + " and " + new_songname_instr + " converted" + "\n") remove(join(temp_path, new_songname_vocals)) remove(join(temp_path, new_songname_instr)) maxCopy -= 1 if __name__ == '__main__': #Call script with scriptname maxfiles override #Example call: musdb18_fileprocessing.py 20 True #This will convert the first twenty files in the source dir and override already existing files in the outputdir maxCopy = -1 override = True unmix_server = '//192.168.1.29/unmix-server' print('Argument List:', str(sys.argv)) if sys.argv.__len__() == 2: unmix_server = sys.argv[1] sources = unmix_server + "/1_sources/MIR-1K/UndividedWavfile" destination = unmix_server + "/2_prepared/MIR-1K" if not exists(temp_path): makedirs(temp_path) copy_files(sources, destination, maxCopy, override) print('Finished converting')
de
0.284266
Filreader enriching files with synonyms out of wordnet #Beispiel ffmpeg mp4 streams auftrennen und zusammenmergen: ffmpeg -i test.mp4 -filter_complex "[0:1][0:2]amerge=inputs=2[ab]" -map [ab] 1.wav #Hier wurden streams 2 und 3 gemerged # cwd = cwd #Call script with scriptname maxfiles override #Example call: musdb18_fileprocessing.py 20 True #This will convert the first twenty files in the source dir and override already existing files in the outputdir
2.554904
3
pythosf/client/api_detail.py
felliott/pythosf
1
6612696
<reponame>felliott/pythosf from ..utils import save_attribute_items, unwrap_data class APIDetail: def __init__(self, session, data=None, wb_data=None): self.session = session if data is not None: self._update(response=data) def _update(self, response): response_data = unwrap_data(response) if response_data: if 'attributes' in response_data: response_attributes = response_data['attributes'] else: response_attributes = response_data save_attribute_items(self, response_attributes=response_attributes) self.id = response_data.get('id', None) self.relationships = TopLevelData( response=response, tld_key='relationships') self.links = TopLevelData(response=response, tld_key='links') self.meta = TopLevelData(response=response, tld_key='meta') class TopLevelData: def __init__(self, response, tld_key): self.update(response=response, tld_key=tld_key) def update(self, response, tld_key): tld_data = unwrap_data(response) if tld_data: tld = tld_data.get(tld_key, None) if tld: save_attribute_items(self, response_attributes=tld)
from ..utils import save_attribute_items, unwrap_data class APIDetail: def __init__(self, session, data=None, wb_data=None): self.session = session if data is not None: self._update(response=data) def _update(self, response): response_data = unwrap_data(response) if response_data: if 'attributes' in response_data: response_attributes = response_data['attributes'] else: response_attributes = response_data save_attribute_items(self, response_attributes=response_attributes) self.id = response_data.get('id', None) self.relationships = TopLevelData( response=response, tld_key='relationships') self.links = TopLevelData(response=response, tld_key='links') self.meta = TopLevelData(response=response, tld_key='meta') class TopLevelData: def __init__(self, response, tld_key): self.update(response=response, tld_key=tld_key) def update(self, response, tld_key): tld_data = unwrap_data(response) if tld_data: tld = tld_data.get(tld_key, None) if tld: save_attribute_items(self, response_attributes=tld)
none
1
2.555096
3
src/script.py
DeveloperZoneIO/homebrew-template-builder
1
6612697
# Copyright (c) 2021 <NAME> from variable import Variable class Script: def __init__(self, script): self.script = script def execute(self, variables): scriptVariables = {} for var in variables: scriptVariables[var.name] = var.value exec(self.script, scriptVariables) extendedVariables = [] for key, value in scriptVariables.items(): if key != '__builtins__': variable = Variable(key, '') variable.value = value extendedVariables.append(variable) return extendedVariables
# Copyright (c) 2021 <NAME> from variable import Variable class Script: def __init__(self, script): self.script = script def execute(self, variables): scriptVariables = {} for var in variables: scriptVariables[var.name] = var.value exec(self.script, scriptVariables) extendedVariables = [] for key, value in scriptVariables.items(): if key != '__builtins__': variable = Variable(key, '') variable.value = value extendedVariables.append(variable) return extendedVariables
en
0.709196
# Copyright (c) 2021 <NAME>
2.875642
3
occuprob/io.py
luis-galvez/OccuProb
0
6612698
<reponame>luis-galvez/OccuProb """ Input and output functions """ # MIT License # Copyright (c) 2021-2022 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import numpy as np from ase.io import read from pymatgen.core.structure import Molecule from pymatgen.symmetry.analyzer import PointGroupAnalyzer import matplotlib.pyplot as plt def calc_symmetry_order(ase_atoms): """ Calculates the order of the rotational subgroup of the symmetry point group of each structure contained in the input ASE atoms object. Parameters ---------- ase_atoms : :obj:`ASE Atoms object` Input ASE Atoms object containing the molecule to analyze. Returns ------- symmetry_order : float Order of the rotational subgroup of the symmetry point group of the input molecule. """ symbols = ase_atoms.get_chemical_symbols() positions = ase_atoms.get_positions() molecule = Molecule(symbols, positions) point_group = PointGroupAnalyzer(molecule, eigen_tolerance=0.01) symmetry_matrices = np.array([matrix.as_dict()['matrix'] for matrix in point_group.get_symmetry_operations()]) symmetry_matrices_det = np.linalg.det(symmetry_matrices) symmetry_order = np.count_nonzero(symmetry_matrices_det > 0) return symmetry_order def load_properties_from_extxyz(xyz_filename): """ Reads isomer properties (energy, spin_multiplicity, frequencies and coordinates) from Extended XYZ files. Parameters ---------- xyz_filename : string Name of the Extended XYZ filename containing the coordinates of each isomer and their properties. Returns ------- properties : dict Dictionary that maps each key to the correspoding property of each isomer in the input file. """ isomers = read(xyz_filename, index=':') energies = [] spin_multiplicity = [] frequencies = [] moments_of_inertia = [] symmetry_order = [] # Reads the values from the input file for atoms in isomers: energies.append(atoms.info['Energy']) spin_multiplicity.append(atoms.info['Multiplicity']) frequencies.append(atoms.info['Frequencies'].flatten(order='F')) moments_of_inertia.append(atoms.get_moments_of_inertia()) symmetry_order.append(calc_symmetry_order(atoms)) properties = {'energy': np.stack(energies), 'multiplicity': np.stack(spin_multiplicity), 'frequencies': np.stack(frequencies).astype(np.longdouble), 'moments': np.stack(moments_of_inertia), 'symmetry': np.stack(symmetry_order)} return properties def plot_results(results, temperature, outfile, **plot_format): """ Function to plot the occupation probability, heat capacity or ensemble- averaged properties. Parameters ---------- results : :obj:`numpy.ndarray` A 2D array shape (N, M) containing the data to be plotted. temperature : :obj:`numpy.ndarray` A 1D array of size M containing the temperature values in K. outfile : string Output filename. plot_format : dict Dictionary containing parameters for the figure format. """ labels = plot_format['labels'] if 'labels' in plot_format else None ylabel = plot_format['ylabel'] if 'ylabel' in plot_format else None ylims = plot_format['ylims'] if 'ylims' in plot_format else None size = plot_format['size'] if 'size' in plot_format else (8., 6.) linewidth = plot_format['linewidth'] if 'linewidth' in plot_format else 2 hline_pos = plot_format['hline_pos'] if 'hline_pos' in plot_format else [] plt.figure(figsize=size) plt.xlabel(r'$T$ [K]') plt.ylabel(ylabel) xmin, xmax = temperature[0], temperature[-1] for position in hline_pos: plt.hlines(position, xmin, xmax, colors='silver', linestyles='--', lw=2) for i, result in enumerate(results): if labels: plt.plot(temperature, result, label=labels[i], lw=linewidth) else: plt.plot(temperature, result, lw=linewidth) plt.xlim((xmin, xmax)) plt.ylim(ylims) if labels: plt.legend() plt.tight_layout() plt.savefig(outfile)
""" Input and output functions """ # MIT License # Copyright (c) 2021-2022 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import numpy as np from ase.io import read from pymatgen.core.structure import Molecule from pymatgen.symmetry.analyzer import PointGroupAnalyzer import matplotlib.pyplot as plt def calc_symmetry_order(ase_atoms): """ Calculates the order of the rotational subgroup of the symmetry point group of each structure contained in the input ASE atoms object. Parameters ---------- ase_atoms : :obj:`ASE Atoms object` Input ASE Atoms object containing the molecule to analyze. Returns ------- symmetry_order : float Order of the rotational subgroup of the symmetry point group of the input molecule. """ symbols = ase_atoms.get_chemical_symbols() positions = ase_atoms.get_positions() molecule = Molecule(symbols, positions) point_group = PointGroupAnalyzer(molecule, eigen_tolerance=0.01) symmetry_matrices = np.array([matrix.as_dict()['matrix'] for matrix in point_group.get_symmetry_operations()]) symmetry_matrices_det = np.linalg.det(symmetry_matrices) symmetry_order = np.count_nonzero(symmetry_matrices_det > 0) return symmetry_order def load_properties_from_extxyz(xyz_filename): """ Reads isomer properties (energy, spin_multiplicity, frequencies and coordinates) from Extended XYZ files. Parameters ---------- xyz_filename : string Name of the Extended XYZ filename containing the coordinates of each isomer and their properties. Returns ------- properties : dict Dictionary that maps each key to the correspoding property of each isomer in the input file. """ isomers = read(xyz_filename, index=':') energies = [] spin_multiplicity = [] frequencies = [] moments_of_inertia = [] symmetry_order = [] # Reads the values from the input file for atoms in isomers: energies.append(atoms.info['Energy']) spin_multiplicity.append(atoms.info['Multiplicity']) frequencies.append(atoms.info['Frequencies'].flatten(order='F')) moments_of_inertia.append(atoms.get_moments_of_inertia()) symmetry_order.append(calc_symmetry_order(atoms)) properties = {'energy': np.stack(energies), 'multiplicity': np.stack(spin_multiplicity), 'frequencies': np.stack(frequencies).astype(np.longdouble), 'moments': np.stack(moments_of_inertia), 'symmetry': np.stack(symmetry_order)} return properties def plot_results(results, temperature, outfile, **plot_format): """ Function to plot the occupation probability, heat capacity or ensemble- averaged properties. Parameters ---------- results : :obj:`numpy.ndarray` A 2D array shape (N, M) containing the data to be plotted. temperature : :obj:`numpy.ndarray` A 1D array of size M containing the temperature values in K. outfile : string Output filename. plot_format : dict Dictionary containing parameters for the figure format. """ labels = plot_format['labels'] if 'labels' in plot_format else None ylabel = plot_format['ylabel'] if 'ylabel' in plot_format else None ylims = plot_format['ylims'] if 'ylims' in plot_format else None size = plot_format['size'] if 'size' in plot_format else (8., 6.) linewidth = plot_format['linewidth'] if 'linewidth' in plot_format else 2 hline_pos = plot_format['hline_pos'] if 'hline_pos' in plot_format else [] plt.figure(figsize=size) plt.xlabel(r'$T$ [K]') plt.ylabel(ylabel) xmin, xmax = temperature[0], temperature[-1] for position in hline_pos: plt.hlines(position, xmin, xmax, colors='silver', linestyles='--', lw=2) for i, result in enumerate(results): if labels: plt.plot(temperature, result, label=labels[i], lw=linewidth) else: plt.plot(temperature, result, lw=linewidth) plt.xlim((xmin, xmax)) plt.ylim(ylims) if labels: plt.legend() plt.tight_layout() plt.savefig(outfile)
en
0.676202
Input and output functions # MIT License # Copyright (c) 2021-2022 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. Calculates the order of the rotational subgroup of the symmetry point group of each structure contained in the input ASE atoms object. Parameters ---------- ase_atoms : :obj:`ASE Atoms object` Input ASE Atoms object containing the molecule to analyze. Returns ------- symmetry_order : float Order of the rotational subgroup of the symmetry point group of the input molecule. Reads isomer properties (energy, spin_multiplicity, frequencies and coordinates) from Extended XYZ files. Parameters ---------- xyz_filename : string Name of the Extended XYZ filename containing the coordinates of each isomer and their properties. Returns ------- properties : dict Dictionary that maps each key to the correspoding property of each isomer in the input file. # Reads the values from the input file Function to plot the occupation probability, heat capacity or ensemble- averaged properties. Parameters ---------- results : :obj:`numpy.ndarray` A 2D array shape (N, M) containing the data to be plotted. temperature : :obj:`numpy.ndarray` A 1D array of size M containing the temperature values in K. outfile : string Output filename. plot_format : dict Dictionary containing parameters for the figure format.
2.29776
2
app/blog/serializers.py
coocostory/vue-django-restful-blog
3
6612699
<gh_stars>1-10 from rest_framework import serializers from .models import Blog, Comment, Course, Coursedetail class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = "__all__" class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = "__all__" class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = "__all__" class CoursedetailSerializer(serializers.ModelSerializer): class Meta: model = Coursedetail fields = "__all__"
from rest_framework import serializers from .models import Blog, Comment, Course, Coursedetail class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = "__all__" class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = "__all__" class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = "__all__" class CoursedetailSerializer(serializers.ModelSerializer): class Meta: model = Coursedetail fields = "__all__"
none
1
2.262391
2
tests/integration/benchmark_runner/common/elasticsearch/test_es_operations.py
jeniferh/benchmark-runner
0
6612700
import pytest from uuid import uuid4 from benchmark_runner.common.oc.oc import OC from benchmark_runner.common.elasticsearch.es_operations import ESOperations from benchmark_runner.common.elasticsearch.elasticsearch_exceptions import ElasticSearchDataNotUploaded from benchmark_runner.main.update_data_template_yaml_with_environment_variables import delete_generate_file, \ update_environment_variable from benchmark_runner.benchmark_operator.benchmark_operator_workloads import BenchmarkOperatorWorkloads from tests.integration.benchmark_runner.test_environment_variables import * def __generate_pod_yamls(): """ This method create pod yaml from template and inject environment variable inside :return: """ update_environment_variable(dir_path=templates_path, yaml_file='stressng_pod_template.yaml', environment_variable_dict=test_environment_variable) def __delete_pod_yamls(): """ This method delete benchmark_operator :return: """ oc = OC(kubeadmin_password=test_environment_variable['kubeadmin_password']) oc.login() if oc._is_pod_exist(pod_name='stressng-pod-workload', namespace=test_environment_variable['namespace']): oc.delete_pod_sync(yaml=os.path.join(f'{templates_path}', 'stressng_pod.yaml'), pod_name='stressng-pod-workload') delete_generate_file(full_path_yaml=os.path.join(f'{templates_path}', 'stressng_pod.yaml')) @pytest.fixture(scope="session", autouse=True) def before_after_all_tests_fixture(): """ This method is create benchmark operator pod once for ALL tests :return: """ print('Install benchmark-operator pod') # delete benchmark-operator pod if exist benchmark_operator = BenchmarkOperatorWorkloads(kubeadmin_password=test_environment_variable['kubeadmin_password'], es_host=test_environment_variable['elasticsearch'], es_port=test_environment_variable['elasticsearch_port']) benchmark_operator.make_undeploy_benchmark_controller_manager_if_exist(runner_path=test_environment_variable['runner_path']) benchmark_operator.make_deploy_benchmark_controller_manager(runner_path=test_environment_variable['runner_path']) yield print('Delete benchmark-operator pod') benchmark_operator.make_undeploy_benchmark_controller_manager(runner_path=test_environment_variable['runner_path']) @pytest.fixture(autouse=True) def before_after_each_test_fixture(): """ This method is clearing yaml before and after EACH test :return: """ # before each test __generate_pod_yamls() yield # After all tests __delete_pod_yamls() print('Test End') def test_verify_es_data_uploaded_stressng_pod(): """ This method verify that the data upload properly to elasticsearch :return: """ oc = OC(kubeadmin_password=test_environment_variable['kubeadmin_password']) oc.login() try: workload = 'stressng-pod' oc.create_pod_sync(yaml=os.path.join(f'{templates_path}', 'stressng_pod.yaml'), pod_name=f'{workload}-workload') oc.wait_for_initialized(label='app=stressng_workload', workload=workload) oc.wait_for_ready(label='app=stressng_workload', workload=workload) oc.wait_for_pod_completed(label='app=stressng_workload', workload=workload) # system-metrics if test_environment_variable['system_metrics'] == 'True': es = ESOperations(es_host=test_environment_variable['elasticsearch'], es_port=test_environment_variable['elasticsearch_port']) assert oc.wait_for_pod_create(pod_name='system-metrics-collector') assert oc.wait_for_initialized(label='app=system-metrics-collector', workload=workload) assert oc.wait_for_pod_completed(label='app=system-metrics-collector', workload=workload) assert es.verify_es_data_uploaded(index='system-metrics-test', uuid=oc.get_long_uuid(workload=workload)) if test_environment_variable['elasticsearch']: # verify that data upload to elastic search es = ESOperations(es_host=test_environment_variable['elasticsearch'], es_port=test_environment_variable['elasticsearch_port']) assert es.verify_es_data_uploaded(index='stressng-pod-test-results', uuid=oc.get_long_uuid(workload=workload)) except ElasticSearchDataNotUploaded as err: raise err except Exception as err: raise err
import pytest from uuid import uuid4 from benchmark_runner.common.oc.oc import OC from benchmark_runner.common.elasticsearch.es_operations import ESOperations from benchmark_runner.common.elasticsearch.elasticsearch_exceptions import ElasticSearchDataNotUploaded from benchmark_runner.main.update_data_template_yaml_with_environment_variables import delete_generate_file, \ update_environment_variable from benchmark_runner.benchmark_operator.benchmark_operator_workloads import BenchmarkOperatorWorkloads from tests.integration.benchmark_runner.test_environment_variables import * def __generate_pod_yamls(): """ This method create pod yaml from template and inject environment variable inside :return: """ update_environment_variable(dir_path=templates_path, yaml_file='stressng_pod_template.yaml', environment_variable_dict=test_environment_variable) def __delete_pod_yamls(): """ This method delete benchmark_operator :return: """ oc = OC(kubeadmin_password=test_environment_variable['kubeadmin_password']) oc.login() if oc._is_pod_exist(pod_name='stressng-pod-workload', namespace=test_environment_variable['namespace']): oc.delete_pod_sync(yaml=os.path.join(f'{templates_path}', 'stressng_pod.yaml'), pod_name='stressng-pod-workload') delete_generate_file(full_path_yaml=os.path.join(f'{templates_path}', 'stressng_pod.yaml')) @pytest.fixture(scope="session", autouse=True) def before_after_all_tests_fixture(): """ This method is create benchmark operator pod once for ALL tests :return: """ print('Install benchmark-operator pod') # delete benchmark-operator pod if exist benchmark_operator = BenchmarkOperatorWorkloads(kubeadmin_password=test_environment_variable['kubeadmin_password'], es_host=test_environment_variable['elasticsearch'], es_port=test_environment_variable['elasticsearch_port']) benchmark_operator.make_undeploy_benchmark_controller_manager_if_exist(runner_path=test_environment_variable['runner_path']) benchmark_operator.make_deploy_benchmark_controller_manager(runner_path=test_environment_variable['runner_path']) yield print('Delete benchmark-operator pod') benchmark_operator.make_undeploy_benchmark_controller_manager(runner_path=test_environment_variable['runner_path']) @pytest.fixture(autouse=True) def before_after_each_test_fixture(): """ This method is clearing yaml before and after EACH test :return: """ # before each test __generate_pod_yamls() yield # After all tests __delete_pod_yamls() print('Test End') def test_verify_es_data_uploaded_stressng_pod(): """ This method verify that the data upload properly to elasticsearch :return: """ oc = OC(kubeadmin_password=test_environment_variable['kubeadmin_password']) oc.login() try: workload = 'stressng-pod' oc.create_pod_sync(yaml=os.path.join(f'{templates_path}', 'stressng_pod.yaml'), pod_name=f'{workload}-workload') oc.wait_for_initialized(label='app=stressng_workload', workload=workload) oc.wait_for_ready(label='app=stressng_workload', workload=workload) oc.wait_for_pod_completed(label='app=stressng_workload', workload=workload) # system-metrics if test_environment_variable['system_metrics'] == 'True': es = ESOperations(es_host=test_environment_variable['elasticsearch'], es_port=test_environment_variable['elasticsearch_port']) assert oc.wait_for_pod_create(pod_name='system-metrics-collector') assert oc.wait_for_initialized(label='app=system-metrics-collector', workload=workload) assert oc.wait_for_pod_completed(label='app=system-metrics-collector', workload=workload) assert es.verify_es_data_uploaded(index='system-metrics-test', uuid=oc.get_long_uuid(workload=workload)) if test_environment_variable['elasticsearch']: # verify that data upload to elastic search es = ESOperations(es_host=test_environment_variable['elasticsearch'], es_port=test_environment_variable['elasticsearch_port']) assert es.verify_es_data_uploaded(index='stressng-pod-test-results', uuid=oc.get_long_uuid(workload=workload)) except ElasticSearchDataNotUploaded as err: raise err except Exception as err: raise err
en
0.818229
This method create pod yaml from template and inject environment variable inside :return: This method delete benchmark_operator :return: This method is create benchmark operator pod once for ALL tests :return: # delete benchmark-operator pod if exist This method is clearing yaml before and after EACH test :return: # before each test # After all tests This method verify that the data upload properly to elasticsearch :return: # system-metrics # verify that data upload to elastic search
2.000837
2
python/pyspark_cassandra/util.py
gfronza/pyspark-cassandra
67
6612701
<filename>python/pyspark_cassandra/util.py # 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 collections import Set, Iterable, Mapping from datetime import datetime from time import mktime from .types import UDT def as_java_array(gateway, java_type, iterable): """Creates a Java array from a Python iterable, using the given p4yj gateway""" if iterable is None: return None java_type = gateway.jvm.__getattr__(java_type) lst = list(iterable) arr = gateway.new_array(java_type, len(lst)) for i, e in enumerate(lst): jobj = as_java_object(gateway, e) arr[i] = jobj return arr def as_java_object(gateway, obj): """ Converts a limited set of types to their corresponding types in java. Supported are 'primitives' (which aren't converted), datetime.datetime and the set-, dict- and iterable-like types. """ if obj is None: return None t = type(obj) if issubclass(t, (bool, int, float, str)): return obj elif issubclass(t, UDT): field_names = as_java_array(gateway, "String", obj.keys()) field_values = as_java_array(gateway, "Object", obj.values()) udt = gateway.jvm.UDTValueConverter(field_names, field_values) return udt.toConnectorType() elif issubclass(t, datetime): timestamp = int(mktime(obj.timetuple()) * 1000) return gateway.jvm.java.util.Date(timestamp) elif issubclass(t, (dict, Mapping)): hash_map = gateway.jvm.java.util.HashMap() for (k, v) in obj.items(): hash_map[k] = v return hash_map elif issubclass(t, (set, Set)): hash_set = gateway.jvm.java.util.HashSet() for e in obj: hash_set.add(e) return hash_set elif issubclass(t, (list, Iterable)): array_list = gateway.jvm.java.util.ArrayList() for e in obj: array_list.append(e) return array_list else: return obj def load_class(ctx, name): return ctx._jvm.java.lang.Thread.currentThread().getContextClassLoader() \ .loadClass(name) _helper = None def helper(ctx): global _helper if not _helper: _helper = load_class(ctx, "pyspark_cassandra.PythonHelper").newInstance() return _helper
<filename>python/pyspark_cassandra/util.py # 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 collections import Set, Iterable, Mapping from datetime import datetime from time import mktime from .types import UDT def as_java_array(gateway, java_type, iterable): """Creates a Java array from a Python iterable, using the given p4yj gateway""" if iterable is None: return None java_type = gateway.jvm.__getattr__(java_type) lst = list(iterable) arr = gateway.new_array(java_type, len(lst)) for i, e in enumerate(lst): jobj = as_java_object(gateway, e) arr[i] = jobj return arr def as_java_object(gateway, obj): """ Converts a limited set of types to their corresponding types in java. Supported are 'primitives' (which aren't converted), datetime.datetime and the set-, dict- and iterable-like types. """ if obj is None: return None t = type(obj) if issubclass(t, (bool, int, float, str)): return obj elif issubclass(t, UDT): field_names = as_java_array(gateway, "String", obj.keys()) field_values = as_java_array(gateway, "Object", obj.values()) udt = gateway.jvm.UDTValueConverter(field_names, field_values) return udt.toConnectorType() elif issubclass(t, datetime): timestamp = int(mktime(obj.timetuple()) * 1000) return gateway.jvm.java.util.Date(timestamp) elif issubclass(t, (dict, Mapping)): hash_map = gateway.jvm.java.util.HashMap() for (k, v) in obj.items(): hash_map[k] = v return hash_map elif issubclass(t, (set, Set)): hash_set = gateway.jvm.java.util.HashSet() for e in obj: hash_set.add(e) return hash_set elif issubclass(t, (list, Iterable)): array_list = gateway.jvm.java.util.ArrayList() for e in obj: array_list.append(e) return array_list else: return obj def load_class(ctx, name): return ctx._jvm.java.lang.Thread.currentThread().getContextClassLoader() \ .loadClass(name) _helper = None def helper(ctx): global _helper if not _helper: _helper = load_class(ctx, "pyspark_cassandra.PythonHelper").newInstance() return _helper
en
0.847157
# 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. Creates a Java array from a Python iterable, using the given p4yj gateway Converts a limited set of types to their corresponding types in java. Supported are 'primitives' (which aren't converted), datetime.datetime and the set-, dict- and iterable-like types.
2.146017
2
occurrence/migrations/0024_auto_20190408_1421.py
ropable/wastd
3
6612702
# Generated by Django 2.1.7 on 2019-04-08 06:21 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('occurrence', '0023_auto_20190327_0755'), ] operations = [ migrations.RemoveField( model_name='conservationthreat', name='observationgroup_ptr', ), migrations.AlterField( model_name='areaencounter', name='source_id', field=models.CharField(default=uuid.UUID('82cf7208-59c6-11e9-a870-ecf4bb19b5fc'), help_text='The ID of the record in the original source, if available.', max_length=1000, verbose_name='Source ID'), ), migrations.DeleteModel( name='ConservationThreat', ), ]
# Generated by Django 2.1.7 on 2019-04-08 06:21 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('occurrence', '0023_auto_20190327_0755'), ] operations = [ migrations.RemoveField( model_name='conservationthreat', name='observationgroup_ptr', ), migrations.AlterField( model_name='areaencounter', name='source_id', field=models.CharField(default=uuid.UUID('82cf7208-59c6-11e9-a870-ecf4bb19b5fc'), help_text='The ID of the record in the original source, if available.', max_length=1000, verbose_name='Source ID'), ), migrations.DeleteModel( name='ConservationThreat', ), ]
en
0.672895
# Generated by Django 2.1.7 on 2019-04-08 06:21
1.560692
2
main.py
Caindrac/Census_Bulk_Downloader
2
6612703
<reponame>Caindrac/Census_Bulk_Downloader import json import time from pathlib import Path import requests import argparse from typing import List from abc import ABC, abstractmethod from bounded_pool_executor import BoundedProcessPoolExecutor """ This tool allows the the user to download all the data from a given summary level. These files will be download as csv files for each state and table your provide. This data is being buld downloaded from http://census.ire.org/data/bulkdata.html """ class AbstractDownloader(ABC): def __init__(self): super().__init__() @abstractmethod def download(self): pass class SF1_Downloader(AbstractDownloader): def __init__(self, data_folder: str, summary_levels: List[str], table_names: List[str], fips_list: List[str], process_num: int): super().__init__() self.summary_levels: List[str] = summary_levels self.table_names: List[str] = table_names self.fips_list: List[str] = [str(fip).zfill(2) for fip in fips_list] self.process_num = process_num self.url_pattern = "http://censusdata.ire.org/{fips}/all_{summary_level}_in_{fips}.{table_name}.csv" self.folder_path = data_folder + "/table_{table_name}/sumLevel_{summary_level}" self.file_path = self.folder_path + "/all_{summary_level}_in_{fips}.csv" def download(self): with BoundedProcessPoolExecutor(max_workers=self.process_num) as worker: for table_name in self.table_names: for summary_level in self.summary_levels: for fip in self.fips_list: worker.submit(self.download_table, fip, table_name, summary_level) def download_table(self, fip: int, table_name: str, summary_level: str): Path(self.folder_path.format(table_name=table_name, summary_level=summary_level)).mkdir(parents=True, exist_ok=True) current_requests = requests.get(self.url_pattern.format(fips=fip, summary_level=summary_level, table_name=table_name)) with open(self.file_path.format(table_name=table_name, summary_level=summary_level, fips=fip), "wb") as f: f.write(current_requests.content) def read_config(config_file_location: str): with open(config_file_location) as config_file: return json.load(config_file) if __name__ == "__main__": class_mapper = { "SF1_Downloader": SF1_Downloader } parser = argparse.ArgumentParser(description="Tool to mass donwlaod data from http://census.ire.org/data/bulkdata.html") parser.add_argument("--config_file", type=str, required=True) args = parser.parse_args() config = read_config(config_file_location=args.config_file) for download in config['download_list']: download_instance = class_mapper[download['download_class']](**download['download_class_variables']) download_instance.download()
import json import time from pathlib import Path import requests import argparse from typing import List from abc import ABC, abstractmethod from bounded_pool_executor import BoundedProcessPoolExecutor """ This tool allows the the user to download all the data from a given summary level. These files will be download as csv files for each state and table your provide. This data is being buld downloaded from http://census.ire.org/data/bulkdata.html """ class AbstractDownloader(ABC): def __init__(self): super().__init__() @abstractmethod def download(self): pass class SF1_Downloader(AbstractDownloader): def __init__(self, data_folder: str, summary_levels: List[str], table_names: List[str], fips_list: List[str], process_num: int): super().__init__() self.summary_levels: List[str] = summary_levels self.table_names: List[str] = table_names self.fips_list: List[str] = [str(fip).zfill(2) for fip in fips_list] self.process_num = process_num self.url_pattern = "http://censusdata.ire.org/{fips}/all_{summary_level}_in_{fips}.{table_name}.csv" self.folder_path = data_folder + "/table_{table_name}/sumLevel_{summary_level}" self.file_path = self.folder_path + "/all_{summary_level}_in_{fips}.csv" def download(self): with BoundedProcessPoolExecutor(max_workers=self.process_num) as worker: for table_name in self.table_names: for summary_level in self.summary_levels: for fip in self.fips_list: worker.submit(self.download_table, fip, table_name, summary_level) def download_table(self, fip: int, table_name: str, summary_level: str): Path(self.folder_path.format(table_name=table_name, summary_level=summary_level)).mkdir(parents=True, exist_ok=True) current_requests = requests.get(self.url_pattern.format(fips=fip, summary_level=summary_level, table_name=table_name)) with open(self.file_path.format(table_name=table_name, summary_level=summary_level, fips=fip), "wb") as f: f.write(current_requests.content) def read_config(config_file_location: str): with open(config_file_location) as config_file: return json.load(config_file) if __name__ == "__main__": class_mapper = { "SF1_Downloader": SF1_Downloader } parser = argparse.ArgumentParser(description="Tool to mass donwlaod data from http://census.ire.org/data/bulkdata.html") parser.add_argument("--config_file", type=str, required=True) args = parser.parse_args() config = read_config(config_file_location=args.config_file) for download in config['download_list']: download_instance = class_mapper[download['download_class']](**download['download_class_variables']) download_instance.download()
en
0.8242
This tool allows the the user to download all the data from a given summary level. These files will be download as csv files for each state and table your provide. This data is being buld downloaded from http://census.ire.org/data/bulkdata.html
3.130291
3
urls.py
huangsongyan/pythondemo
0
6612704
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = '<NAME>' from transwarp.web import get,post,ctx @get('/') def index(): print ctx.request.headers return 'hello' @post('/') def post(): print ctx.request.headers print ctx.request.header('CONTENT-TYPE','test2') return 'post'
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = '<NAME>' from transwarp.web import get,post,ctx @get('/') def index(): print ctx.request.headers return 'hello' @post('/') def post(): print ctx.request.headers print ctx.request.header('CONTENT-TYPE','test2') return 'post'
en
0.352855
#!/usr/bin/env python # -*- coding: utf-8 -*-
2.040797
2
setup.py
GrupoAndradeMartins/totvserprm
7
6612705
# -*- coding: utf-8 -*- from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='totvserprmgam', version='1.0.22', description='API para webservices do TOTVS ERP RM', url='https://github.com/grupoandrademartins/totvserprm', author='<NAME>, <NAME>', author_email='<EMAIL>', license='MIT', packages=find_packages(exclude=['contrib', 'docs', 'tests']), install_requires=[ 'dicttoxml', 'lxml', 'requests', 'zeep' ], keywords='totvs webservice erp rm soap api', long_description=long_description )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='totvserprmgam', version='1.0.22', description='API para webservices do TOTVS ERP RM', url='https://github.com/grupoandrademartins/totvserprm', author='<NAME>, <NAME>', author_email='<EMAIL>', license='MIT', packages=find_packages(exclude=['contrib', 'docs', 'tests']), install_requires=[ 'dicttoxml', 'lxml', 'requests', 'zeep' ], keywords='totvs webservice erp rm soap api', long_description=long_description )
en
0.769321
# -*- coding: utf-8 -*-
1.368214
1
tests/funcs.py
ziord/Switches
7
6612706
<reponame>ziord/Switches<gh_stars>1-10 """ :copyright: Copyright (c) 2020 <NAME> (@ziord) :license: MIT, see LICENSE for more details """ from switches.switch import switch, SwitchError def foobar(x, y): return x*y def foofoo(): return 'foo'*2 class Foo: def __init__(self, n): self._n = n def __eq__(self, other): return self._n == other._n def __hash__(self): return sum(map(lambda x: ord(x), self._n)) class Bar: def __init__(self, p): self._p = p def __eq__(self, other): return self._p == other._p def __hash__(self): return sum(map(lambda x: ord(x), self._p)) def __call__(self, *args, **kwargs): print(args, kwargs) return args, kwargs valNum = 5 valList = [1, 2, 3] valTup = (1, 2) valCall = foofoo valCall2 = foobar valFoo = Foo('foo') valBar = Bar('bar') valRange = range(10) ############################## # ft ############################## def test_valNum_ft(): g = [] with switch(valNum, allow_duplicates=False, fallthrough=True) as s: s.case(5, lambda: g.append('pop')) s.case(12, lambda: g.append('push')) s.default(None) return g def test_valList_ft(): g = [] with switch(valList, allow_duplicates=False) as s: s.allow_fallthrough = True s.case(5, lambda x: g.append(x), args=('push',)) s.case(12, func=lambda y: g.append(y), kwargs={'y': 'pop'}) s.default(func=lambda x: print('default here', x), args=('yeah!',)) return g def test_valFoo_ft(): g = [] with switch(valFoo, fallthrough=True) as s: s.allow_duplicates = True s.case(5, lambda: g.append('pop')) s.case(12, lambda: g.append('push')) s.case(valFoo, lambda: g.append('poof')) s.case(valFoo, lambda: g.append('poof2')) s.default(None) return g def test_valCall_ft(): g = [] with switch(valCall, fallthrough=True) as s: s.allow_duplicates = True s.as_callable = True s.case('foofoo', lambda: g.append('pop')) s.case(6, lambda: g.append('push')) s.default(None) return g def test_valCall2_ft(): g = [] with switch(valCall2, args=(2, 3), fallthrough=True) as s: s.allow_duplicates = True s.as_callable = True s.case('foofoo', lambda: g.append('pop')) s.case(6, lambda: g.append('push')) s.default(None) return g def test_valNum2_ft(): g = [] with switch(valNum, allow_duplicates=False, fallthrough=True) as s: s.case(5, lambda: g.append('pop')) s.c_break() s.case(12, lambda: g.append('push')) s.default(None) return g def test_valList2_ft(): g = [] with switch(valList, allow_duplicates=False) as s: s.allow_fallthrough = True s.case(valList, lambda: g.append('pop'), c_break=True) s.case([1, 2, 3], lambda: g.append('pop')) s.case(12, lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_valFoo2_ft(): g = [] with switch(valFoo, fallthrough=True) as s: s.allow_duplicates = True s.case(5, lambda: g.append('pop')) s.case(12, lambda: g.append('push')) s.case(valFoo, lambda: g.append('poof'), c_break=False) s.case(valFoo, lambda: g.append('poof2'),) s.c_break() s.case(valFoo, lambda: g.append('poof2')) s.default(None) return g def test_valNum3_ft(): g = [] with switch(valNum) as s: s.allow_fallthrough = True s.allow_duplicates = False s.icase([1, 2, 3], lambda: g.append('pop')) s.icase(range(10), lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_valFoo3_ft(val): g = [] with switch(val, fallthrough=True) as s: s.allow_duplicates = True s.case(5,) # case without func or break, fall through s.case(12,) s.icase([Foo('tea'), Foo('coffee'), Foo('foo'), ], lambda: g.append('poof')) s.c_break() s.case(valFoo, lambda: g.append('poof2')) s.default(None) return g def test_valNum4_ft(): g = [] with switch(valNum) as s: s.allow_fallthrough = True s.allow_duplicates = False s.fcase(f_name=foobar, f_kwargs={'x': 5, 'y': 1}, func=lambda: g.append('push'), c_break=True) s.case(range(10), lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_valNum5_ft(): g = [] with switch(value='foo'*2) as s: s.allow_fallthrough = True s.allow_duplicates = False s.fcase(f_name=foofoo, f_args=[], func=lambda: g.append('foofoo')) s.icase(['foo', 'foofoo', 'foobar'], lambda: g.pop(), c_break=True) s.case(range(10), lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_new_ft(): g = [] with switch(value=100) as s: s.allow_fallthrough = True s.allow_duplicates = False s.fcase(f_name=foofoo, f_args=(), func=lambda x: g.append(x), args=['foofoo',]) s.icase(['foo', 'foofoo', 'foobar'], lambda: g.pop(), c_break=True) s.case(range(10), lambda: g.append('push')) s.default(func=lambda: g.append('defaulted')) return g def test_call_ft(): g = [] with switch(value=Bar(2)(2, 3), as_callable=True) as s: s.allow_fallthrough = True s.case(1) s.case(((2, 3), {}), lambda: g.append(s.value)) s.default(None) print('s.value', s.value) return g[0] ############################## # nft ############################## def test_valNum_nft(): g = [] # fallthrough is False by default with switch(valNum, allow_duplicates=False, fallthrough=False) as s: s.case(5, lambda: g.append('pop')) s.case(12, lambda: g.append('push')) s.default(None) return g def test_valList_nft(): g = [] with switch(valList, allow_duplicates=False) as s: s.case(5, lambda arg: g.append(arg), kwargs=dict(arg='pop')) s.case(12, lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_valFoo_nft(): g = [] with switch(valFoo) as s: s.allow_duplicates = True s.case(valFoo, func=lambda v: g.append(v), args=['poof']) s.case(6, lambda: g.append('poof2')) s.default(None) return g def test_valNum2_nft(): g = [] with switch(valNum, allow_duplicates=False,) as s: s.case(5, lambda: g.append('pop'), c_break=False) s.case(12, lambda: g.append('push')) s.default(None) return g def test_valCall_nft(): g = [] with switch(valCall,) as s: s.allow_duplicates = True s.as_callable = True s.case('foofoo', lambda: g.append('pop')) s.case(6, lambda: g.append('push')) s.default(None) return g def test_valCall2_nft(): g = [] with switch(valCall2, args=(2, 3),) as s: s.allow_duplicates = True s.as_callable = True s.case('foofoo', lambda: g.append('pop')) s.case(12, lambda: g.append('push')) s.default(None) return g def test_valList2_nft(): g = [] with switch(valList, allow_duplicates=False) as s: s.case(valList, lambda: g.append('pop'), c_break=True) s.case([1, 2, 3], lambda: g.append('pop')) s.default(func=lambda: print('default here')) return g def test_valFoo2_nft(): g = [] with switch(valFoo,) as s: s.allow_duplicates = True s.case(12, lambda: g.append('push')) s.case(valFoo, lambda: g.append('poof'), c_break=False) s.case(valFoo, lambda: g.append('poof2'),) s.c_break() # redundant s.case(valFoo, lambda: g.append('poof2')) s.default(None) return g def test_valNum3_nft(): g = [] with switch(valNum) as s: s.allow_duplicates = False s.icase([1, 2, 3], lambda: g.append('pop')) s.icase(range(10), lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_valFoo3_nft(val): g = [] with switch(val, allow_duplicates=True) as s: s.case(5,) # case without func or break, no fall through s.case(12,) s.icase([Foo('tea'), Foo('coffee'), Foo('foo'), ], lambda: g.append('poof')) s.case(valFoo, lambda: g.append('poof2')) s.default(None) return g def test_valNum4_nft(): g = [] with switch(valNum, allow_duplicates=False) as s: s.fcase(f_name=foobar, f_kwargs={'x': 5, 'y': 1}, func=lambda: g.append('push'), c_break=True) s.case(range(10), lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_valNum5_nft(): g = [] with switch(value='foo'*2, allow_duplicates=False) as s: s.fcase(f_name=foofoo, func=lambda: g.append('foofoo')) s.icase(['foo', 'foofoo', 'foobar'], lambda: g.pop(), c_break=True) s.case(range(10), lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_new_nft(): g = [] with switch(value=100, allow_duplicates=False) as s: s.fcase(f_name=foofoo, f_args=set(), func=lambda: g.append('foofoo')) s.icase(['foo', 'foofoo', 'foobar'], lambda: g.pop(), c_break=True) s.case(range(10), lambda: g.append('push')) s.default(func=lambda: g.append('defaulted')) return g def test_call_nft(): g = [] with switch(value=Bar(2)(2, 3), as_callable=True) as s: s.case(1) s.case(((2, 3), {}), lambda: g.append(s.value)) s.default(None) print('s.value', s.value) return g[0] ########################## # warnings ########################## def test_valNum_wn(): g = [] with switch(valNum) as s: s.allow_duplicates = True s.allow_fallthrough = True s.case(5, lambda: g.append('pop')) s.case(5, lambda: g.append('push')) s.default(None) s.c_break() return g def test_valTup_wn(): g = [] with switch(valTup) as s: s.allow_fallthrough = True s.case(5, lambda: g.append('pop')) s.case(5, lambda: g.append('push')) s.c_break() return g ########################## # errors ########################## def test_dup_err(): # duplicate error g = [] with switch(valNum) as s: s.allow_duplicates = False s.allow_fallthrough = True s.case(5, lambda: g.append('pop')) s.case(5, lambda: g.append('push')) s.default(None) return g def test_double_cbreak_err(): # double c_break g = [] with switch(valNum) as s: s.allow_duplicates = False s.allow_fallthrough = True s.case(5, lambda: g.append('pop')) s.case(5, lambda: g.append('push')) s.default(None) s.c_break() s.c_break() return g def test_double_cbreak2_err(): # double c_break g = [] with switch(valNum) as s: s.allow_duplicates = False s.allow_fallthrough = True s.case(5, lambda: g.append('pop')) s.c_break() s.c_break() s.case(5, lambda: g.append('push')) s.default(None) return g def test_case_after_default_err(): # case after default g = [] with switch(valNum) as s: s.allow_duplicates = False s.allow_fallthrough = True s.case(5, lambda: g.append('pop')) s.case(5, lambda: g.append('push')) s.default(None) s.case(10) return g def test_call_err(): # callable error g = [] with switch(valNum, as_callable=False, fallthrough=True) as s: s.allow_duplicates = False s.fcase(f_name=5, func=lambda: g.append('pop')) s.default(None) return g def test_iter_err(): # iterable error g = [] with switch(valNum, as_callable=False, fallthrough=True) as s: s.allow_duplicates = False s.icase(5, func=lambda: g.append('pop')) s.default(None) return g def test_double_default_err(): # double default statements with switch(valNum, as_callable=False, fallthrough=True) as s: s.default(None) s.default(None) def test_value_args_err(): with switch(valCall, args={},) as s: s.no_warning = True pass def test_value_kwargs_err(): with switch(valCall, kwargs=(),) as s: s.no_warning = True pass def test_fcase_f_args_err(): # f_args in fcase, passed in as the wrong type with switch(valNum, as_callable=False, fallthrough=True) as s: s.fcase(f_name=foofoo, f_args={}) s.default(None) def test_fcase_f_kwargs_err(): # f_kwargs in fcase, passed in as the wrong type with switch(valNum, as_callable=False, fallthrough=True) as s: s.fcase(f_name=foobar, f_kwargs=()) s.default(None) def test_case_args_err(): # args in case, passed in as the wrong type with switch(valCall,) as s: s.as_callable = True s.case(5, func=foofoo, args={}) s.default(None) def test_case_kwargs_err(): # kwargs in case, passed in as the wrong type with switch(Bar('test'),) as s: s.as_callable = True s.case(Bar('test'), func=foobar, kwargs=()) s.default(None) def test_icase_args_err(): # args in icase, passed in as the wrong type with switch(valTup, as_callable=False,) as s: s.allow_fallthrough = True s.icase((2, 3, 4), func=foofoo, args={}) s.default(None) def test_icase_kwargs_err(): # kwargs in icase, passed in as the wrong type with switch(valNum, as_callable=False, fallthrough=True) as s: s.icase(foofoo, func=lambda **kwargs: print(kwargs), kwargs=[]) s.default(None)
""" :copyright: Copyright (c) 2020 <NAME> (@ziord) :license: MIT, see LICENSE for more details """ from switches.switch import switch, SwitchError def foobar(x, y): return x*y def foofoo(): return 'foo'*2 class Foo: def __init__(self, n): self._n = n def __eq__(self, other): return self._n == other._n def __hash__(self): return sum(map(lambda x: ord(x), self._n)) class Bar: def __init__(self, p): self._p = p def __eq__(self, other): return self._p == other._p def __hash__(self): return sum(map(lambda x: ord(x), self._p)) def __call__(self, *args, **kwargs): print(args, kwargs) return args, kwargs valNum = 5 valList = [1, 2, 3] valTup = (1, 2) valCall = foofoo valCall2 = foobar valFoo = Foo('foo') valBar = Bar('bar') valRange = range(10) ############################## # ft ############################## def test_valNum_ft(): g = [] with switch(valNum, allow_duplicates=False, fallthrough=True) as s: s.case(5, lambda: g.append('pop')) s.case(12, lambda: g.append('push')) s.default(None) return g def test_valList_ft(): g = [] with switch(valList, allow_duplicates=False) as s: s.allow_fallthrough = True s.case(5, lambda x: g.append(x), args=('push',)) s.case(12, func=lambda y: g.append(y), kwargs={'y': 'pop'}) s.default(func=lambda x: print('default here', x), args=('yeah!',)) return g def test_valFoo_ft(): g = [] with switch(valFoo, fallthrough=True) as s: s.allow_duplicates = True s.case(5, lambda: g.append('pop')) s.case(12, lambda: g.append('push')) s.case(valFoo, lambda: g.append('poof')) s.case(valFoo, lambda: g.append('poof2')) s.default(None) return g def test_valCall_ft(): g = [] with switch(valCall, fallthrough=True) as s: s.allow_duplicates = True s.as_callable = True s.case('foofoo', lambda: g.append('pop')) s.case(6, lambda: g.append('push')) s.default(None) return g def test_valCall2_ft(): g = [] with switch(valCall2, args=(2, 3), fallthrough=True) as s: s.allow_duplicates = True s.as_callable = True s.case('foofoo', lambda: g.append('pop')) s.case(6, lambda: g.append('push')) s.default(None) return g def test_valNum2_ft(): g = [] with switch(valNum, allow_duplicates=False, fallthrough=True) as s: s.case(5, lambda: g.append('pop')) s.c_break() s.case(12, lambda: g.append('push')) s.default(None) return g def test_valList2_ft(): g = [] with switch(valList, allow_duplicates=False) as s: s.allow_fallthrough = True s.case(valList, lambda: g.append('pop'), c_break=True) s.case([1, 2, 3], lambda: g.append('pop')) s.case(12, lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_valFoo2_ft(): g = [] with switch(valFoo, fallthrough=True) as s: s.allow_duplicates = True s.case(5, lambda: g.append('pop')) s.case(12, lambda: g.append('push')) s.case(valFoo, lambda: g.append('poof'), c_break=False) s.case(valFoo, lambda: g.append('poof2'),) s.c_break() s.case(valFoo, lambda: g.append('poof2')) s.default(None) return g def test_valNum3_ft(): g = [] with switch(valNum) as s: s.allow_fallthrough = True s.allow_duplicates = False s.icase([1, 2, 3], lambda: g.append('pop')) s.icase(range(10), lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_valFoo3_ft(val): g = [] with switch(val, fallthrough=True) as s: s.allow_duplicates = True s.case(5,) # case without func or break, fall through s.case(12,) s.icase([Foo('tea'), Foo('coffee'), Foo('foo'), ], lambda: g.append('poof')) s.c_break() s.case(valFoo, lambda: g.append('poof2')) s.default(None) return g def test_valNum4_ft(): g = [] with switch(valNum) as s: s.allow_fallthrough = True s.allow_duplicates = False s.fcase(f_name=foobar, f_kwargs={'x': 5, 'y': 1}, func=lambda: g.append('push'), c_break=True) s.case(range(10), lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_valNum5_ft(): g = [] with switch(value='foo'*2) as s: s.allow_fallthrough = True s.allow_duplicates = False s.fcase(f_name=foofoo, f_args=[], func=lambda: g.append('foofoo')) s.icase(['foo', 'foofoo', 'foobar'], lambda: g.pop(), c_break=True) s.case(range(10), lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_new_ft(): g = [] with switch(value=100) as s: s.allow_fallthrough = True s.allow_duplicates = False s.fcase(f_name=foofoo, f_args=(), func=lambda x: g.append(x), args=['foofoo',]) s.icase(['foo', 'foofoo', 'foobar'], lambda: g.pop(), c_break=True) s.case(range(10), lambda: g.append('push')) s.default(func=lambda: g.append('defaulted')) return g def test_call_ft(): g = [] with switch(value=Bar(2)(2, 3), as_callable=True) as s: s.allow_fallthrough = True s.case(1) s.case(((2, 3), {}), lambda: g.append(s.value)) s.default(None) print('s.value', s.value) return g[0] ############################## # nft ############################## def test_valNum_nft(): g = [] # fallthrough is False by default with switch(valNum, allow_duplicates=False, fallthrough=False) as s: s.case(5, lambda: g.append('pop')) s.case(12, lambda: g.append('push')) s.default(None) return g def test_valList_nft(): g = [] with switch(valList, allow_duplicates=False) as s: s.case(5, lambda arg: g.append(arg), kwargs=dict(arg='pop')) s.case(12, lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_valFoo_nft(): g = [] with switch(valFoo) as s: s.allow_duplicates = True s.case(valFoo, func=lambda v: g.append(v), args=['poof']) s.case(6, lambda: g.append('poof2')) s.default(None) return g def test_valNum2_nft(): g = [] with switch(valNum, allow_duplicates=False,) as s: s.case(5, lambda: g.append('pop'), c_break=False) s.case(12, lambda: g.append('push')) s.default(None) return g def test_valCall_nft(): g = [] with switch(valCall,) as s: s.allow_duplicates = True s.as_callable = True s.case('foofoo', lambda: g.append('pop')) s.case(6, lambda: g.append('push')) s.default(None) return g def test_valCall2_nft(): g = [] with switch(valCall2, args=(2, 3),) as s: s.allow_duplicates = True s.as_callable = True s.case('foofoo', lambda: g.append('pop')) s.case(12, lambda: g.append('push')) s.default(None) return g def test_valList2_nft(): g = [] with switch(valList, allow_duplicates=False) as s: s.case(valList, lambda: g.append('pop'), c_break=True) s.case([1, 2, 3], lambda: g.append('pop')) s.default(func=lambda: print('default here')) return g def test_valFoo2_nft(): g = [] with switch(valFoo,) as s: s.allow_duplicates = True s.case(12, lambda: g.append('push')) s.case(valFoo, lambda: g.append('poof'), c_break=False) s.case(valFoo, lambda: g.append('poof2'),) s.c_break() # redundant s.case(valFoo, lambda: g.append('poof2')) s.default(None) return g def test_valNum3_nft(): g = [] with switch(valNum) as s: s.allow_duplicates = False s.icase([1, 2, 3], lambda: g.append('pop')) s.icase(range(10), lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_valFoo3_nft(val): g = [] with switch(val, allow_duplicates=True) as s: s.case(5,) # case without func or break, no fall through s.case(12,) s.icase([Foo('tea'), Foo('coffee'), Foo('foo'), ], lambda: g.append('poof')) s.case(valFoo, lambda: g.append('poof2')) s.default(None) return g def test_valNum4_nft(): g = [] with switch(valNum, allow_duplicates=False) as s: s.fcase(f_name=foobar, f_kwargs={'x': 5, 'y': 1}, func=lambda: g.append('push'), c_break=True) s.case(range(10), lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_valNum5_nft(): g = [] with switch(value='foo'*2, allow_duplicates=False) as s: s.fcase(f_name=foofoo, func=lambda: g.append('foofoo')) s.icase(['foo', 'foofoo', 'foobar'], lambda: g.pop(), c_break=True) s.case(range(10), lambda: g.append('push')) s.default(func=lambda: print('default here')) return g def test_new_nft(): g = [] with switch(value=100, allow_duplicates=False) as s: s.fcase(f_name=foofoo, f_args=set(), func=lambda: g.append('foofoo')) s.icase(['foo', 'foofoo', 'foobar'], lambda: g.pop(), c_break=True) s.case(range(10), lambda: g.append('push')) s.default(func=lambda: g.append('defaulted')) return g def test_call_nft(): g = [] with switch(value=Bar(2)(2, 3), as_callable=True) as s: s.case(1) s.case(((2, 3), {}), lambda: g.append(s.value)) s.default(None) print('s.value', s.value) return g[0] ########################## # warnings ########################## def test_valNum_wn(): g = [] with switch(valNum) as s: s.allow_duplicates = True s.allow_fallthrough = True s.case(5, lambda: g.append('pop')) s.case(5, lambda: g.append('push')) s.default(None) s.c_break() return g def test_valTup_wn(): g = [] with switch(valTup) as s: s.allow_fallthrough = True s.case(5, lambda: g.append('pop')) s.case(5, lambda: g.append('push')) s.c_break() return g ########################## # errors ########################## def test_dup_err(): # duplicate error g = [] with switch(valNum) as s: s.allow_duplicates = False s.allow_fallthrough = True s.case(5, lambda: g.append('pop')) s.case(5, lambda: g.append('push')) s.default(None) return g def test_double_cbreak_err(): # double c_break g = [] with switch(valNum) as s: s.allow_duplicates = False s.allow_fallthrough = True s.case(5, lambda: g.append('pop')) s.case(5, lambda: g.append('push')) s.default(None) s.c_break() s.c_break() return g def test_double_cbreak2_err(): # double c_break g = [] with switch(valNum) as s: s.allow_duplicates = False s.allow_fallthrough = True s.case(5, lambda: g.append('pop')) s.c_break() s.c_break() s.case(5, lambda: g.append('push')) s.default(None) return g def test_case_after_default_err(): # case after default g = [] with switch(valNum) as s: s.allow_duplicates = False s.allow_fallthrough = True s.case(5, lambda: g.append('pop')) s.case(5, lambda: g.append('push')) s.default(None) s.case(10) return g def test_call_err(): # callable error g = [] with switch(valNum, as_callable=False, fallthrough=True) as s: s.allow_duplicates = False s.fcase(f_name=5, func=lambda: g.append('pop')) s.default(None) return g def test_iter_err(): # iterable error g = [] with switch(valNum, as_callable=False, fallthrough=True) as s: s.allow_duplicates = False s.icase(5, func=lambda: g.append('pop')) s.default(None) return g def test_double_default_err(): # double default statements with switch(valNum, as_callable=False, fallthrough=True) as s: s.default(None) s.default(None) def test_value_args_err(): with switch(valCall, args={},) as s: s.no_warning = True pass def test_value_kwargs_err(): with switch(valCall, kwargs=(),) as s: s.no_warning = True pass def test_fcase_f_args_err(): # f_args in fcase, passed in as the wrong type with switch(valNum, as_callable=False, fallthrough=True) as s: s.fcase(f_name=foofoo, f_args={}) s.default(None) def test_fcase_f_kwargs_err(): # f_kwargs in fcase, passed in as the wrong type with switch(valNum, as_callable=False, fallthrough=True) as s: s.fcase(f_name=foobar, f_kwargs=()) s.default(None) def test_case_args_err(): # args in case, passed in as the wrong type with switch(valCall,) as s: s.as_callable = True s.case(5, func=foofoo, args={}) s.default(None) def test_case_kwargs_err(): # kwargs in case, passed in as the wrong type with switch(Bar('test'),) as s: s.as_callable = True s.case(Bar('test'), func=foobar, kwargs=()) s.default(None) def test_icase_args_err(): # args in icase, passed in as the wrong type with switch(valTup, as_callable=False,) as s: s.allow_fallthrough = True s.icase((2, 3, 4), func=foofoo, args={}) s.default(None) def test_icase_kwargs_err(): # kwargs in icase, passed in as the wrong type with switch(valNum, as_callable=False, fallthrough=True) as s: s.icase(foofoo, func=lambda **kwargs: print(kwargs), kwargs=[]) s.default(None)
en
0.545693
:copyright: Copyright (c) 2020 <NAME> (@ziord) :license: MIT, see LICENSE for more details ############################## # ft ############################## # case without func or break, fall through ############################## # nft ############################## # fallthrough is False by default # redundant # case without func or break, no fall through ########################## # warnings ########################## ########################## # errors ########################## # duplicate error # double c_break # double c_break # case after default # callable error # iterable error # double default statements # f_args in fcase, passed in as the wrong type # f_kwargs in fcase, passed in as the wrong type # args in case, passed in as the wrong type # kwargs in case, passed in as the wrong type # args in icase, passed in as the wrong type # kwargs in icase, passed in as the wrong type
3.128841
3
set1/challenge1_convert_hex_to_base64/s1c1.py
douglasnaphas/cryptopals-py
0
6612707
<reponame>douglasnaphas/cryptopals-py import math import base64 class S1C1(): @staticmethod def ret_true(): return True @staticmethod def hex_to_base64(hx): hx_str = '0x' + hx n = int(hx_str, 16) num_bytes = math.ceil(n.bit_length() / 8) if num_bytes == 0: num_bytes = 1 b = (n).to_bytes(num_bytes, 'big') return str(base64.b64encode(b))[2:-1]
import math import base64 class S1C1(): @staticmethod def ret_true(): return True @staticmethod def hex_to_base64(hx): hx_str = '0x' + hx n = int(hx_str, 16) num_bytes = math.ceil(n.bit_length() / 8) if num_bytes == 0: num_bytes = 1 b = (n).to_bytes(num_bytes, 'big') return str(base64.b64encode(b))[2:-1]
none
1
2.975028
3
guanabara/Exercicios/mundo 2 _ aulas 12 a 15/066.py
pbittencourt/datasciencestudies
0
6612708
<filename>guanabara/Exercicios/mundo 2 _ aulas 12 a 15/066.py<gh_stars>0 # EXIBINDO NÚMEROS ATÉ PARAR NO 999 '''O programa lê vários números inteiros, parando apenas se o usuário digitar 999. Ao final, exibe a quantidade de valores inseridos e sua soma, desconsiderando o 999 (flag)''' c = s = 0 # zerando contador e soma while True: # equivalente ao DO (something): n = int(input('Insira um número (ou digite 999 para encerrar): _ ')) if n == 999: break # equivalente ao ... WHILE (condition) c += 1 # incrementa 1 no contador s += n # acrescenta o número à soma print(f'Foram digitados {c} números, cuja soma é {s}.') print(f'{"FIM DO PROGRAMA":_^40}')
<filename>guanabara/Exercicios/mundo 2 _ aulas 12 a 15/066.py<gh_stars>0 # EXIBINDO NÚMEROS ATÉ PARAR NO 999 '''O programa lê vários números inteiros, parando apenas se o usuário digitar 999. Ao final, exibe a quantidade de valores inseridos e sua soma, desconsiderando o 999 (flag)''' c = s = 0 # zerando contador e soma while True: # equivalente ao DO (something): n = int(input('Insira um número (ou digite 999 para encerrar): _ ')) if n == 999: break # equivalente ao ... WHILE (condition) c += 1 # incrementa 1 no contador s += n # acrescenta o número à soma print(f'Foram digitados {c} números, cuja soma é {s}.') print(f'{"FIM DO PROGRAMA":_^40}')
pt
0.811915
# EXIBINDO NÚMEROS ATÉ PARAR NO 999 O programa lê vários números inteiros, parando apenas se o usuário digitar 999. Ao final, exibe a quantidade de valores inseridos e sua soma, desconsiderando o 999 (flag) # zerando contador e soma # equivalente ao DO (something): # equivalente ao ... WHILE (condition) # incrementa 1 no contador # acrescenta o número à soma
3.799281
4
labeller/__init__.py
jasrub/predict-news-labels
1
6612709
import os import logging.config import json base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # set up logging with open(os.path.join(base_dir, 'config', 'logging.json'), 'r') as f: logging_config = json.load(f) logging.config.dictConfig(logging_config) logging.info("Running from "+base_dir)
import os import logging.config import json base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # set up logging with open(os.path.join(base_dir, 'config', 'logging.json'), 'r') as f: logging_config = json.load(f) logging.config.dictConfig(logging_config) logging.info("Running from "+base_dir)
en
0.78644
# set up logging
2.308529
2
tests/test_app.py
tatsuya4649/fly
16
6612710
<reponame>tatsuya4649/fly import pytest import os import stat from fly import Fly from fly.app import Method @pytest.fixture(scope="function", autouse=False) def fly_init(): __f = Fly() yield __f def test_fly_init(): Fly() @pytest.mark.parametrize( "path", [ 200, 200.0, True, {}, [], b"fly/conf" ]) def test_fly_init_path_error(path): with pytest.raises( TypeError ): Fly(config_path=path) @pytest.mark.parametrize( "debug", [ 200, 200.0, {}, [], b"fly/conf" ]) def test_fly_debug_error(debug): with pytest.raises( TypeError ): Fly(debug=debug) TEST_PATH="fly" def test_fly_init_path_value_error(): with pytest.raises( ValueError ): Fly(config_path=TEST_PATH) TEST_READ_PATH="test_read.conf" def test_fly_iniit_path_perm_error(): open(TEST_READ_PATH, "w") os.chmod(path=TEST_READ_PATH, mode=stat.S_IWRITE) if not os.access(TEST_READ_PATH, os.R_OK): with pytest.raises( ValueError ): Fly(config_path=TEST_READ_PATH) else: Fly(config_path=TEST_READ_PATH) os.remove(TEST_READ_PATH) def test_fly_singleton(): a = Fly() b = Fly() c = Fly() d = Fly() assert(a == b == c == d) TEST_MOUNT = "__fly_test_mount_dir" @pytest.fixture(scope="function", autouse=False) def fly_mount(fly_init): os.makedirs(TEST_MOUNT, exist_ok=True) yield fly_init os.rmdir(TEST_MOUNT) def test_mount(fly_mount): fly_mount.mount(TEST_MOUNT) def test_mount_value_error(fly_mount): with pytest.raises( ValueError ): fly_mount.mount(TEST_MOUNT + "test") def test_route(fly_init): func = fly_init.route("/", Method.GET) assert(callable(func)) @pytest.mark.parametrize( "route", [ b"route", 1, 1.0, [], {}, ]) def test_route_type_error(fly_init, route): with pytest.raises(TypeError): fly_init.route(route, Method.GET) @pytest.mark.parametrize( "func", [ "func", b"func", 1, 1.0, [], {}, ]) def test_route_func_error(fly_init, func): _route = fly_init.route("/", Method.GET) with pytest.raises(TypeError): _route(func) def hello(): return "Hello" def test_route(fly_init): _route = fly_init.route("/", Method.GET) _route(hello) def test_route_method(fly_init): func = fly_init.route("/", Method.GET) assert(callable(func)) def test_get(fly_init): func = fly_init.get("/") assert(callable(func)) def test_post(fly_init): func = fly_init.post("/") assert(callable(func)) def test_head(fly_init): func = fly_init.head("/") assert(callable(func)) def test_options(fly_init): func = fly_init.options("/") assert(callable(func)) def test_put(fly_init): func = fly_init.put("/") assert(callable(func)) def test_delete(fly_init): func = fly_init.delete("/") assert(callable(func)) def test_connect(fly_init): func = fly_init.connect("/") assert(callable(func)) def test_trace(fly_init): func = fly_init.trace("/") assert(callable(func)) def test_patch(fly_init): func = fly_init.patch("/") assert(callable(func))
import pytest import os import stat from fly import Fly from fly.app import Method @pytest.fixture(scope="function", autouse=False) def fly_init(): __f = Fly() yield __f def test_fly_init(): Fly() @pytest.mark.parametrize( "path", [ 200, 200.0, True, {}, [], b"fly/conf" ]) def test_fly_init_path_error(path): with pytest.raises( TypeError ): Fly(config_path=path) @pytest.mark.parametrize( "debug", [ 200, 200.0, {}, [], b"fly/conf" ]) def test_fly_debug_error(debug): with pytest.raises( TypeError ): Fly(debug=debug) TEST_PATH="fly" def test_fly_init_path_value_error(): with pytest.raises( ValueError ): Fly(config_path=TEST_PATH) TEST_READ_PATH="test_read.conf" def test_fly_iniit_path_perm_error(): open(TEST_READ_PATH, "w") os.chmod(path=TEST_READ_PATH, mode=stat.S_IWRITE) if not os.access(TEST_READ_PATH, os.R_OK): with pytest.raises( ValueError ): Fly(config_path=TEST_READ_PATH) else: Fly(config_path=TEST_READ_PATH) os.remove(TEST_READ_PATH) def test_fly_singleton(): a = Fly() b = Fly() c = Fly() d = Fly() assert(a == b == c == d) TEST_MOUNT = "__fly_test_mount_dir" @pytest.fixture(scope="function", autouse=False) def fly_mount(fly_init): os.makedirs(TEST_MOUNT, exist_ok=True) yield fly_init os.rmdir(TEST_MOUNT) def test_mount(fly_mount): fly_mount.mount(TEST_MOUNT) def test_mount_value_error(fly_mount): with pytest.raises( ValueError ): fly_mount.mount(TEST_MOUNT + "test") def test_route(fly_init): func = fly_init.route("/", Method.GET) assert(callable(func)) @pytest.mark.parametrize( "route", [ b"route", 1, 1.0, [], {}, ]) def test_route_type_error(fly_init, route): with pytest.raises(TypeError): fly_init.route(route, Method.GET) @pytest.mark.parametrize( "func", [ "func", b"func", 1, 1.0, [], {}, ]) def test_route_func_error(fly_init, func): _route = fly_init.route("/", Method.GET) with pytest.raises(TypeError): _route(func) def hello(): return "Hello" def test_route(fly_init): _route = fly_init.route("/", Method.GET) _route(hello) def test_route_method(fly_init): func = fly_init.route("/", Method.GET) assert(callable(func)) def test_get(fly_init): func = fly_init.get("/") assert(callable(func)) def test_post(fly_init): func = fly_init.post("/") assert(callable(func)) def test_head(fly_init): func = fly_init.head("/") assert(callable(func)) def test_options(fly_init): func = fly_init.options("/") assert(callable(func)) def test_put(fly_init): func = fly_init.put("/") assert(callable(func)) def test_delete(fly_init): func = fly_init.delete("/") assert(callable(func)) def test_connect(fly_init): func = fly_init.connect("/") assert(callable(func)) def test_trace(fly_init): func = fly_init.trace("/") assert(callable(func)) def test_patch(fly_init): func = fly_init.patch("/") assert(callable(func))
none
1
2.070278
2
bin/CourseApplication.py
MrLucio/Lezione-alla-pari
1
6612711
<reponame>MrLucio/Lezione-alla-pari from PermissionManager import PermissionManager from CourseFileSystem import CourseFileSystem from UserManager import UserManager from QuizManager import QuizManager from bs4 import BeautifulSoup from Error import Error import os import re import webview import threading import http.server import socketserver import urllib.request import sys class CourseApplication: def __init__(self, usermanager, user_id): api = Api(usermanager, user_id) t = threading.Thread(target=self.load_html) t1 = threading.Thread(target=self.start_local_html_server, args=[t]) t1.start() webview.config.gui = "cef" webview.create_window("Lezioni alla Pari", debug=True, js_api=api) @staticmethod def load_html(): with open(os.path.join("html", "index.html"), "r") as html: webview.load_html(html.read()) @staticmethod def start_local_html_server(t): port = 8080 handler = http.server.SimpleHTTPRequestHandler with socketserver.ThreadingTCPServer(("", port), handler) as httpd: t.start() httpd.serve_forever() class Api: def __init__(self, usermanager, user_id): self.user_mgr = usermanager self.permission_mgr = PermissionManager() self.course_fs = CourseFileSystem() self._logged_user = user_id def add_course(self, args_dict): id = self.course_fs.add_course(args_dict["course_name"]) self.permission_mgr.add_course(id) self.permission_mgr.add_permission(self._logged_user, id, "rw") return id def remove_course(self, course_id): self.course_fs.remove_course(course_id) self.permission_mgr.remove_course(course_id) return course_id def add_topic(self, args_dict): id = self.course_fs.add_topic( args_dict["topic_name"], args_dict["course_id"]) return id def remove_topic(self, args_dict): self.course_fs.remove_topic( args_dict["topic_id"], args_dict["course_id"]) return args_dict["topic_id"] def add_lesson(self, args_dict): id = self.course_fs.add_lesson(args_dict["element_name"], args_dict["topic_id"], args_dict["course_id"]) return id def edit_lesson(self, args_dict): self.course_fs.edit_lesson( args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"], args_dict["element_html"] ) def remove_element(self, args_dict): self.course_fs.remove_element( args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"]) return args_dict["element_id"] def list_courses(self, arg): return {"message": self.permission_mgr.get_user_permissions(self._logged_user)} def list_topics(self, args_dict): return {"message": self.course_fs.get_topics_list(args_dict["course_id"])} def list_elements(self, args_dict): return {"message": self.course_fs.get_elements_list(args_dict["topic_id"], args_dict["course_id"])} def get_course_attributes(self, args_dict): return {"message": self.course_fs.get_course_attributes(args_dict["course_id"])} def get_topic_attributes(self, args_dict): return {"message": self.course_fs.get_topic_attributes(args_dict["topic_id"], args_dict["course_id"])} def get_element_attributes(self, args_dict): return {"message": self.course_fs.get_element_attributes(args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"])} def get_quiz_questions(self, args_dict): return {"message": self.course_fs.get_quiz_json(args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"])["questions"]} def submit_quiz(self, args_dict): quiz_mgr = QuizManager(self.course_fs.get_quiz_json( args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"])) scores = quiz_mgr.evaluate_answers( self._logged_user, args_dict["answers"]) quiz_mgr.add_attempt(self._logged_user, args_dict["answers"], scores) self.course_fs.edit_quiz( args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"], quiz_mgr.get_quiz_dict()) def get_user_attempts(self, args_dict): quiz_mgr = QuizManager(self.course_fs.get_quiz_json( args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"])) return quiz_mgr.get_user_attempts(self._logged_user) def load_lesson_html(self, args_dict): element_html = self.course_fs.get_lesson_html( args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"]) element_name = self.course_fs.get_element_attributes( args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"])["name"] webview.set_title(element_name) lesson_model = self._load_html_lesson_model() html_page = lesson_model.format( # title=element_title, content=element_html ) return {"message": re.sub('\s+', ' ', html_page)} @staticmethod def _load_html_lesson_model(): with urllib.request.urlopen("http://localhost:8080/html/lesson_model.html") as html_file: return html_file.read().decode("utf-8") def set_title(self, args_dict): webview.set_title(args_dict['title'])
from PermissionManager import PermissionManager from CourseFileSystem import CourseFileSystem from UserManager import UserManager from QuizManager import QuizManager from bs4 import BeautifulSoup from Error import Error import os import re import webview import threading import http.server import socketserver import urllib.request import sys class CourseApplication: def __init__(self, usermanager, user_id): api = Api(usermanager, user_id) t = threading.Thread(target=self.load_html) t1 = threading.Thread(target=self.start_local_html_server, args=[t]) t1.start() webview.config.gui = "cef" webview.create_window("Lezioni alla Pari", debug=True, js_api=api) @staticmethod def load_html(): with open(os.path.join("html", "index.html"), "r") as html: webview.load_html(html.read()) @staticmethod def start_local_html_server(t): port = 8080 handler = http.server.SimpleHTTPRequestHandler with socketserver.ThreadingTCPServer(("", port), handler) as httpd: t.start() httpd.serve_forever() class Api: def __init__(self, usermanager, user_id): self.user_mgr = usermanager self.permission_mgr = PermissionManager() self.course_fs = CourseFileSystem() self._logged_user = user_id def add_course(self, args_dict): id = self.course_fs.add_course(args_dict["course_name"]) self.permission_mgr.add_course(id) self.permission_mgr.add_permission(self._logged_user, id, "rw") return id def remove_course(self, course_id): self.course_fs.remove_course(course_id) self.permission_mgr.remove_course(course_id) return course_id def add_topic(self, args_dict): id = self.course_fs.add_topic( args_dict["topic_name"], args_dict["course_id"]) return id def remove_topic(self, args_dict): self.course_fs.remove_topic( args_dict["topic_id"], args_dict["course_id"]) return args_dict["topic_id"] def add_lesson(self, args_dict): id = self.course_fs.add_lesson(args_dict["element_name"], args_dict["topic_id"], args_dict["course_id"]) return id def edit_lesson(self, args_dict): self.course_fs.edit_lesson( args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"], args_dict["element_html"] ) def remove_element(self, args_dict): self.course_fs.remove_element( args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"]) return args_dict["element_id"] def list_courses(self, arg): return {"message": self.permission_mgr.get_user_permissions(self._logged_user)} def list_topics(self, args_dict): return {"message": self.course_fs.get_topics_list(args_dict["course_id"])} def list_elements(self, args_dict): return {"message": self.course_fs.get_elements_list(args_dict["topic_id"], args_dict["course_id"])} def get_course_attributes(self, args_dict): return {"message": self.course_fs.get_course_attributes(args_dict["course_id"])} def get_topic_attributes(self, args_dict): return {"message": self.course_fs.get_topic_attributes(args_dict["topic_id"], args_dict["course_id"])} def get_element_attributes(self, args_dict): return {"message": self.course_fs.get_element_attributes(args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"])} def get_quiz_questions(self, args_dict): return {"message": self.course_fs.get_quiz_json(args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"])["questions"]} def submit_quiz(self, args_dict): quiz_mgr = QuizManager(self.course_fs.get_quiz_json( args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"])) scores = quiz_mgr.evaluate_answers( self._logged_user, args_dict["answers"]) quiz_mgr.add_attempt(self._logged_user, args_dict["answers"], scores) self.course_fs.edit_quiz( args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"], quiz_mgr.get_quiz_dict()) def get_user_attempts(self, args_dict): quiz_mgr = QuizManager(self.course_fs.get_quiz_json( args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"])) return quiz_mgr.get_user_attempts(self._logged_user) def load_lesson_html(self, args_dict): element_html = self.course_fs.get_lesson_html( args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"]) element_name = self.course_fs.get_element_attributes( args_dict["element_id"], args_dict["topic_id"], args_dict["course_id"])["name"] webview.set_title(element_name) lesson_model = self._load_html_lesson_model() html_page = lesson_model.format( # title=element_title, content=element_html ) return {"message": re.sub('\s+', ' ', html_page)} @staticmethod def _load_html_lesson_model(): with urllib.request.urlopen("http://localhost:8080/html/lesson_model.html") as html_file: return html_file.read().decode("utf-8") def set_title(self, args_dict): webview.set_title(args_dict['title'])
ta
0.113348
# title=element_title,
2.299381
2
src/_pytest/_io/__init__.py
scorphus/pytest
2
6612712
from typing import List from typing import Sequence from py.io import TerminalWriter as BaseTerminalWriter # noqa: F401 class TerminalWriter(BaseTerminalWriter): def _write_source(self, lines: List[str], indents: Sequence[str] = ()) -> None: """Write lines of source code possibly highlighted. Keeping this private for now because the API is clunky. We should discuss how to evolve the terminal writer so we can have more precise color support, for example being able to write part of a line in one color and the rest in another, and so on. """ if indents and len(indents) != len(lines): raise ValueError( "indents size ({}) should have same size as lines ({})".format( len(indents), len(lines) ) ) if not indents: indents = [""] * len(lines) source = "\n".join(lines) new_lines = self._highlight(source).splitlines() for indent, new_line in zip(indents, new_lines): self.line(indent + new_line) def _highlight(self, source): """Highlight the given source code if we have markup support""" if not self.hasmarkup: return source try: from pygments.formatters.terminal import TerminalFormatter from pygments.lexers.python import PythonLexer from pygments import highlight except ImportError: return source else: return highlight(source, PythonLexer(), TerminalFormatter(bg="dark"))
from typing import List from typing import Sequence from py.io import TerminalWriter as BaseTerminalWriter # noqa: F401 class TerminalWriter(BaseTerminalWriter): def _write_source(self, lines: List[str], indents: Sequence[str] = ()) -> None: """Write lines of source code possibly highlighted. Keeping this private for now because the API is clunky. We should discuss how to evolve the terminal writer so we can have more precise color support, for example being able to write part of a line in one color and the rest in another, and so on. """ if indents and len(indents) != len(lines): raise ValueError( "indents size ({}) should have same size as lines ({})".format( len(indents), len(lines) ) ) if not indents: indents = [""] * len(lines) source = "\n".join(lines) new_lines = self._highlight(source).splitlines() for indent, new_line in zip(indents, new_lines): self.line(indent + new_line) def _highlight(self, source): """Highlight the given source code if we have markup support""" if not self.hasmarkup: return source try: from pygments.formatters.terminal import TerminalFormatter from pygments.lexers.python import PythonLexer from pygments import highlight except ImportError: return source else: return highlight(source, PythonLexer(), TerminalFormatter(bg="dark"))
en
0.905975
# noqa: F401 Write lines of source code possibly highlighted. Keeping this private for now because the API is clunky. We should discuss how to evolve the terminal writer so we can have more precise color support, for example being able to write part of a line in one color and the rest in another, and so on. Highlight the given source code if we have markup support
3.295616
3
test-runner/adapters/rest/generated/e2erestapi/aio/operations_async/__init__.py
brycewang-microsoft/iot-sdks-e2e-fx
12
6612713
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from ._system_control_operations_async import SystemControlOperations from ._control_operations_async import ControlOperations from ._device_operations_async import DeviceOperations from ._module_operations_async import ModuleOperations from ._service_operations_async import ServiceOperations from ._registry_operations_async import RegistryOperations __all__ = [ 'SystemControlOperations', 'ControlOperations', 'DeviceOperations', 'ModuleOperations', 'ServiceOperations', 'RegistryOperations', ]
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from ._system_control_operations_async import SystemControlOperations from ._control_operations_async import ControlOperations from ._device_operations_async import DeviceOperations from ._module_operations_async import ModuleOperations from ._service_operations_async import ServiceOperations from ._registry_operations_async import RegistryOperations __all__ = [ 'SystemControlOperations', 'ControlOperations', 'DeviceOperations', 'ModuleOperations', 'ServiceOperations', 'RegistryOperations', ]
en
0.442127
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # --------------------------------------------------------------------------
1.132113
1
imblearn/under_sampling/__init__.py
seabay/UnbalancedDataset
1
6612714
<reponame>seabay/UnbalancedDataset """ The :mod:`imblearn.under_sampling` provides methods to under-sample a dataset. """ from .prototype_generation import ClusterCentroids from .prototype_selection import RandomUnderSampler from .prototype_selection import TomekLinks from .prototype_selection import NearMiss from .prototype_selection import CondensedNearestNeighbour from .prototype_selection import OneSidedSelection from .prototype_selection import NeighbourhoodCleaningRule from .prototype_selection import EditedNearestNeighbours from .prototype_selection import RepeatedEditedNearestNeighbours from .prototype_selection import AllKNN from .prototype_selection import InstanceHardnessThreshold __all__ = [ 'ClusterCentroids', 'RandomUnderSampler', 'InstanceHardnessThreshold', 'NearMiss', 'TomekLinks', 'EditedNearestNeighbours', 'RepeatedEditedNearestNeighbours', 'AllKNN', 'OneSidedSelection', 'CondensedNearestNeighbour', 'NeighbourhoodCleaningRule' ]
""" The :mod:`imblearn.under_sampling` provides methods to under-sample a dataset. """ from .prototype_generation import ClusterCentroids from .prototype_selection import RandomUnderSampler from .prototype_selection import TomekLinks from .prototype_selection import NearMiss from .prototype_selection import CondensedNearestNeighbour from .prototype_selection import OneSidedSelection from .prototype_selection import NeighbourhoodCleaningRule from .prototype_selection import EditedNearestNeighbours from .prototype_selection import RepeatedEditedNearestNeighbours from .prototype_selection import AllKNN from .prototype_selection import InstanceHardnessThreshold __all__ = [ 'ClusterCentroids', 'RandomUnderSampler', 'InstanceHardnessThreshold', 'NearMiss', 'TomekLinks', 'EditedNearestNeighbours', 'RepeatedEditedNearestNeighbours', 'AllKNN', 'OneSidedSelection', 'CondensedNearestNeighbour', 'NeighbourhoodCleaningRule' ]
en
0.574605
The :mod:`imblearn.under_sampling` provides methods to under-sample a dataset.
1.655933
2
weibo/login/weiboMain.py
haiboz/weiboSpider
0
6612715
# coding:utf8 ''' Created on 2016年4月11日 @author: wb-zhaohaibo ''' from weibo.login.weiboLogin import WeiboLogin from weibo.spider import url_manager from weibo.spider import html_downloader from weibo.spider import html_parser from weibo.spider import html_outputer import spynner import time from _pyio import open from bs4 import BeautifulSoup class WeiboMain(object): def __init__(self): #记录用户粉丝url self.fansUrls = url_manager.UrlManager() #记录用户首页url self.userUrls = url_manager.UrlManager() self.downloader = html_downloader.HtmlDownloader() self.parser = html_parser.HtmlParser() self.outputer = html_outputer.Output() self.fansCount = 0 def parseDownPage(self,url): browser = spynner.Browser() #创建一个浏览器对象 browser.hide() #打开浏览器,并隐藏。 browser.load(url) #browser 类中有一个类方法load,可以用webkit加载你想加载的页面信息。 #load(是你想要加载的网址的字符串形式) htmlContent = browser.html.encode("utf-8") # htmlContent = open("Test.html", 'w+').write(browser.html.encode("utf-8")) #你也可以将它写到文件中,用浏览器打开。 print "htmlContent="+htmlContent return htmlContent #browser 类中有一个成员是html,是页面进过处理后的源码的字符串. htmlContent = open("Test.html", 'w+') def craw_user(self,user_url,count,userMaxCount): flag = 0 #下载粉丝主页 html_cont = self.downloader.download(user_url) self.outputer.user_html(html_cont) #获取用户信息详情页url detailUrl = self.parser.getDetailUrl(html_cont,user_url) #详情页url不为空 if detailUrl != "": #下载详情页 info_cont = self.downloader.download(detailUrl) #解析用户详细信息 new_data = self.parser.parseUserDetail(info_cont) #保存用户url new_data["userUrl"] = user_url print "已爬取 %d 个粉丝信息" % count if count > userMaxCount: flag = 1 count = count + 1 else: new_data = {} flag = 0 return new_data,flag,count def craw(self,root_url,userMaxCount,weiboMaxCount): #userMaxCount 控制爬取的微博用户最大数 #weiboMaxCount 控制爬取的微博内容最大数 #已爬取粉丝数 count = 1 #爬取微博最大数 weiboCoubt = 0 #爬取的页面数 pageCount = 1 #写入微博html的前半部 self.outputer.output_weibo_cont_bef() #写入粉丝html的前半部 self.outputer.output_weibo_fans_bef() #把当前主页加入到粉丝主页列表 self.fansUrls.add_new_fans_url(root_url) #判断粉丝列表是否有内容 粉丝列表存储的就是用户的主页url while self.fansUrls.has_new_fans_url(): #休眠10秒钟 print "程序休眠10秒钟。。。" time.sleep(10) try: new_user_url = self.fansUrls.get_new_fans_url() #获取用户主页的粉丝页面url--这是一个临时的url 不做存储 每个用户主页唯一对应一个粉丝页面url fansUrl = self.parser.getFansUrl(new_user_url) print "爬取第 %d 个粉丝页面地址: %s" % (pageCount,fansUrl) # fansUrl = "http://weibo.com/p/1005052739250252/follow?relate=fans&from=100505&wvr=6&mod=headfans&current=fans#place" #下载个人页面粉丝页面信息 html_cont = self.downloader.download(fansUrl) #输出个人页面粉丝页面信息 self.outputer.text_html(html_cont) #获取粉丝主页地址 new_user_urls = self.parser.parse(fansUrl,html_cont) if len(new_user_urls) == 0: print "粉丝列表加载失败" else: print "粉丝列表加载成功" #把新抓取的粉丝主页添加到用户主页url列表中 self.fansUrls.add_new_fans_urls(new_user_urls) pageCount = pageCount + 1 obj_spider = WeiboMain() for user_url in new_user_urls: #爬取粉丝基本信息 new_data,flag,count = obj_spider.craw_user(user_url,count,userMaxCount) #爬取发表的微博信息 list weibo_conts = obj_spider.craw_weiboCont(user_url) #收集用户数据 self.outputer.collect_data(new_data) #写入发表微博信息 只包含table内容部分 #如果发表数过少 过滤掉不获取微博内容 if len(weibo_conts) >= 10 : subCount = self.outputer.output_weibo_cont_html(weibo_conts) weiboCoubt = weiboCoubt + subCount print "已爬取微博数:%d" % weiboCoubt #如果超过限定数量的微博已经爬取 则结束 if weiboCoubt >= weiboMaxCount: flag = 1 if(flag == 1): break #写入粉丝基本信息 self.outputer.output_fans_html() #到达预设记录数 结束爬取 if(flag == 1): #写入微博内容html的后半部 self.outputer.output_weibo_cont_beh() #写入微博粉丝html的后半部 self.outputer.output_weibo_fans_beh() print "所有记录爬取完成!共爬取 %d 条微博!" % weiboCoubt break except Exception as e: print "该用户记录爬取失败!" print "weiboMain.craw:" + str(e) def craw_weiboCont(self, rootUrl): try: weibo_data = [] #下载微博主页页面信息 html_cont = self.downloader.download(rootUrl) soup = BeautifulSoup(html_cont,"html.parser",from_encoding="utf-8") tags = soup.findAll("script") if len(tags) > 1: #获取包含微博内容的script tag = tags[len(tags)-2].get_text() indexBegin = tag.find("<div") indexEnd = tag.rfind("<\/div>")#从 if indexBegin != -1 and indexEnd != -1: contStr = tag[indexBegin:indexEnd+7] #写入到临时网页中 weibo_temp.html self.outputer.output_weibo_temp(contStr) #获取临时文件 提取微博内容 weibo_data = self.parser.getWeiboCont() else: #未发表微博 pass else: print "微博内容爬取失败" except Exception as e: print "获取微博内容出错!" print "weiboMain.craw_weiboCont:"+str(e) raise e return weibo_data if __name__ == '__main__': startTime = time.time() username = '<EMAIL>'#微博账户 password = '<PASSWORD>'#微博密码 weiboLogin = WeiboLogin(username, password) if weiboLogin.Login() != True: print "登录失败!" else: print "登陆成功!username = "+username #正式访问 #主页地址 rootUrl = "http://weibo.com/u/5296704009?refer_flag=1005050012_" obj_spider = WeiboMain() #启动爬虫 rootUrl为用户主页 #微博用户最大数限制 userMaxCount = 1000 #微博内容最大数限制 weiboMaxCount = 1000 obj_spider.craw(rootUrl,userMaxCount,weiboMaxCount) endTime = time.time() si = endTime - startTime mi = (si % 3600)/60 hi = si/3600 print "系统共耗时 %d 秒" % si print "系统共耗时 %d 时 %d 分" % (hi,mi) # #测试下载用户基本信息详情页 # html_download = html_downloader.HtmlDownloader() # html_out = html_outputer.Output() # url = "http://weibo.com/p/1005055898067337/info?mod=pedit_more" # html_cont = html_download.download(url) # html_out.userDetail_html(html_cont) # #测试下载主页信息 获取微博内容 # html_download = html_downloader.HtmlDownloader() # html_out = html_outputer.Output() # url = "http://weibo.com/u/2515950453?refer_flag=1005050005_&is_all=1" # html_cont = html_download.download(url) # html_out.user_html(html_cont)
# coding:utf8 ''' Created on 2016年4月11日 @author: wb-zhaohaibo ''' from weibo.login.weiboLogin import WeiboLogin from weibo.spider import url_manager from weibo.spider import html_downloader from weibo.spider import html_parser from weibo.spider import html_outputer import spynner import time from _pyio import open from bs4 import BeautifulSoup class WeiboMain(object): def __init__(self): #记录用户粉丝url self.fansUrls = url_manager.UrlManager() #记录用户首页url self.userUrls = url_manager.UrlManager() self.downloader = html_downloader.HtmlDownloader() self.parser = html_parser.HtmlParser() self.outputer = html_outputer.Output() self.fansCount = 0 def parseDownPage(self,url): browser = spynner.Browser() #创建一个浏览器对象 browser.hide() #打开浏览器,并隐藏。 browser.load(url) #browser 类中有一个类方法load,可以用webkit加载你想加载的页面信息。 #load(是你想要加载的网址的字符串形式) htmlContent = browser.html.encode("utf-8") # htmlContent = open("Test.html", 'w+').write(browser.html.encode("utf-8")) #你也可以将它写到文件中,用浏览器打开。 print "htmlContent="+htmlContent return htmlContent #browser 类中有一个成员是html,是页面进过处理后的源码的字符串. htmlContent = open("Test.html", 'w+') def craw_user(self,user_url,count,userMaxCount): flag = 0 #下载粉丝主页 html_cont = self.downloader.download(user_url) self.outputer.user_html(html_cont) #获取用户信息详情页url detailUrl = self.parser.getDetailUrl(html_cont,user_url) #详情页url不为空 if detailUrl != "": #下载详情页 info_cont = self.downloader.download(detailUrl) #解析用户详细信息 new_data = self.parser.parseUserDetail(info_cont) #保存用户url new_data["userUrl"] = user_url print "已爬取 %d 个粉丝信息" % count if count > userMaxCount: flag = 1 count = count + 1 else: new_data = {} flag = 0 return new_data,flag,count def craw(self,root_url,userMaxCount,weiboMaxCount): #userMaxCount 控制爬取的微博用户最大数 #weiboMaxCount 控制爬取的微博内容最大数 #已爬取粉丝数 count = 1 #爬取微博最大数 weiboCoubt = 0 #爬取的页面数 pageCount = 1 #写入微博html的前半部 self.outputer.output_weibo_cont_bef() #写入粉丝html的前半部 self.outputer.output_weibo_fans_bef() #把当前主页加入到粉丝主页列表 self.fansUrls.add_new_fans_url(root_url) #判断粉丝列表是否有内容 粉丝列表存储的就是用户的主页url while self.fansUrls.has_new_fans_url(): #休眠10秒钟 print "程序休眠10秒钟。。。" time.sleep(10) try: new_user_url = self.fansUrls.get_new_fans_url() #获取用户主页的粉丝页面url--这是一个临时的url 不做存储 每个用户主页唯一对应一个粉丝页面url fansUrl = self.parser.getFansUrl(new_user_url) print "爬取第 %d 个粉丝页面地址: %s" % (pageCount,fansUrl) # fansUrl = "http://weibo.com/p/1005052739250252/follow?relate=fans&from=100505&wvr=6&mod=headfans&current=fans#place" #下载个人页面粉丝页面信息 html_cont = self.downloader.download(fansUrl) #输出个人页面粉丝页面信息 self.outputer.text_html(html_cont) #获取粉丝主页地址 new_user_urls = self.parser.parse(fansUrl,html_cont) if len(new_user_urls) == 0: print "粉丝列表加载失败" else: print "粉丝列表加载成功" #把新抓取的粉丝主页添加到用户主页url列表中 self.fansUrls.add_new_fans_urls(new_user_urls) pageCount = pageCount + 1 obj_spider = WeiboMain() for user_url in new_user_urls: #爬取粉丝基本信息 new_data,flag,count = obj_spider.craw_user(user_url,count,userMaxCount) #爬取发表的微博信息 list weibo_conts = obj_spider.craw_weiboCont(user_url) #收集用户数据 self.outputer.collect_data(new_data) #写入发表微博信息 只包含table内容部分 #如果发表数过少 过滤掉不获取微博内容 if len(weibo_conts) >= 10 : subCount = self.outputer.output_weibo_cont_html(weibo_conts) weiboCoubt = weiboCoubt + subCount print "已爬取微博数:%d" % weiboCoubt #如果超过限定数量的微博已经爬取 则结束 if weiboCoubt >= weiboMaxCount: flag = 1 if(flag == 1): break #写入粉丝基本信息 self.outputer.output_fans_html() #到达预设记录数 结束爬取 if(flag == 1): #写入微博内容html的后半部 self.outputer.output_weibo_cont_beh() #写入微博粉丝html的后半部 self.outputer.output_weibo_fans_beh() print "所有记录爬取完成!共爬取 %d 条微博!" % weiboCoubt break except Exception as e: print "该用户记录爬取失败!" print "weiboMain.craw:" + str(e) def craw_weiboCont(self, rootUrl): try: weibo_data = [] #下载微博主页页面信息 html_cont = self.downloader.download(rootUrl) soup = BeautifulSoup(html_cont,"html.parser",from_encoding="utf-8") tags = soup.findAll("script") if len(tags) > 1: #获取包含微博内容的script tag = tags[len(tags)-2].get_text() indexBegin = tag.find("<div") indexEnd = tag.rfind("<\/div>")#从 if indexBegin != -1 and indexEnd != -1: contStr = tag[indexBegin:indexEnd+7] #写入到临时网页中 weibo_temp.html self.outputer.output_weibo_temp(contStr) #获取临时文件 提取微博内容 weibo_data = self.parser.getWeiboCont() else: #未发表微博 pass else: print "微博内容爬取失败" except Exception as e: print "获取微博内容出错!" print "weiboMain.craw_weiboCont:"+str(e) raise e return weibo_data if __name__ == '__main__': startTime = time.time() username = '<EMAIL>'#微博账户 password = '<PASSWORD>'#微博密码 weiboLogin = WeiboLogin(username, password) if weiboLogin.Login() != True: print "登录失败!" else: print "登陆成功!username = "+username #正式访问 #主页地址 rootUrl = "http://weibo.com/u/5296704009?refer_flag=1005050012_" obj_spider = WeiboMain() #启动爬虫 rootUrl为用户主页 #微博用户最大数限制 userMaxCount = 1000 #微博内容最大数限制 weiboMaxCount = 1000 obj_spider.craw(rootUrl,userMaxCount,weiboMaxCount) endTime = time.time() si = endTime - startTime mi = (si % 3600)/60 hi = si/3600 print "系统共耗时 %d 秒" % si print "系统共耗时 %d 时 %d 分" % (hi,mi) # #测试下载用户基本信息详情页 # html_download = html_downloader.HtmlDownloader() # html_out = html_outputer.Output() # url = "http://weibo.com/p/1005055898067337/info?mod=pedit_more" # html_cont = html_download.download(url) # html_out.userDetail_html(html_cont) # #测试下载主页信息 获取微博内容 # html_download = html_downloader.HtmlDownloader() # html_out = html_outputer.Output() # url = "http://weibo.com/u/2515950453?refer_flag=1005050005_&is_all=1" # html_cont = html_download.download(url) # html_out.user_html(html_cont)
zh
0.861491
# coding:utf8 Created on 2016年4月11日 @author: wb-zhaohaibo #记录用户粉丝url #记录用户首页url #创建一个浏览器对象 #打开浏览器,并隐藏。 #browser 类中有一个类方法load,可以用webkit加载你想加载的页面信息。 #load(是你想要加载的网址的字符串形式) # htmlContent = open("Test.html", 'w+').write(browser.html.encode("utf-8")) #你也可以将它写到文件中,用浏览器打开。 #browser 类中有一个成员是html,是页面进过处理后的源码的字符串. #下载粉丝主页 #获取用户信息详情页url #详情页url不为空 #下载详情页 #解析用户详细信息 #保存用户url #userMaxCount 控制爬取的微博用户最大数 #weiboMaxCount 控制爬取的微博内容最大数 #已爬取粉丝数 #爬取微博最大数 #爬取的页面数 #写入微博html的前半部 #写入粉丝html的前半部 #把当前主页加入到粉丝主页列表 #判断粉丝列表是否有内容 粉丝列表存储的就是用户的主页url #休眠10秒钟 #获取用户主页的粉丝页面url--这是一个临时的url 不做存储 每个用户主页唯一对应一个粉丝页面url # fansUrl = "http://weibo.com/p/1005052739250252/follow?relate=fans&from=100505&wvr=6&mod=headfans&current=fans#place" #下载个人页面粉丝页面信息 #输出个人页面粉丝页面信息 #获取粉丝主页地址 #把新抓取的粉丝主页添加到用户主页url列表中 #爬取粉丝基本信息 #爬取发表的微博信息 list #收集用户数据 #写入发表微博信息 只包含table内容部分 #如果发表数过少 过滤掉不获取微博内容 #如果超过限定数量的微博已经爬取 则结束 #写入粉丝基本信息 #到达预设记录数 结束爬取 #写入微博内容html的后半部 #写入微博粉丝html的后半部 #下载微博主页页面信息 #获取包含微博内容的script #从 #写入到临时网页中 weibo_temp.html #获取临时文件 提取微博内容 #未发表微博 #正式访问 #主页地址 #启动爬虫 rootUrl为用户主页 #微博用户最大数限制 #微博内容最大数限制 # #测试下载用户基本信息详情页 # html_download = html_downloader.HtmlDownloader() # html_out = html_outputer.Output() # url = "http://weibo.com/p/1005055898067337/info?mod=pedit_more" # html_cont = html_download.download(url) # html_out.userDetail_html(html_cont) # #测试下载主页信息 获取微博内容 # html_download = html_downloader.HtmlDownloader() # html_out = html_outputer.Output() # url = "http://weibo.com/u/2515950453?refer_flag=1005050005_&is_all=1" # html_cont = html_download.download(url) # html_out.user_html(html_cont)
2.658036
3
src/purchase/views.py
ResearchHub/ResearchHub-Backend-Open
18
6612716
import time import datetime import stripe import decimal import json from django.core.cache import cache from django.contrib.contenttypes.models import ContentType from django.db import transaction from rest_framework import status, viewsets from rest_framework.decorators import action from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response from rest_framework.permissions import ( IsAuthenticated ) from paper.models import Paper from researchhub_document.models import ResearchhubPost from paper.utils import ( get_cache_key, invalidate_top_rated_cache, invalidate_newest_cache, invalidate_most_discussed_cache, ) from purchase.models import ( Purchase, Balance, AggregatePurchase, Wallet, Support ) from purchase.serializers import ( PurchaseSerializer, AggregatePurchaseSerializer, WalletSerializer, SupportSerializer ) from notification.models import Notification from purchase.tasks import send_support_email from utils.throttles import THROTTLE_CLASSES from utils.http import http_request, RequestMethods from utils.permissions import CreateOrUpdateOrReadOnly, CreateOrUpdateIfAllowed from user.models import User, Author, Action from user.serializers import UserSerializer from researchhub.settings import ASYNC_SERVICE_HOST, BASE_FRONTEND_URL from reputation.models import Contribution from reputation.tasks import create_contribution from reputation.distributions import create_purchase_distribution from reputation.distributor import Distributor class PurchaseViewSet(viewsets.ModelViewSet): queryset = Purchase.objects.all() serializer_class = PurchaseSerializer permission_classes = [ IsAuthenticated, CreateOrUpdateOrReadOnly, CreateOrUpdateIfAllowed ] pagination_class = PageNumberPagination throttle_classes = THROTTLE_CLASSES def create(self, request): user = request.user data = request.data amount = data['amount'] purchase_method = data['purchase_method'] purchase_type = data['purchase_type'] content_type_str = data['content_type'] content_type = ContentType.objects.get(model=content_type_str) object_id = data['object_id'] transfer_rsc = False recipient = None with transaction.atomic(): if purchase_method == Purchase.ON_CHAIN: purchase = Purchase.objects.create( user=user, content_type=content_type, object_id=object_id, purchase_method=purchase_method, purchase_type=purchase_type, amount=amount ) else: user_balance = user.get_balance() decimal_amount = decimal.Decimal(amount) if user_balance - decimal_amount < 0: return Response('Insufficient Funds', status=402) purchase = Purchase.objects.create( user=user, content_type=content_type, object_id=object_id, purchase_method=purchase_method, purchase_type=purchase_type, amount=amount, paid_status=Purchase.PAID ) source_type = ContentType.objects.get_for_model(purchase) Balance.objects.create( user=user, content_type=source_type, object_id=purchase.id, amount=f'-{amount}', ) purchase_hash = purchase.hash() purchase.purchase_hash = purchase_hash purchase_boost_time = purchase.get_boost_time(amount) purchase.boost_time = purchase_boost_time purchase.group = purchase.get_aggregate_group() purchase.save() item = purchase.item context = { 'purchase_minimal_serialization': True, 'exclude_stats': True } # transfer_rsc is set each time just in case we want # to disable rsc transfer for a specific item if content_type_str == 'paper': paper = Paper.objects.get(id=object_id) unified_doc = paper.unified_document paper.calculate_hot_score() recipient = paper.uploaded_by cache_key = get_cache_key('paper', object_id) cache.delete(cache_key) transfer_rsc = True # invalidate_trending_cache([]) invalidate_top_rated_cache([]) invalidate_most_discussed_cache([]) invalidate_newest_cache([]) elif content_type_str == 'thread': transfer_rsc = True recipient = item.created_by unified_doc = item.unified_document elif content_type_str == 'comment': transfer_rsc = True unified_doc = item.unified_document recipient = item.created_by elif content_type_str == 'reply': transfer_rsc = True unified_doc = item.unified_document recipient = item.created_by elif content_type_str == 'summary': transfer_rsc = True recipient = item.proposed_by unified_doc = item.paper.unified_document elif content_type_str == 'bulletpoint': transfer_rsc = True recipient = item.created_by unified_doc = item.paper.unified_document elif content_type_str == 'researchhubpost': transfer_rsc = True recipient = item.created_by unified_doc = item.unified_document invalidate_top_rated_cache([]) invalidate_most_discussed_cache([]) invalidate_newest_cache([]) if unified_doc.is_removed: return Response('Content is removed', status=403) if transfer_rsc and recipient and recipient != user: distribution = create_purchase_distribution(amount) distributor = Distributor( distribution, recipient, purchase, time.time() ) distributor.distribute() serializer = self.serializer_class(purchase, context=context) serializer_data = serializer.data if recipient and user: self.send_purchase_notification( purchase, unified_doc, recipient ) self.send_purchase_email(purchase, recipient, unified_doc) create_contribution.apply_async( ( Contribution.SUPPORTER, {'app_label': 'purchase', 'model': 'purchase'}, user.id, unified_doc.id, purchase.id ), priority=2, countdown=10 ) return Response(serializer_data, status=201) def update(self, request, *args, **kwargs): response = super().update(request, *args, **kwargs) purchase = self.get_object() purchase.group = purchase.get_aggregate_group() purchase.save() if purchase.transaction_hash: self.track_paid_status(purchase.id, purchase.transaction_hash) return response def track_paid_status(self, purchase_id, transaction_hash): url = ASYNC_SERVICE_HOST + '/ethereum/track_purchase' data = { 'purchase': purchase_id, 'transaction_hash': transaction_hash } response = http_request( RequestMethods.POST, url, data=json.dumps(data), timeout=3 ) response.raise_for_status() return response @action( detail=True, methods=['get'], permission_classes=[IsAuthenticated] ) def aggregate_user_promotions(self, request, pk=None): user = User.objects.get(id=pk) context = self.get_serializer_context() context['purchase_minimal_serialization'] = True paper_content_type_id = ContentType.objects.get_for_model(Paper).id post_content_type_id = ContentType.objects.get_for_model(ResearchhubPost).id groups = AggregatePurchase.objects.filter( user=user, content_type_id__in=[paper_content_type_id, post_content_type_id], ) page = self.paginate_queryset(groups) if page is not None: serializer = AggregatePurchaseSerializer( page, many=True, context=context ) return self.get_paginated_response(serializer.data) serializer = AggregatePurchaseSerializer( groups, context=context, many=True ) return Response(serializer.data, status=status.HTTP_200_OK) @action( detail=True, methods=['get'], permission_classes=[IsAuthenticated] ) def user_promotions(self, request, pk=None): context = self.get_serializer_context() context['purchase_minimal_serialization'] = True user = User.objects.get(id=pk) queryset = Purchase.objects.filter(user=user).order_by( '-created_date', 'object_id' ) page = self.paginate_queryset(queryset) if page is not None: serializer = self.serializer_class( page, many=True, context=context ) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def send_purchase_notification( self, purchase, unified_doc, recipient, ): creator = purchase.user if creator == recipient: return content_type = ContentType.objects.get_for_model(purchase) action = Action.objects.create( user=recipient, content_type=content_type, object_id=purchase.id, ) notification = Notification.objects.create( unified_document=unified_doc, recipient=recipient, action_user=creator, action=action, ) notification.send_notification() def send_purchase_email(self, purchase, recipient, unified_doc): sender = purchase.user if sender == recipient: return # TODO: Add email support for posts paper = unified_doc.paper if not paper: return else: paper_id = paper.id sender_balance_date = datetime.datetime.now().strftime( '%m/%d/%Y' ) amount = purchase.amount payment_type = purchase.purchase_method content_type_str = purchase.content_type.model object_id = purchase.object_id send_support_email.apply_async( ( f'{BASE_FRONTEND_URL}/user/{sender.author_profile.id}/overview', sender.full_name(), recipient.full_name(), recipient.email, amount, sender_balance_date, payment_type, 'recipient', content_type_str, object_id, paper_id ), priority=6, countdown=2 ) send_support_email.apply_async( ( f'{BASE_FRONTEND_URL}/user/{recipient.author_profile.id}/overview', sender.full_name(), recipient.full_name(), sender.email, amount, sender_balance_date, payment_type, 'sender', content_type_str, object_id, paper_id ), priority=6, countdown=2 ) class SupportViewSet(viewsets.ModelViewSet): queryset = Support.objects.all() serializer_class = SupportSerializer permission_classes = [ IsAuthenticated, CreateOrUpdateOrReadOnly, CreateOrUpdateIfAllowed ] throttle_classes = THROTTLE_CLASSES @action( detail=False, methods=['get'], permission_classes=[CreateOrUpdateOrReadOnly] ) def get_supported(self, request): paper_id = request.query_params.get('paper_id') author_id = request.query_params.get('author_id') if paper_id: paper_type = ContentType.objects.get(model='paper') supports = self.queryset.filter( content_type=paper_type, object_id=paper_id ) elif author_id: author_type = ContentType.objects.get(model='author') supports = self.queryset.filter( content_type=author_type, object_id=author_id ) else: return Response({'message': 'No query param included'}, status=400) user_ids = supports.values_list('sender', flat=True) users = User.objects.filter(id__in=user_ids, is_suspended=False) page = self.paginate_queryset(users) if page is not None: serializer = UserSerializer(page, many=True) return self.get_paginated_response(serializer.data) return Response({'message': 'Error'}, status=400) def create(self, request): sender = request.user data = request.data payment_option = data['payment_option'] payment_type = data['payment_type'] sender_id = data['user_id'] recipient_id = data['recipient_id'] recipient = Author.objects.get(id=recipient_id) recipient_user = recipient.user amount = data['amount'] content_type_str = data['content_type'] content_type = ContentType.objects.get(model=content_type_str) object_id = data['object_id'] # User check if sender.id != sender_id: return Response(status=400) # Balance check if payment_type == Support.RSC_OFF_CHAIN: sender_balance = sender.get_balance() decimal_amount = decimal.Decimal(amount) if sender_balance - decimal_amount < 0: return Response('Insufficient Funds', status=402) with transaction.atomic(): support = Support.objects.create( payment_type=payment_type, duration=payment_option, amount=amount, content_type=content_type, object_id=object_id, sender=sender, recipient=recipient_user ) source_type = ContentType.objects.get_for_model(support) if payment_type == Support.RSC_OFF_CHAIN: # Subtracting balance from user sender_bal = Balance.objects.create( user=sender, content_type=source_type, object_id=support.id, amount=f'-{amount}', ) # Adding balance to recipient recipient_bal = Balance.objects.create( user=recipient_user, content_type=source_type, object_id=support.id, amount=amount, ) sender_balance_date = sender_bal.created_date.strftime( '%m/%d/%Y' ) recipient_balance_date = recipient_bal.created_date.strftime( '%m/%d/%Y' ) elif payment_type == Support.STRIPE: recipient_stripe_acc = recipient.wallet.stripe_acc if not recipient_stripe_acc: return Response( 'Author has not created a Stripe Account', status=403 ) payment_intent = stripe.PaymentIntent.create( payment_method_types=['card'], amount=amount * 100, # The amount in cents currency='usd', application_fee_amount=0, transfer_data={ 'destination': recipient_stripe_acc } ) support.proof = payment_intent support.save() data['client_secret'] = payment_intent['client_secret'] sender_balance_date = datetime.datetime.now().strftime( '%m/%d/%Y' ) recipient_balance_date = datetime.datetime.now().strftime( '%m/%d/%Y' ) send_support_email.apply_async( ( f'{BASE_FRONTEND_URL}/user/{recipient.id}/overview', sender.full_name(), recipient_user.full_name(), sender.email, amount, sender_balance_date, payment_type, 'sender', content_type_str, object_id ), priority=6, countdown=2 ) send_support_email.apply_async( ( f'{BASE_FRONTEND_URL}/user/{sender.author_profile.id}/overview', sender.full_name(), recipient_user.full_name(), recipient_user.email, amount, recipient_balance_date, payment_type, 'recipient', content_type_str, object_id ), priority=6, countdown=2, ) sender_data = UserSerializer(sender).data response_data = {'user': sender_data, **data} return Response(response_data, status=200) class StripeViewSet(viewsets.ModelViewSet): queryset = Wallet.objects.all() serializer_class = WalletSerializer permission_classes = [] throttle_classes = [] @action( detail=False, methods=['post'], permission_classes=[IsAuthenticated] ) def onboard_stripe_account(self, request): user = request.user wallet = user.author_profile.wallet if not wallet.stripe_acc or not wallet.stripe_verified: acc = stripe.Account.create( type='express', country='US', # This is where our business resides email=user.email, capabilities={ 'card_payments': {'requested': True}, 'transfers': {'requested': True}, }, ) wallet.stripe_acc = acc['id'] wallet.save() elif wallet: account_links = stripe.Account.create_login_link(wallet.stripe_acc) return Response(account_links, status=200) refresh_url = request.data['refresh_url'] return_url = request.data['return_url'] try: account_links = stripe.AccountLink.create( account=wallet.stripe_acc, refresh_url=refresh_url, return_url=return_url, type='account_onboarding' ) except Exception as e: return Response(e, status=400) return Response(account_links, status=200) @action( detail=True, methods=['get'] ) def verify_stripe_account(self, request, pk=None): author = Author.objects.get(id=pk) wallet = author.wallet stripe_id = wallet.stripe_acc acc = stripe.Account.retrieve(stripe_id) redirect = f'{BASE_FRONTEND_URL}/user/{pk}/stripe?verify_stripe=true' account_links = stripe.Account.create_login_link( stripe_id, redirect_url=redirect ) if acc['charges_enabled']: wallet.stripe_verified = True wallet.save() return Response({**account_links}, status=200) return Response( { 'reason': 'Please complete verification via Stripe Dashboard', **account_links }, status=200 ) @action(detail=False, methods=['post']) def stripe_capability_updated(self, request): data = request.data acc_id = data['account'] acc_obj = data['data']['object'] status = acc_obj['status'] capability_type = acc_obj['id'] requirements = acc_obj['requirements'] currently_due = requirements['currently_due'] id_due = 'individual.id_number' in currently_due id_verf_due = 'individual.verification.document' in currently_due if capability_type != 'transfers' or status == 'pending': return Response(status=200) wallet = self.queryset.get(stripe_acc=acc_id) user = wallet.author.user if status == 'active' and not wallet.stripe_verified: account_links = stripe.Account.create_login_link(acc_id) wallet.stripe_verified = True wallet.save() self._send_stripe_notification( user, status, 'Your Stripe account has been verified', **account_links ) elif status == 'active' and wallet.stripe_verified: return Response(status=200) if not id_due and not id_verf_due and not len(currently_due) <= 2: return Response(status=200) try: account_links = stripe.Account.create_login_link(acc_id) except Exception as e: return Response(e, status=200) message = '' if id_due: message = """ Social Security Number or other government identification """ elif id_verf_due: message = """ Documents pertaining to government identification """ self._send_stripe_notification( user, status, message, **account_links ) return Response(status=200) def _send_stripe_notification(self, user, status, message, **kwargs): user_id = user.id user_type = ContentType.objects.get(model='user') action = Action.objects.create( user=user, content_type=user_type, object_id=user_id, ) notification = Notification.objects.create( recipient=user, action_user=user, action=action, ) notification.send_notification()
import time import datetime import stripe import decimal import json from django.core.cache import cache from django.contrib.contenttypes.models import ContentType from django.db import transaction from rest_framework import status, viewsets from rest_framework.decorators import action from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response from rest_framework.permissions import ( IsAuthenticated ) from paper.models import Paper from researchhub_document.models import ResearchhubPost from paper.utils import ( get_cache_key, invalidate_top_rated_cache, invalidate_newest_cache, invalidate_most_discussed_cache, ) from purchase.models import ( Purchase, Balance, AggregatePurchase, Wallet, Support ) from purchase.serializers import ( PurchaseSerializer, AggregatePurchaseSerializer, WalletSerializer, SupportSerializer ) from notification.models import Notification from purchase.tasks import send_support_email from utils.throttles import THROTTLE_CLASSES from utils.http import http_request, RequestMethods from utils.permissions import CreateOrUpdateOrReadOnly, CreateOrUpdateIfAllowed from user.models import User, Author, Action from user.serializers import UserSerializer from researchhub.settings import ASYNC_SERVICE_HOST, BASE_FRONTEND_URL from reputation.models import Contribution from reputation.tasks import create_contribution from reputation.distributions import create_purchase_distribution from reputation.distributor import Distributor class PurchaseViewSet(viewsets.ModelViewSet): queryset = Purchase.objects.all() serializer_class = PurchaseSerializer permission_classes = [ IsAuthenticated, CreateOrUpdateOrReadOnly, CreateOrUpdateIfAllowed ] pagination_class = PageNumberPagination throttle_classes = THROTTLE_CLASSES def create(self, request): user = request.user data = request.data amount = data['amount'] purchase_method = data['purchase_method'] purchase_type = data['purchase_type'] content_type_str = data['content_type'] content_type = ContentType.objects.get(model=content_type_str) object_id = data['object_id'] transfer_rsc = False recipient = None with transaction.atomic(): if purchase_method == Purchase.ON_CHAIN: purchase = Purchase.objects.create( user=user, content_type=content_type, object_id=object_id, purchase_method=purchase_method, purchase_type=purchase_type, amount=amount ) else: user_balance = user.get_balance() decimal_amount = decimal.Decimal(amount) if user_balance - decimal_amount < 0: return Response('Insufficient Funds', status=402) purchase = Purchase.objects.create( user=user, content_type=content_type, object_id=object_id, purchase_method=purchase_method, purchase_type=purchase_type, amount=amount, paid_status=Purchase.PAID ) source_type = ContentType.objects.get_for_model(purchase) Balance.objects.create( user=user, content_type=source_type, object_id=purchase.id, amount=f'-{amount}', ) purchase_hash = purchase.hash() purchase.purchase_hash = purchase_hash purchase_boost_time = purchase.get_boost_time(amount) purchase.boost_time = purchase_boost_time purchase.group = purchase.get_aggregate_group() purchase.save() item = purchase.item context = { 'purchase_minimal_serialization': True, 'exclude_stats': True } # transfer_rsc is set each time just in case we want # to disable rsc transfer for a specific item if content_type_str == 'paper': paper = Paper.objects.get(id=object_id) unified_doc = paper.unified_document paper.calculate_hot_score() recipient = paper.uploaded_by cache_key = get_cache_key('paper', object_id) cache.delete(cache_key) transfer_rsc = True # invalidate_trending_cache([]) invalidate_top_rated_cache([]) invalidate_most_discussed_cache([]) invalidate_newest_cache([]) elif content_type_str == 'thread': transfer_rsc = True recipient = item.created_by unified_doc = item.unified_document elif content_type_str == 'comment': transfer_rsc = True unified_doc = item.unified_document recipient = item.created_by elif content_type_str == 'reply': transfer_rsc = True unified_doc = item.unified_document recipient = item.created_by elif content_type_str == 'summary': transfer_rsc = True recipient = item.proposed_by unified_doc = item.paper.unified_document elif content_type_str == 'bulletpoint': transfer_rsc = True recipient = item.created_by unified_doc = item.paper.unified_document elif content_type_str == 'researchhubpost': transfer_rsc = True recipient = item.created_by unified_doc = item.unified_document invalidate_top_rated_cache([]) invalidate_most_discussed_cache([]) invalidate_newest_cache([]) if unified_doc.is_removed: return Response('Content is removed', status=403) if transfer_rsc and recipient and recipient != user: distribution = create_purchase_distribution(amount) distributor = Distributor( distribution, recipient, purchase, time.time() ) distributor.distribute() serializer = self.serializer_class(purchase, context=context) serializer_data = serializer.data if recipient and user: self.send_purchase_notification( purchase, unified_doc, recipient ) self.send_purchase_email(purchase, recipient, unified_doc) create_contribution.apply_async( ( Contribution.SUPPORTER, {'app_label': 'purchase', 'model': 'purchase'}, user.id, unified_doc.id, purchase.id ), priority=2, countdown=10 ) return Response(serializer_data, status=201) def update(self, request, *args, **kwargs): response = super().update(request, *args, **kwargs) purchase = self.get_object() purchase.group = purchase.get_aggregate_group() purchase.save() if purchase.transaction_hash: self.track_paid_status(purchase.id, purchase.transaction_hash) return response def track_paid_status(self, purchase_id, transaction_hash): url = ASYNC_SERVICE_HOST + '/ethereum/track_purchase' data = { 'purchase': purchase_id, 'transaction_hash': transaction_hash } response = http_request( RequestMethods.POST, url, data=json.dumps(data), timeout=3 ) response.raise_for_status() return response @action( detail=True, methods=['get'], permission_classes=[IsAuthenticated] ) def aggregate_user_promotions(self, request, pk=None): user = User.objects.get(id=pk) context = self.get_serializer_context() context['purchase_minimal_serialization'] = True paper_content_type_id = ContentType.objects.get_for_model(Paper).id post_content_type_id = ContentType.objects.get_for_model(ResearchhubPost).id groups = AggregatePurchase.objects.filter( user=user, content_type_id__in=[paper_content_type_id, post_content_type_id], ) page = self.paginate_queryset(groups) if page is not None: serializer = AggregatePurchaseSerializer( page, many=True, context=context ) return self.get_paginated_response(serializer.data) serializer = AggregatePurchaseSerializer( groups, context=context, many=True ) return Response(serializer.data, status=status.HTTP_200_OK) @action( detail=True, methods=['get'], permission_classes=[IsAuthenticated] ) def user_promotions(self, request, pk=None): context = self.get_serializer_context() context['purchase_minimal_serialization'] = True user = User.objects.get(id=pk) queryset = Purchase.objects.filter(user=user).order_by( '-created_date', 'object_id' ) page = self.paginate_queryset(queryset) if page is not None: serializer = self.serializer_class( page, many=True, context=context ) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def send_purchase_notification( self, purchase, unified_doc, recipient, ): creator = purchase.user if creator == recipient: return content_type = ContentType.objects.get_for_model(purchase) action = Action.objects.create( user=recipient, content_type=content_type, object_id=purchase.id, ) notification = Notification.objects.create( unified_document=unified_doc, recipient=recipient, action_user=creator, action=action, ) notification.send_notification() def send_purchase_email(self, purchase, recipient, unified_doc): sender = purchase.user if sender == recipient: return # TODO: Add email support for posts paper = unified_doc.paper if not paper: return else: paper_id = paper.id sender_balance_date = datetime.datetime.now().strftime( '%m/%d/%Y' ) amount = purchase.amount payment_type = purchase.purchase_method content_type_str = purchase.content_type.model object_id = purchase.object_id send_support_email.apply_async( ( f'{BASE_FRONTEND_URL}/user/{sender.author_profile.id}/overview', sender.full_name(), recipient.full_name(), recipient.email, amount, sender_balance_date, payment_type, 'recipient', content_type_str, object_id, paper_id ), priority=6, countdown=2 ) send_support_email.apply_async( ( f'{BASE_FRONTEND_URL}/user/{recipient.author_profile.id}/overview', sender.full_name(), recipient.full_name(), sender.email, amount, sender_balance_date, payment_type, 'sender', content_type_str, object_id, paper_id ), priority=6, countdown=2 ) class SupportViewSet(viewsets.ModelViewSet): queryset = Support.objects.all() serializer_class = SupportSerializer permission_classes = [ IsAuthenticated, CreateOrUpdateOrReadOnly, CreateOrUpdateIfAllowed ] throttle_classes = THROTTLE_CLASSES @action( detail=False, methods=['get'], permission_classes=[CreateOrUpdateOrReadOnly] ) def get_supported(self, request): paper_id = request.query_params.get('paper_id') author_id = request.query_params.get('author_id') if paper_id: paper_type = ContentType.objects.get(model='paper') supports = self.queryset.filter( content_type=paper_type, object_id=paper_id ) elif author_id: author_type = ContentType.objects.get(model='author') supports = self.queryset.filter( content_type=author_type, object_id=author_id ) else: return Response({'message': 'No query param included'}, status=400) user_ids = supports.values_list('sender', flat=True) users = User.objects.filter(id__in=user_ids, is_suspended=False) page = self.paginate_queryset(users) if page is not None: serializer = UserSerializer(page, many=True) return self.get_paginated_response(serializer.data) return Response({'message': 'Error'}, status=400) def create(self, request): sender = request.user data = request.data payment_option = data['payment_option'] payment_type = data['payment_type'] sender_id = data['user_id'] recipient_id = data['recipient_id'] recipient = Author.objects.get(id=recipient_id) recipient_user = recipient.user amount = data['amount'] content_type_str = data['content_type'] content_type = ContentType.objects.get(model=content_type_str) object_id = data['object_id'] # User check if sender.id != sender_id: return Response(status=400) # Balance check if payment_type == Support.RSC_OFF_CHAIN: sender_balance = sender.get_balance() decimal_amount = decimal.Decimal(amount) if sender_balance - decimal_amount < 0: return Response('Insufficient Funds', status=402) with transaction.atomic(): support = Support.objects.create( payment_type=payment_type, duration=payment_option, amount=amount, content_type=content_type, object_id=object_id, sender=sender, recipient=recipient_user ) source_type = ContentType.objects.get_for_model(support) if payment_type == Support.RSC_OFF_CHAIN: # Subtracting balance from user sender_bal = Balance.objects.create( user=sender, content_type=source_type, object_id=support.id, amount=f'-{amount}', ) # Adding balance to recipient recipient_bal = Balance.objects.create( user=recipient_user, content_type=source_type, object_id=support.id, amount=amount, ) sender_balance_date = sender_bal.created_date.strftime( '%m/%d/%Y' ) recipient_balance_date = recipient_bal.created_date.strftime( '%m/%d/%Y' ) elif payment_type == Support.STRIPE: recipient_stripe_acc = recipient.wallet.stripe_acc if not recipient_stripe_acc: return Response( 'Author has not created a Stripe Account', status=403 ) payment_intent = stripe.PaymentIntent.create( payment_method_types=['card'], amount=amount * 100, # The amount in cents currency='usd', application_fee_amount=0, transfer_data={ 'destination': recipient_stripe_acc } ) support.proof = payment_intent support.save() data['client_secret'] = payment_intent['client_secret'] sender_balance_date = datetime.datetime.now().strftime( '%m/%d/%Y' ) recipient_balance_date = datetime.datetime.now().strftime( '%m/%d/%Y' ) send_support_email.apply_async( ( f'{BASE_FRONTEND_URL}/user/{recipient.id}/overview', sender.full_name(), recipient_user.full_name(), sender.email, amount, sender_balance_date, payment_type, 'sender', content_type_str, object_id ), priority=6, countdown=2 ) send_support_email.apply_async( ( f'{BASE_FRONTEND_URL}/user/{sender.author_profile.id}/overview', sender.full_name(), recipient_user.full_name(), recipient_user.email, amount, recipient_balance_date, payment_type, 'recipient', content_type_str, object_id ), priority=6, countdown=2, ) sender_data = UserSerializer(sender).data response_data = {'user': sender_data, **data} return Response(response_data, status=200) class StripeViewSet(viewsets.ModelViewSet): queryset = Wallet.objects.all() serializer_class = WalletSerializer permission_classes = [] throttle_classes = [] @action( detail=False, methods=['post'], permission_classes=[IsAuthenticated] ) def onboard_stripe_account(self, request): user = request.user wallet = user.author_profile.wallet if not wallet.stripe_acc or not wallet.stripe_verified: acc = stripe.Account.create( type='express', country='US', # This is where our business resides email=user.email, capabilities={ 'card_payments': {'requested': True}, 'transfers': {'requested': True}, }, ) wallet.stripe_acc = acc['id'] wallet.save() elif wallet: account_links = stripe.Account.create_login_link(wallet.stripe_acc) return Response(account_links, status=200) refresh_url = request.data['refresh_url'] return_url = request.data['return_url'] try: account_links = stripe.AccountLink.create( account=wallet.stripe_acc, refresh_url=refresh_url, return_url=return_url, type='account_onboarding' ) except Exception as e: return Response(e, status=400) return Response(account_links, status=200) @action( detail=True, methods=['get'] ) def verify_stripe_account(self, request, pk=None): author = Author.objects.get(id=pk) wallet = author.wallet stripe_id = wallet.stripe_acc acc = stripe.Account.retrieve(stripe_id) redirect = f'{BASE_FRONTEND_URL}/user/{pk}/stripe?verify_stripe=true' account_links = stripe.Account.create_login_link( stripe_id, redirect_url=redirect ) if acc['charges_enabled']: wallet.stripe_verified = True wallet.save() return Response({**account_links}, status=200) return Response( { 'reason': 'Please complete verification via Stripe Dashboard', **account_links }, status=200 ) @action(detail=False, methods=['post']) def stripe_capability_updated(self, request): data = request.data acc_id = data['account'] acc_obj = data['data']['object'] status = acc_obj['status'] capability_type = acc_obj['id'] requirements = acc_obj['requirements'] currently_due = requirements['currently_due'] id_due = 'individual.id_number' in currently_due id_verf_due = 'individual.verification.document' in currently_due if capability_type != 'transfers' or status == 'pending': return Response(status=200) wallet = self.queryset.get(stripe_acc=acc_id) user = wallet.author.user if status == 'active' and not wallet.stripe_verified: account_links = stripe.Account.create_login_link(acc_id) wallet.stripe_verified = True wallet.save() self._send_stripe_notification( user, status, 'Your Stripe account has been verified', **account_links ) elif status == 'active' and wallet.stripe_verified: return Response(status=200) if not id_due and not id_verf_due and not len(currently_due) <= 2: return Response(status=200) try: account_links = stripe.Account.create_login_link(acc_id) except Exception as e: return Response(e, status=200) message = '' if id_due: message = """ Social Security Number or other government identification """ elif id_verf_due: message = """ Documents pertaining to government identification """ self._send_stripe_notification( user, status, message, **account_links ) return Response(status=200) def _send_stripe_notification(self, user, status, message, **kwargs): user_id = user.id user_type = ContentType.objects.get(model='user') action = Action.objects.create( user=user, content_type=user_type, object_id=user_id, ) notification = Notification.objects.create( recipient=user, action_user=user, action=action, ) notification.send_notification()
en
0.819656
# transfer_rsc is set each time just in case we want # to disable rsc transfer for a specific item # invalidate_trending_cache([]) # TODO: Add email support for posts # User check # Balance check # Subtracting balance from user # Adding balance to recipient # The amount in cents # This is where our business resides Social Security Number or other government identification Documents pertaining to government identification
1.750168
2
django/db/models/sql/__init__.py
egenerat/gae-django
3
6612717
<filename>django/db/models/sql/__init__.py from query import * from subqueries import * from where import AND, OR from datastructures import EmptyResultSet __all__ = ['Query', 'AND', 'OR', 'EmptyResultSet']
<filename>django/db/models/sql/__init__.py from query import * from subqueries import * from where import AND, OR from datastructures import EmptyResultSet __all__ = ['Query', 'AND', 'OR', 'EmptyResultSet']
none
1
1.760416
2
__init__.py
collincj/Daily-Brain-Stimulator
0
6612718
<reponame>collincj/Daily-Brain-Stimulator #A program to Stay Sharp
#A program to Stay Sharp
en
0.826612
#A program to Stay Sharp
0.958023
1
civ_minimap.py
Pella86/GIMP_plugins
3
6612719
#!/usr/bin/env python # Tutorial available at: https://www.youtube.com/watch?v=nmb-0KcgXzI from gimpfu import * def civ_minimap(image, drawable): # insert the alpha channel layer = image.active_layer pdb.gimp_layer_add_alpha(layer) # crop the image new_width = 257 new_height = 140 offx = 14 offy = 918 pdb.gimp_image_crop(image, new_width, new_height, offx, offy) # propagate_mode = 0 # white # propagating_channel = 0 # propagating_rate = 0 # 0 to 1 # direction_mask = 0 # 0 to 15 # lower_limit = 0 # 0 to 255 # upper_limit = 0 # 0 to 255 # pdb.plug_in_erode(image, drawable, propagate_mode, propagating_channel, propagating_rate, direction_mask, lower_limit, upper_limit) # blur the image horizontal = 3 vertical = 3 method = 1 # RLE method pdb.plug_in_gauss(image, drawable, horizontal, vertical, method) # select the shitty view rectangle color = (170, 154, 170) threshold = 40/255.0 operation = CHANNEL_OP_REPLACE pdb.gimp_context_set_sample_threshold(threshold) pdb.gimp_image_select_color(image, operation, drawable, color) register( "python-fu-Civilizations-minimap", "The script should automatically beautyfy the minimap", "First attempt at making sense of the minimap", "<NAME>", "<NAME>", "2015", "Civ minimap beautyfier", "", # type of image it works on (*, RGB, RGB*, RGBA, GRAY etc...) [ # basic parameters are: (UI_ELEMENT, "variable", "label", Default) (PF_IMAGE, "image", "takes current image", None), (PF_DRAWABLE, "drawable", "Input layer", None) # PF_SLIDER, SPINNER have an extra tuple (min, max, step) # PF_RADIO has an extra tuples within a tuple: # eg. (("radio_label", "radio_value), ...) for as many radio buttons # PF_OPTION has an extra tuple containing options in drop-down list # eg. ("opt1", "opt2", ...) for as many options # see ui_examples_1.py and ui_examples_2.py for live examples ], [], civ_minimap, menu="<Image>/Games scripts") # second item is menu location main()
#!/usr/bin/env python # Tutorial available at: https://www.youtube.com/watch?v=nmb-0KcgXzI from gimpfu import * def civ_minimap(image, drawable): # insert the alpha channel layer = image.active_layer pdb.gimp_layer_add_alpha(layer) # crop the image new_width = 257 new_height = 140 offx = 14 offy = 918 pdb.gimp_image_crop(image, new_width, new_height, offx, offy) # propagate_mode = 0 # white # propagating_channel = 0 # propagating_rate = 0 # 0 to 1 # direction_mask = 0 # 0 to 15 # lower_limit = 0 # 0 to 255 # upper_limit = 0 # 0 to 255 # pdb.plug_in_erode(image, drawable, propagate_mode, propagating_channel, propagating_rate, direction_mask, lower_limit, upper_limit) # blur the image horizontal = 3 vertical = 3 method = 1 # RLE method pdb.plug_in_gauss(image, drawable, horizontal, vertical, method) # select the shitty view rectangle color = (170, 154, 170) threshold = 40/255.0 operation = CHANNEL_OP_REPLACE pdb.gimp_context_set_sample_threshold(threshold) pdb.gimp_image_select_color(image, operation, drawable, color) register( "python-fu-Civilizations-minimap", "The script should automatically beautyfy the minimap", "First attempt at making sense of the minimap", "<NAME>", "<NAME>", "2015", "Civ minimap beautyfier", "", # type of image it works on (*, RGB, RGB*, RGBA, GRAY etc...) [ # basic parameters are: (UI_ELEMENT, "variable", "label", Default) (PF_IMAGE, "image", "takes current image", None), (PF_DRAWABLE, "drawable", "Input layer", None) # PF_SLIDER, SPINNER have an extra tuple (min, max, step) # PF_RADIO has an extra tuples within a tuple: # eg. (("radio_label", "radio_value), ...) for as many radio buttons # PF_OPTION has an extra tuple containing options in drop-down list # eg. ("opt1", "opt2", ...) for as many options # see ui_examples_1.py and ui_examples_2.py for live examples ], [], civ_minimap, menu="<Image>/Games scripts") # second item is menu location main()
en
0.629564
#!/usr/bin/env python # Tutorial available at: https://www.youtube.com/watch?v=nmb-0KcgXzI # insert the alpha channel # crop the image # propagate_mode = 0 # white # propagating_channel = 0 # propagating_rate = 0 # 0 to 1 # direction_mask = 0 # 0 to 15 # lower_limit = 0 # 0 to 255 # upper_limit = 0 # 0 to 255 # pdb.plug_in_erode(image, drawable, propagate_mode, propagating_channel, propagating_rate, direction_mask, lower_limit, upper_limit) # blur the image # RLE method # select the shitty view rectangle # type of image it works on (*, RGB, RGB*, RGBA, GRAY etc...) # basic parameters are: (UI_ELEMENT, "variable", "label", Default) # PF_SLIDER, SPINNER have an extra tuple (min, max, step) # PF_RADIO has an extra tuples within a tuple: # eg. (("radio_label", "radio_value), ...) for as many radio buttons # PF_OPTION has an extra tuple containing options in drop-down list # eg. ("opt1", "opt2", ...) for as many options # see ui_examples_1.py and ui_examples_2.py for live examples # second item is menu location
3.317813
3
server/dockyard/service/interface/default/_handler.py
tor4z/Galileo-dockyard
0
6612720
from dockyard.service.interface import BaseHandler class DefaultHandeler(BaseHandler): def get(self, *args, **kwargs): self.success() def post(self, *args, **kwargs): self.success() def delete(self, *args, **kwargs): self.success() def put(self, *args, **kwargs): self.success()
from dockyard.service.interface import BaseHandler class DefaultHandeler(BaseHandler): def get(self, *args, **kwargs): self.success() def post(self, *args, **kwargs): self.success() def delete(self, *args, **kwargs): self.success() def put(self, *args, **kwargs): self.success()
none
1
2.18189
2
tes_optimization/DE_opt_functions.py
AbbyGi/tes-optimization
0
6612721
import numpy as np from random import random, uniform import matplotlib.pyplot as plt def ackley(x, a=20, b=0.2, c=2*np.pi): # n dimensional x = np.asarray_chkfinite(x) # ValueError if any NaN or Inf n = len(x) s1 = sum(x**2) s2 = sum(np.cos(c * x)) return -a*np.exp(-b*np.sqrt(s1 / n)) - np.exp(s2 / n) + a + np.exp(1) def bukin(x): # 2 dimensional return 100 * np.sqrt(np.abs(x[1] - 0.01 * x[0] ** 2)) + 0.01 * np.abs(x[0] + 10) def griewank(x): # n dimensional dim = len(x) j = np.arange(1, dim + 1) sq_list = [i ** 2 for i in x] s = sum(sq_list) p = np.prod(np.cos(x / np.sqrt(j))) return s / 4000 - p + 1 def rosenbrock(x): # n dimensional x = np.asarray_chkfinite(x) x0 = x[:-1] x1 = x[1:] return sum(100 * (x1 - x0 ** 2) ** 2 + (x0 - 1) ** 2) def zakharov(x): # n dimensional x = np.asarray_chkfinite(x) dim = len(x) j = np.arange(1, dim + 1) s1 = sum(0.5 * j * x) return sum(x ** 2) + s1 ** 2 + s1 ** 4 def levy(x): # n dimensional x = np.asarray_chkfinite(x) w = 1 + (x - 1) / 4 return (np.sin(np.pi * w[0])) ** 2 \ + sum((w[:-1] - 1) ** 2 * (1 + 10 * np.sin(np.pi * w[:-1] + 1) ** 2)) \ + (w[-1] - 1) ** 2 * (1 + (np.sin(2 * np.pi * w[-1]) ** 2)) def rastrigin(x): # n dimensional x = np.asarray_chkfinite(x) dim = len(x) return 10 * dim + sum(x ** 2 - 10 * np.cos(2 * np.pi * x)) def schwefel(x): # n dimensional x = np.asarray_chkfinite(x) dim = len(x) return 418.9829 * dim - sum(x * np.sin(np.sqrt(np.abs(x)))) def sphere(x): # n dimensional x = np.asarray_chkfinite(x) return sum(x ** 2) def sum_diff_powers(x): # n dimensional x = np.asarray_chkfinite(x) dim = len(x) j = np.arange(1, dim + 1) return sum(np.abs(x) ** (j + 1)) def sum_of_squares(x): # n dimensional x = np.asarray_chkfinite(x) dim = len(x) j = np.arange(1, dim + 1) return sum(j * x ** 2) def rotated_hyper_ellipsoid(x): # n dimensional x = np.asarray_chkfinite(x) dim = len(x) total = 0 for i in range(1, dim + 1): for j in range(1, i + 1): total += (x[j - 1] ** 2) return total def ellipse(x): # n dimensional x = np.asarray_chkfinite(x) return np.mean((1 - x) ** 2) + 100 * np.mean(np.diff(x) ** 2) def schafferN6(x): # 2 dimensional x = np.asarray_chkfinite(x) num = np.sin(np.sqrt(x[0] ** 2 + x[1] ** 2)) ** 2 - 0.5 denom = (1 + 0.001*(x[0] ** 2 + x[1] ** 2)) ** 2 return 0.5 + num / denom def simple_parabola(x): x = np.asarray(x) return -3 * x ** 2 + 3 def beamline_test_function(x): x = np.asarray(x) return np.sin(4 * x) - np.cos(8 * x) + 2 def ensure_bounds(vec, bounds): # Makes sure each individual stays within bounds and adjusts them if they aren't vec_new = [] # cycle through each variable in vector for i in range(len(vec)): # variable exceeds the minimum boundary if vec[i] < bounds[i][0]: vec_new.append(bounds[i][0]) # variable exceeds the maximum boundary if vec[i] > bounds[i][1]: vec_new.append(bounds[i][1]) # the variable is fine if bounds[i][0] <= vec[i] <= bounds[i][1]: vec_new.append(vec[i]) return vec_new def omea(positions, func): evaluations = [] min_positions = [] min_evals = [] # get first position eval evaluations.append(func(positions[0])) for i in range(1, len(positions)): hold_eval = [] in_between = np.linspace(positions[i - 1], positions[i], 50) between = in_between[1:-1] for t in range(len(between)): hold_eval.append(func(between[t])) # get eval of next position evaluations.append(func(positions[i])) # find index of min ii = np.argmin(hold_eval) min_positions.append(between[ii]) min_evals.append(hold_eval[ii]) for i in range(len(min_positions)): if min_evals[i] < evaluations[i + 1]: evaluations[i + 1] = min_evals[i] for k in range(len(min_positions[i])): positions[i + 1][k] = min_positions[i][k] return positions, evaluations def rand_1(pop, popsize, t_indx, mut, bounds): # v = x_r1 + F * (x_r2 - x_r3) idxs = [idx for idx in range(popsize) if idx != t_indx] a, b, c = np.random.choice(idxs, 3, replace=False) x_1 = pop[a] x_2 = pop[b] x_3 = pop[c] x_diff = [x_2_i - x_3_i for x_2_i, x_3_i in zip(x_2, x_3)] v_donor = [x_1_i + mut * x_diff_i for x_1_i, x_diff_i in zip(x_1, x_diff)] v_donor = ensure_bounds(v_donor, bounds) return v_donor def best_1(pop, popsize, t_indx, mut, bounds, ind_sol): # v = x_best + F * (x_r1 - x_r2) x_best = pop[ind_sol.index(np.min(ind_sol))] idxs = [idx for idx in range(popsize) if idx != t_indx] a, b = np.random.choice(idxs, 2, replace=False) x_1 = pop[a] x_2 = pop[b] x_diff = [x_1_i - x_2_i for x_1_i, x_2_i in zip(x_1, x_2)] v_donor = [x_b + mut * x_diff_i for x_b, x_diff_i in zip(x_best, x_diff)] v_donor = ensure_bounds(v_donor, bounds) return v_donor def current_to_best_1(pop, popsize, t_indx, mut, bounds, ind_sol): # v = x_curr + F * (x_best - x_curr) + F * (x_r1 - r_r2) x_best = pop[ind_sol.index(np.min(ind_sol))] idxs = [idx for idx in range(popsize) if idx != t_indx] a, b = np.random.choice(idxs, 2, replace=False) x_1 = pop[a] x_2 = pop[b] x_curr = pop[t_indx] x_diff1 = [x_b - x_c for x_b, x_c in zip(x_best, x_curr)] x_diff2 = [x_1_i - x_2_i for x_1_i, x_2_i in zip(x_1, x_2)] v_donor = [x_c + mut * x_diff_1 + mut * x_diff_2 for x_c, x_diff_1, x_diff_2 in zip(x_curr, x_diff1, x_diff2)] v_donor = ensure_bounds(v_donor, bounds) return v_donor def best_2(pop, popsize, t_indx, mut, bounds, ind_sol): # v = x_best + F * (x_r1 - x_r2) + F * (x_r3 - r_r4) x_best = pop[ind_sol.index(np.min(ind_sol))] idxs = [idx for idx in range(popsize) if idx != t_indx] a, b, c, d = np.random.choice(idxs, 4, replace=False) x_1 = pop[a] x_2 = pop[b] x_3 = pop[c] x_4 = pop[d] x_diff1 = [x_1_i - x_2_i for x_1_i, x_2_i in zip(x_1, x_2)] x_diff2 = [x_3_i - x_4_i for x_3_i, x_4_i in zip(x_3, x_4)] v_donor = [x_b + mut * x_diff_1 + mut * x_diff_2 for x_b, x_diff_1, x_diff_2 in zip(x_best, x_diff1, x_diff2)] v_donor = ensure_bounds(v_donor, bounds) return v_donor def rand_2(pop, popsize, t_indx, mut, bounds): # v = x_r1 + F * (x_r2 - x_r3) + F * (x_r4 - r_r5) idxs = [idx for idx in range(popsize) if idx != t_indx] a, b, c, d, e = np.random.choice(idxs, 5, replace=False) x_1 = pop[a] x_2 = pop[b] x_3 = pop[c] x_4 = pop[d] x_5 = pop[e] x_diff1 = [x_2_i - x_3_i for x_2_i, x_3_i in zip(x_2, x_3)] x_diff2 = [x_4_i - x_5_i for x_4_i, x_5_i in zip(x_4, x_5)] v_donor = [x_1_i + mut * x_diff_1 + mut * x_diff_2 for x_1_i, x_diff_1, x_diff_2 in zip(x_1, x_diff1, x_diff2)] v_donor = ensure_bounds(v_donor, bounds) return v_donor def mutate(population, strategy, mut, bounds, ind_sol): mutated_indv = [] for i in range(len(population)): if strategy == 'rand/1': v_donor = rand_1(population, len(population), i, mut, bounds) elif strategy == 'best/1': v_donor = best_1(population, len(population), i, mut, bounds, ind_sol) elif strategy == 'current-to-best/1': v_donor = current_to_best_1(population, len(population), i, mut, bounds, ind_sol) elif strategy == 'best/2': v_donor = best_2(population, len(population), i, mut, bounds, ind_sol) elif strategy == 'rand/2': v_donor = rand_2(population, len(population), i, mut, bounds) mutated_indv.append(v_donor) return mutated_indv def crossover(population, mutated_indv, crosspb): crossover_indv = [] for i in range(len(population)): v_trial = [] x_t = population[i] for j in range(len(x_t)): crossover_val = random() if crossover_val <= crosspb: v_trial.append(mutated_indv[i][j]) else: v_trial.append(x_t[j]) crossover_indv.append(v_trial) return crossover_indv def select(population, crossover_indv, ind_sol, func): positions = [elm for elm in crossover_indv] positions.insert(0, population[0]) positions, evals = omea(positions, func) positions = positions[1:] evals = evals[1:] for i in range(len(evals)): if evals[i] < ind_sol[i]: population[i] = positions[i] ind_sol[i] = evals[i] population.reverse() ind_sol.reverse() return population, ind_sol def diff_ev(bounds, func, threshold, popsize=10, crosspb=0.8, mut=0.05, mut_type='rand/1'): # Initial population population = [] best_fitness = [10] for i in range(popsize): indv = [] for j in range(len(bounds)): indv.append(uniform(bounds[j][0], bounds[j][1])) population.append(indv) init_pop = population[:] # Evaluate fitness/OMEA init_pop.sort() pop, ind_sol = omea(init_pop, func) # reverse for efficiency with motors pop.reverse() ind_sol.reverse() # Termination conditions v = 0 # generation number consec_best_ctr = 0 # counting successive generations with no change to best value old_best_fit_val = 0 while not (consec_best_ctr >= 5 and old_best_fit_val <= threshold): print('\nGENERATION ' + str(v + 1)) best_gen_sol = [] # holding best scores of each generation mutated_trial_pop = mutate(pop, mut_type, mut, bounds, ind_sol) cross_trial_pop = crossover(pop, mutated_trial_pop, crosspb) pop, ind_sol = select(pop, cross_trial_pop, ind_sol, func) # score keeping gen_best = np.min(ind_sol) # fitness of best individual best_indv = pop[ind_sol.index(gen_best)] # best individual positions best_gen_sol.append(best_indv) best_fitness.append(gen_best) print(' > BEST FITNESS:', gen_best) print(' > BEST POSITIONS:', best_indv) v += 1 if np.round(gen_best, 6) == np.round(old_best_fit_val, 6): consec_best_ctr += 1 print('Counter:', consec_best_ctr) else: consec_best_ctr = 0 old_best_fit_val = gen_best if consec_best_ctr >= 5 and old_best_fit_val <= threshold: print('Finished') break else: change_index = ind_sol.index(np.max(ind_sol)) changed_indv = pop[change_index] for k in range(len(changed_indv)): changed_indv[k] = uniform(bounds[k][0], bounds[k][1]) # OMEA would be here too # not sure how to do this with functions ind_sol[change_index] = func(changed_indv) x_best = best_gen_sol[-1] print('\nThe best individual is', x_best, 'with a fitness of', gen_best) print('It took', v, 'generations') # plot best fitness plot_index = np.arange(len(best_fitness)) plt.figure() plt.plot(plot_index, best_fitness) diff_ev(bounds=[(-10, 10)] * 20, func=sphere, threshold=0.05, popsize=10, crosspb=0.8, mut=0.2)
import numpy as np from random import random, uniform import matplotlib.pyplot as plt def ackley(x, a=20, b=0.2, c=2*np.pi): # n dimensional x = np.asarray_chkfinite(x) # ValueError if any NaN or Inf n = len(x) s1 = sum(x**2) s2 = sum(np.cos(c * x)) return -a*np.exp(-b*np.sqrt(s1 / n)) - np.exp(s2 / n) + a + np.exp(1) def bukin(x): # 2 dimensional return 100 * np.sqrt(np.abs(x[1] - 0.01 * x[0] ** 2)) + 0.01 * np.abs(x[0] + 10) def griewank(x): # n dimensional dim = len(x) j = np.arange(1, dim + 1) sq_list = [i ** 2 for i in x] s = sum(sq_list) p = np.prod(np.cos(x / np.sqrt(j))) return s / 4000 - p + 1 def rosenbrock(x): # n dimensional x = np.asarray_chkfinite(x) x0 = x[:-1] x1 = x[1:] return sum(100 * (x1 - x0 ** 2) ** 2 + (x0 - 1) ** 2) def zakharov(x): # n dimensional x = np.asarray_chkfinite(x) dim = len(x) j = np.arange(1, dim + 1) s1 = sum(0.5 * j * x) return sum(x ** 2) + s1 ** 2 + s1 ** 4 def levy(x): # n dimensional x = np.asarray_chkfinite(x) w = 1 + (x - 1) / 4 return (np.sin(np.pi * w[0])) ** 2 \ + sum((w[:-1] - 1) ** 2 * (1 + 10 * np.sin(np.pi * w[:-1] + 1) ** 2)) \ + (w[-1] - 1) ** 2 * (1 + (np.sin(2 * np.pi * w[-1]) ** 2)) def rastrigin(x): # n dimensional x = np.asarray_chkfinite(x) dim = len(x) return 10 * dim + sum(x ** 2 - 10 * np.cos(2 * np.pi * x)) def schwefel(x): # n dimensional x = np.asarray_chkfinite(x) dim = len(x) return 418.9829 * dim - sum(x * np.sin(np.sqrt(np.abs(x)))) def sphere(x): # n dimensional x = np.asarray_chkfinite(x) return sum(x ** 2) def sum_diff_powers(x): # n dimensional x = np.asarray_chkfinite(x) dim = len(x) j = np.arange(1, dim + 1) return sum(np.abs(x) ** (j + 1)) def sum_of_squares(x): # n dimensional x = np.asarray_chkfinite(x) dim = len(x) j = np.arange(1, dim + 1) return sum(j * x ** 2) def rotated_hyper_ellipsoid(x): # n dimensional x = np.asarray_chkfinite(x) dim = len(x) total = 0 for i in range(1, dim + 1): for j in range(1, i + 1): total += (x[j - 1] ** 2) return total def ellipse(x): # n dimensional x = np.asarray_chkfinite(x) return np.mean((1 - x) ** 2) + 100 * np.mean(np.diff(x) ** 2) def schafferN6(x): # 2 dimensional x = np.asarray_chkfinite(x) num = np.sin(np.sqrt(x[0] ** 2 + x[1] ** 2)) ** 2 - 0.5 denom = (1 + 0.001*(x[0] ** 2 + x[1] ** 2)) ** 2 return 0.5 + num / denom def simple_parabola(x): x = np.asarray(x) return -3 * x ** 2 + 3 def beamline_test_function(x): x = np.asarray(x) return np.sin(4 * x) - np.cos(8 * x) + 2 def ensure_bounds(vec, bounds): # Makes sure each individual stays within bounds and adjusts them if they aren't vec_new = [] # cycle through each variable in vector for i in range(len(vec)): # variable exceeds the minimum boundary if vec[i] < bounds[i][0]: vec_new.append(bounds[i][0]) # variable exceeds the maximum boundary if vec[i] > bounds[i][1]: vec_new.append(bounds[i][1]) # the variable is fine if bounds[i][0] <= vec[i] <= bounds[i][1]: vec_new.append(vec[i]) return vec_new def omea(positions, func): evaluations = [] min_positions = [] min_evals = [] # get first position eval evaluations.append(func(positions[0])) for i in range(1, len(positions)): hold_eval = [] in_between = np.linspace(positions[i - 1], positions[i], 50) between = in_between[1:-1] for t in range(len(between)): hold_eval.append(func(between[t])) # get eval of next position evaluations.append(func(positions[i])) # find index of min ii = np.argmin(hold_eval) min_positions.append(between[ii]) min_evals.append(hold_eval[ii]) for i in range(len(min_positions)): if min_evals[i] < evaluations[i + 1]: evaluations[i + 1] = min_evals[i] for k in range(len(min_positions[i])): positions[i + 1][k] = min_positions[i][k] return positions, evaluations def rand_1(pop, popsize, t_indx, mut, bounds): # v = x_r1 + F * (x_r2 - x_r3) idxs = [idx for idx in range(popsize) if idx != t_indx] a, b, c = np.random.choice(idxs, 3, replace=False) x_1 = pop[a] x_2 = pop[b] x_3 = pop[c] x_diff = [x_2_i - x_3_i for x_2_i, x_3_i in zip(x_2, x_3)] v_donor = [x_1_i + mut * x_diff_i for x_1_i, x_diff_i in zip(x_1, x_diff)] v_donor = ensure_bounds(v_donor, bounds) return v_donor def best_1(pop, popsize, t_indx, mut, bounds, ind_sol): # v = x_best + F * (x_r1 - x_r2) x_best = pop[ind_sol.index(np.min(ind_sol))] idxs = [idx for idx in range(popsize) if idx != t_indx] a, b = np.random.choice(idxs, 2, replace=False) x_1 = pop[a] x_2 = pop[b] x_diff = [x_1_i - x_2_i for x_1_i, x_2_i in zip(x_1, x_2)] v_donor = [x_b + mut * x_diff_i for x_b, x_diff_i in zip(x_best, x_diff)] v_donor = ensure_bounds(v_donor, bounds) return v_donor def current_to_best_1(pop, popsize, t_indx, mut, bounds, ind_sol): # v = x_curr + F * (x_best - x_curr) + F * (x_r1 - r_r2) x_best = pop[ind_sol.index(np.min(ind_sol))] idxs = [idx for idx in range(popsize) if idx != t_indx] a, b = np.random.choice(idxs, 2, replace=False) x_1 = pop[a] x_2 = pop[b] x_curr = pop[t_indx] x_diff1 = [x_b - x_c for x_b, x_c in zip(x_best, x_curr)] x_diff2 = [x_1_i - x_2_i for x_1_i, x_2_i in zip(x_1, x_2)] v_donor = [x_c + mut * x_diff_1 + mut * x_diff_2 for x_c, x_diff_1, x_diff_2 in zip(x_curr, x_diff1, x_diff2)] v_donor = ensure_bounds(v_donor, bounds) return v_donor def best_2(pop, popsize, t_indx, mut, bounds, ind_sol): # v = x_best + F * (x_r1 - x_r2) + F * (x_r3 - r_r4) x_best = pop[ind_sol.index(np.min(ind_sol))] idxs = [idx for idx in range(popsize) if idx != t_indx] a, b, c, d = np.random.choice(idxs, 4, replace=False) x_1 = pop[a] x_2 = pop[b] x_3 = pop[c] x_4 = pop[d] x_diff1 = [x_1_i - x_2_i for x_1_i, x_2_i in zip(x_1, x_2)] x_diff2 = [x_3_i - x_4_i for x_3_i, x_4_i in zip(x_3, x_4)] v_donor = [x_b + mut * x_diff_1 + mut * x_diff_2 for x_b, x_diff_1, x_diff_2 in zip(x_best, x_diff1, x_diff2)] v_donor = ensure_bounds(v_donor, bounds) return v_donor def rand_2(pop, popsize, t_indx, mut, bounds): # v = x_r1 + F * (x_r2 - x_r3) + F * (x_r4 - r_r5) idxs = [idx for idx in range(popsize) if idx != t_indx] a, b, c, d, e = np.random.choice(idxs, 5, replace=False) x_1 = pop[a] x_2 = pop[b] x_3 = pop[c] x_4 = pop[d] x_5 = pop[e] x_diff1 = [x_2_i - x_3_i for x_2_i, x_3_i in zip(x_2, x_3)] x_diff2 = [x_4_i - x_5_i for x_4_i, x_5_i in zip(x_4, x_5)] v_donor = [x_1_i + mut * x_diff_1 + mut * x_diff_2 for x_1_i, x_diff_1, x_diff_2 in zip(x_1, x_diff1, x_diff2)] v_donor = ensure_bounds(v_donor, bounds) return v_donor def mutate(population, strategy, mut, bounds, ind_sol): mutated_indv = [] for i in range(len(population)): if strategy == 'rand/1': v_donor = rand_1(population, len(population), i, mut, bounds) elif strategy == 'best/1': v_donor = best_1(population, len(population), i, mut, bounds, ind_sol) elif strategy == 'current-to-best/1': v_donor = current_to_best_1(population, len(population), i, mut, bounds, ind_sol) elif strategy == 'best/2': v_donor = best_2(population, len(population), i, mut, bounds, ind_sol) elif strategy == 'rand/2': v_donor = rand_2(population, len(population), i, mut, bounds) mutated_indv.append(v_donor) return mutated_indv def crossover(population, mutated_indv, crosspb): crossover_indv = [] for i in range(len(population)): v_trial = [] x_t = population[i] for j in range(len(x_t)): crossover_val = random() if crossover_val <= crosspb: v_trial.append(mutated_indv[i][j]) else: v_trial.append(x_t[j]) crossover_indv.append(v_trial) return crossover_indv def select(population, crossover_indv, ind_sol, func): positions = [elm for elm in crossover_indv] positions.insert(0, population[0]) positions, evals = omea(positions, func) positions = positions[1:] evals = evals[1:] for i in range(len(evals)): if evals[i] < ind_sol[i]: population[i] = positions[i] ind_sol[i] = evals[i] population.reverse() ind_sol.reverse() return population, ind_sol def diff_ev(bounds, func, threshold, popsize=10, crosspb=0.8, mut=0.05, mut_type='rand/1'): # Initial population population = [] best_fitness = [10] for i in range(popsize): indv = [] for j in range(len(bounds)): indv.append(uniform(bounds[j][0], bounds[j][1])) population.append(indv) init_pop = population[:] # Evaluate fitness/OMEA init_pop.sort() pop, ind_sol = omea(init_pop, func) # reverse for efficiency with motors pop.reverse() ind_sol.reverse() # Termination conditions v = 0 # generation number consec_best_ctr = 0 # counting successive generations with no change to best value old_best_fit_val = 0 while not (consec_best_ctr >= 5 and old_best_fit_val <= threshold): print('\nGENERATION ' + str(v + 1)) best_gen_sol = [] # holding best scores of each generation mutated_trial_pop = mutate(pop, mut_type, mut, bounds, ind_sol) cross_trial_pop = crossover(pop, mutated_trial_pop, crosspb) pop, ind_sol = select(pop, cross_trial_pop, ind_sol, func) # score keeping gen_best = np.min(ind_sol) # fitness of best individual best_indv = pop[ind_sol.index(gen_best)] # best individual positions best_gen_sol.append(best_indv) best_fitness.append(gen_best) print(' > BEST FITNESS:', gen_best) print(' > BEST POSITIONS:', best_indv) v += 1 if np.round(gen_best, 6) == np.round(old_best_fit_val, 6): consec_best_ctr += 1 print('Counter:', consec_best_ctr) else: consec_best_ctr = 0 old_best_fit_val = gen_best if consec_best_ctr >= 5 and old_best_fit_val <= threshold: print('Finished') break else: change_index = ind_sol.index(np.max(ind_sol)) changed_indv = pop[change_index] for k in range(len(changed_indv)): changed_indv[k] = uniform(bounds[k][0], bounds[k][1]) # OMEA would be here too # not sure how to do this with functions ind_sol[change_index] = func(changed_indv) x_best = best_gen_sol[-1] print('\nThe best individual is', x_best, 'with a fitness of', gen_best) print('It took', v, 'generations') # plot best fitness plot_index = np.arange(len(best_fitness)) plt.figure() plt.plot(plot_index, best_fitness) diff_ev(bounds=[(-10, 10)] * 20, func=sphere, threshold=0.05, popsize=10, crosspb=0.8, mut=0.2)
en
0.753448
# n dimensional # ValueError if any NaN or Inf # 2 dimensional # n dimensional # n dimensional # n dimensional # n dimensional # n dimensional # n dimensional # n dimensional # n dimensional # n dimensional # n dimensional # n dimensional # 2 dimensional # Makes sure each individual stays within bounds and adjusts them if they aren't # cycle through each variable in vector # variable exceeds the minimum boundary # variable exceeds the maximum boundary # the variable is fine # get first position eval # get eval of next position # find index of min # v = x_r1 + F * (x_r2 - x_r3) # v = x_best + F * (x_r1 - x_r2) # v = x_curr + F * (x_best - x_curr) + F * (x_r1 - r_r2) # v = x_best + F * (x_r1 - x_r2) + F * (x_r3 - r_r4) # v = x_r1 + F * (x_r2 - x_r3) + F * (x_r4 - r_r5) # Initial population # Evaluate fitness/OMEA # reverse for efficiency with motors # Termination conditions # generation number # counting successive generations with no change to best value # holding best scores of each generation # score keeping # fitness of best individual # best individual positions # OMEA would be here too # not sure how to do this with functions # plot best fitness
2.579432
3
ismore/tubingen/featurelist.py
srsummerson/bmi_python
0
6612722
<filename>ismore/tubingen/featurelist.py<gh_stars>0 ''' List of features which can be used to extend experiments through the web interface ''' from ismore.brainamp_features import BrainAmpData, SimBrainAmpData, LiveAmpData from features.hdf_features import SaveHDF from ismore.tubingen.tuebingen_features.VideoRecording import VideoRecording from ismore.exo_3D_visualization import Exo3DVisualization, Exo3DVisualizationInvasive from ismore.tubingen.tuebingen_features.AdvancedVisualization import AdvancedVisualization features = dict( brainampdata = BrainAmpData, liveampdata = LiveAmpData, simbrainampdata = SimBrainAmpData, saveHDF = SaveHDF, recordVideo = VideoRecording, AdvancedVisualization = AdvancedVisualization )
<filename>ismore/tubingen/featurelist.py<gh_stars>0 ''' List of features which can be used to extend experiments through the web interface ''' from ismore.brainamp_features import BrainAmpData, SimBrainAmpData, LiveAmpData from features.hdf_features import SaveHDF from ismore.tubingen.tuebingen_features.VideoRecording import VideoRecording from ismore.exo_3D_visualization import Exo3DVisualization, Exo3DVisualizationInvasive from ismore.tubingen.tuebingen_features.AdvancedVisualization import AdvancedVisualization features = dict( brainampdata = BrainAmpData, liveampdata = LiveAmpData, simbrainampdata = SimBrainAmpData, saveHDF = SaveHDF, recordVideo = VideoRecording, AdvancedVisualization = AdvancedVisualization )
en
0.93304
List of features which can be used to extend experiments through the web interface
1.747764
2
plastron/daemon.py
dsteelma-umd/plastron
0
6612723
<gh_stars>0 #!/usr/bin/env python3 import argparse import logging import logging.config import os import signal import sys import yaml from datetime import datetime from plastron import version from plastron.http import Repository from plastron.logging import DEFAULT_LOGGING_OPTIONS from plastron.stomp import Broker from plastron.stomp.listeners import ReconnectListener, CommandListener logger = logging.getLogger(__name__) now = datetime.utcnow().strftime('%Y%m%d%H%M%S') def main(): parser = argparse.ArgumentParser( prog='plastron', description='Batch operations daemon for Fedora 4.' ) parser.add_argument( '-c', '--config', help='Path to configuration file.', action='store', required=True ) parser.add_argument( '-v', '--verbose', help='increase the verbosity of the status output', action='store_true' ) # parse command line args args = parser.parse_args() with open(args.config, 'r') as config_file: config = yaml.safe_load(config_file) repo_config = config['REPOSITORY'] broker_config = config['MESSAGE_BROKER'] logging_options = DEFAULT_LOGGING_OPTIONS # log file configuration log_dirname = repo_config.get('LOG_DIR') if not os.path.isdir(log_dirname): os.makedirs(log_dirname) log_filename = f'plastron.daemon.{now}.log' logfile = os.path.join(log_dirname, log_filename) logging_options['handlers']['file']['filename'] = logfile # manipulate console verbosity if args.verbose: logging_options['handlers']['console']['level'] = 'DEBUG' # configure logging logging.config.dictConfig(logging_options) # configure STOMP message broker broker = Broker(broker_config) logger.info(f'plastrond {version}') repo = Repository(repo_config, ua_string=f'plastron/{version}') # setup listeners broker.connection.set_listener('reconnect', ReconnectListener(broker)) broker.connection.set_listener('export', CommandListener(broker, repo)) try: broker.connect() while True: signal.pause() except KeyboardInterrupt: sys.exit() if __name__ == "__main__": main()
#!/usr/bin/env python3 import argparse import logging import logging.config import os import signal import sys import yaml from datetime import datetime from plastron import version from plastron.http import Repository from plastron.logging import DEFAULT_LOGGING_OPTIONS from plastron.stomp import Broker from plastron.stomp.listeners import ReconnectListener, CommandListener logger = logging.getLogger(__name__) now = datetime.utcnow().strftime('%Y%m%d%H%M%S') def main(): parser = argparse.ArgumentParser( prog='plastron', description='Batch operations daemon for Fedora 4.' ) parser.add_argument( '-c', '--config', help='Path to configuration file.', action='store', required=True ) parser.add_argument( '-v', '--verbose', help='increase the verbosity of the status output', action='store_true' ) # parse command line args args = parser.parse_args() with open(args.config, 'r') as config_file: config = yaml.safe_load(config_file) repo_config = config['REPOSITORY'] broker_config = config['MESSAGE_BROKER'] logging_options = DEFAULT_LOGGING_OPTIONS # log file configuration log_dirname = repo_config.get('LOG_DIR') if not os.path.isdir(log_dirname): os.makedirs(log_dirname) log_filename = f'plastron.daemon.{now}.log' logfile = os.path.join(log_dirname, log_filename) logging_options['handlers']['file']['filename'] = logfile # manipulate console verbosity if args.verbose: logging_options['handlers']['console']['level'] = 'DEBUG' # configure logging logging.config.dictConfig(logging_options) # configure STOMP message broker broker = Broker(broker_config) logger.info(f'plastrond {version}') repo = Repository(repo_config, ua_string=f'plastron/{version}') # setup listeners broker.connection.set_listener('reconnect', ReconnectListener(broker)) broker.connection.set_listener('export', CommandListener(broker, repo)) try: broker.connect() while True: signal.pause() except KeyboardInterrupt: sys.exit() if __name__ == "__main__": main()
en
0.339578
#!/usr/bin/env python3 # parse command line args # log file configuration # manipulate console verbosity # configure logging # configure STOMP message broker # setup listeners
1.818823
2
main.py
LambdaLint/pyflakes
0
6612724
<gh_stars>0 """Lambda function that executes pyflakes, a static file linter.""" from lintipy import CheckRun handle = CheckRun.as_handler('pyflakes', 'pyflakes', '.')
"""Lambda function that executes pyflakes, a static file linter.""" from lintipy import CheckRun handle = CheckRun.as_handler('pyflakes', 'pyflakes', '.')
en
0.714748
Lambda function that executes pyflakes, a static file linter.
1.704201
2
eyekit/_validate.py
ys7yoo/eyekit
0
6612725
""" Functions for checking that a variable is of the correct Eyekit type. """ from .fixation import Fixation, FixationSequence from .text import InterestArea, TextBlock def fail(obj, expectation): raise TypeError(f"Expected {expectation}, got {obj.__class__.__name__}") def is_Fixation(fixation): if not isinstance(fixation, Fixation): fail(fixation, "Fixation") def is_FixationSequence(fixation_sequence): if not isinstance(fixation_sequence, FixationSequence): fail(fixation_sequence, "FixationSequence") def is_InterestArea(interest_area): if not isinstance(interest_area, InterestArea): fail(interest_area, "InterestArea") def is_TextBlock(text_block): if not isinstance(text_block, TextBlock): fail(text_block, "TextBlock")
""" Functions for checking that a variable is of the correct Eyekit type. """ from .fixation import Fixation, FixationSequence from .text import InterestArea, TextBlock def fail(obj, expectation): raise TypeError(f"Expected {expectation}, got {obj.__class__.__name__}") def is_Fixation(fixation): if not isinstance(fixation, Fixation): fail(fixation, "Fixation") def is_FixationSequence(fixation_sequence): if not isinstance(fixation_sequence, FixationSequence): fail(fixation_sequence, "FixationSequence") def is_InterestArea(interest_area): if not isinstance(interest_area, InterestArea): fail(interest_area, "InterestArea") def is_TextBlock(text_block): if not isinstance(text_block, TextBlock): fail(text_block, "TextBlock")
en
0.8267
Functions for checking that a variable is of the correct Eyekit type.
3.216525
3
sso/user/migrations/0017_user_is_staff.py
uktrade/staff-sso
7
6612726
# Generated by Django 2.0.8 on 2019-02-11 13:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("user", "0016_merge_20190121_1321"), ] operations = [ migrations.AddField( model_name="user", name="is_staff", field=models.BooleanField( default=False, help_text="Designates whether the user can log into this admin site.", verbose_name="staff status", ), ), ]
# Generated by Django 2.0.8 on 2019-02-11 13:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("user", "0016_merge_20190121_1321"), ] operations = [ migrations.AddField( model_name="user", name="is_staff", field=models.BooleanField( default=False, help_text="Designates whether the user can log into this admin site.", verbose_name="staff status", ), ), ]
en
0.814804
# Generated by Django 2.0.8 on 2019-02-11 13:44
1.782163
2
test/test_md013.py
jackdewinter/pymarkdown
20
6612727
""" Module to provide tests related to the MD013 rule. """ from test.markdown_scanner import MarkdownScanner import pytest # pylint: disable=too-many-lines @pytest.mark.rules def test_md013_bad_configuration_line_length(): """ Test to verify that a configuration error is thrown when supplying the line_length value with a string that is not an integer. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.line_length=not-integer", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.line_length' must be of type 'int'." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_configuration_line_length_zero(): """ Test to verify that a configuration error is thrown when supplying the line_length value with an integer that is 0. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.line_length=$#0", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.line_length' is not valid: Allowable values are any integer greater than 0." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_configuration_heading_line_length(): """ Test to verify that a configuration error is thrown when supplying the heading_line_length value with a string that is not an integer. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.heading_line_length=not-integer", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.heading_line_length' must be of type 'int'." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_configuration_headings_active(): """ Test to verify that a configuration error is thrown when supplying the headings value with a string that is not a boolean. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.headings=not-integer", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.headings' must be of type 'bool'." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_configuration_code_block_line_length(): """ Test to verify that a configuration error is thrown when supplying the code_block_line_length value with a string that is not an integer. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.code_block_line_length=not-integer", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.code_block_line_length' must be of type 'int'." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_configuration_code_blocks_active(): """ Test to verify that a configuration error is thrown when supplying the code_blocks value with a string that is not a boolean. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.code_blocks=not-integer", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.code_blocks' must be of type 'bool'." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_configuration_strict_mode(): """ Test to verify that a configuration error is thrown when supplying the strict value with a string that is not a boolean. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.strict=not-integer", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.strict' must be of type 'bool'." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_configuration_stern_mode(): """ Test to verify that a configuration error is thrown when supplying the stern value with a string that is not a boolean. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.stern=not-integer", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.stern' must be of type 'bool'." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_small_line(): """ Test to make sure this rule does not trigger with a document that contains a single line with 38 characters. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_small_line_with_config(): """ Test to make sure this rule does trigger with a document that contains a single line with 38 characters, with configuration setting the maximum line length to 25. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.line_length=$#25", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/good_small_line.md:1:1: " + "MD013: Line length " + "[Expected: 25, Actual: 38] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_medium_line(): """ Test to make sure this rule does not trigger with a document that contains a single line with 80 characters. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_medium_line.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_medium_line_with_config(): """ Test to make sure this rule does trigger with a document that contains a single line with 80 characters with a configured maximum line length of 80. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.line_length=$#50", "--strict-config", "scan", "test/resources/rules/md013/good_medium_line.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/good_medium_line.md:1:1: " + "MD013: Line length " + "[Expected: 50, Actual: 80] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_long_line(): """ Test to make sure this rule does trigger with a document that contains a single line with 80 characters. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_long_line.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/good_long_line.md:1:1: " + "MD013: Line length " + "[Expected: 80, Actual: 100] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_long_line_with_config(): """ Test to make sure this rule does not trigger with a document that contains a single line with 80 characters with a configured maximum line length of 110. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.line_length=$#110", "--strict-config", "scan", "test/resources/rules/md013/good_long_line.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_medium_line_with_long_last_word(): """ Test to make sure this rule does not trigger with a document that contains a single line the crosses the normal 80 character limit with a 31 character last "word". """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_medium_line_with_very_long_last_word.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_medium_line_with_long_last_word_with_config_strict(): """ Test to make sure this rule does trigger with a document that contains a single line the crosses the normal 80 character limit with a 31 character last "word" and strict mode active. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.strict=$!True", "--strict-config", "scan", "test/resources/rules/md013/good_medium_line_with_very_long_last_word.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/good_medium_line_with_very_long_last_word.md:1:1: " + "MD013: Line length " + "[Expected: 80, Actual: 102] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_medium_line_with_long_last_word_with_config_stern(): """ Test to make sure this rule does not trigger with a document that contains a single line the crosses the normal 80 character limit with a 31 character last "word" and stern mode active. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.stern=$!True", "--strict-config", "scan", "test/resources/rules/md013/good_medium_line_with_very_long_last_word.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/good_medium_line_with_very_long_last_word.md:1:1: " + "MD013: Line length " + "[Expected: 80, Actual: 102] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_medium_line_with_long_last_word(): """ Test to make sure this rule does trigger with a document that contains a single line with multiple words past the 80 character boundary. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_medium_line_with_very_long_last_word.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/bad_medium_line_with_very_long_last_word.md:1:1: " + "MD013: Line length " + "[Expected: 80, Actual: 102] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_medium_line_with_long_last_word_with_config_strict(): """ Test to make sure this rule does trigger with a document that contains a single line with multiple words past the 80 character boundary and strict mode. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.strict=$!True", "--strict-config", "scan", "test/resources/rules/md013/bad_medium_line_with_very_long_last_word.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/bad_medium_line_with_very_long_last_word.md:1:1: " + "MD013: Line length " + "[Expected: 80, Actual: 102] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_medium_line_with_long_last_word_with_config_stern(): """ Test to make sure this rule does trigger with a document that contains a single line with multiple words past the 80 character boundary and stern mode. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.stern=$!True", "--strict-config", "scan", "test/resources/rules/md013/bad_medium_line_with_very_long_last_word.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_paragraph_with_long_line_in_middle(): """ Test to make sure this rule does trigger with a document that contains a multiple lines with a very long line in the middle. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_paragraph_with_long_line_in_middle.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/bad_paragraph_with_long_line_in_middle.md:3:1: " + "MD013: Line length " + "[Expected: 80, Actual: 91] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_fenced_code_block(): """ Test to make sure this rule does not trigger with a document that contains a good line within a fenced code block. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_fenced_code_block.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_fenced_code_block(): """ Test to make sure this rule does trigger with a document that contains a long line within a fenced code block. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_fenced_code_block.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_fenced_code_block.md:6:1: MD013: Line length [Expected: 80, Actual: 146] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_fenced_code_block_with_config(): """ Test to make sure this rule does trigger with a document that contains a very long line within a fenced code block, even with an extended line length for code blocks. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.code_block_line_length=$#100", "--strict-config", "scan", "test/resources/rules/md013/bad_fenced_code_block.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_fenced_code_block.md:6:1: MD013: Line length [Expected: 100, Actual: 146] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_fenced_code_block_with_config_active(): """ Test to make sure this rule does not trigger with a document that contains a long line within a fenced code block, but with the code_block value turned off. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.code_blocks=$!False", "--strict-config", "scan", "test/resources/rules/md013/bad_fenced_code_block.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_indented_code_block(): """ Test to make sure this rule does not trigger with a document that contains a long line within an indented code block, but with the code_block value turned off. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_indented_code_block.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_indented_code_block(): """ Test to make sure this rule does trigger with a document that contains a long line within an indented code block. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_indented_code_block.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_indented_code_block.md:5:1: MD013: Line length [Expected: 80, Actual: 154] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_indented_code_block_with_config(): """ Test to make sure this rule does not trigger with a document that contains a long line within an indented code block, but with the code_block_line_length set to 100. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.code_block_line_length=$#100", "--strict-config", "scan", "test/resources/rules/md013/bad_indented_code_block.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_indented_code_block.md:5:1: MD013: Line length [Expected: 100, Actual: 154] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_indented_code_block_with_config_active(): """ Test to make sure this rule does not trigger with a document that contains a long line within an indented code block, but with the code_blocks set to False. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.code_blocks=$!False", "--strict-config", "scan", "test/resources/rules/md013/bad_indented_code_block.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_thematic_break(): """ Test to make sure this rule does not trigger with a document that contains a normal line within a thematic break. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_thematic_break.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_thematic_break(): """ Test to make sure this rule does trigger with a document that contains a long line within a thematic break. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_thematic_break.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_thematic_break.md:1:1: MD013: Line length [Expected: 80, Actual: 87] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_thematic_break_with_config(): """ Test to make sure this rule does not trigger with a document that contains a long line within a thematic break, but with a configuration to allow the long line. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.line_length=$#100", "--strict-config", "scan", "test/resources/rules/md013/bad_thematic_break.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_atx_heading(): """ Test to make sure this rule does not trigger with a document that contains a normal line within an Atx Heading. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_atx_heading.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_atx_heading(): """ Test to make sure this rule does trigger with a document that contains a long line within an Atx Heading. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_atx_heading.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_atx_heading.md:1:1: MD013: Line length [Expected: 80, Actual: 88] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_atx_heading_with_config(): """ Test to make sure this rule does not trigger with a document that contains a long line within an Atx Heading, but with configuration to allow it. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.heading_line_length=$#100", "--strict-config", "scan", "test/resources/rules/md013/bad_atx_heading.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_atx_heading_with_config_active(): """ Test to make sure this rule does not trigger with a document that contains a long line within an Atx Heading, but with configuration to exclude headings. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.headings=$!False", "--strict-config", "scan", "test/resources/rules/md013/bad_atx_heading.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_setext_heading(): """ Test to make sure this rule does not trigger with a document that contains a normal line within a SetExt Heading. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_setext_heading.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_setext_heading(): """ Test to make sure this rule does trigger with a document that contains a long line within a SetExt Heading. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_setext_heading.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_setext_heading.md:1:1: MD013: Line length [Expected: 80, Actual: 86] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_setext_heading_with_config(): """ Test to make sure this rule does not trigger with a document that contains a long line within a SetExt Heading, but configuration to allow it. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.heading_line_length=$#100", "--strict-config", "scan", "test/resources/rules/md013/bad_setext_heading.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_setext_heading_with_config_active(): """ Test to make sure this rule does not trigger with a document that contains a long line within a SetExt Heading, but with headings turned off. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.headings=$!False", "--strict-config", "scan", "test/resources/rules/md013/bad_setext_heading.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_html_block(): """ Test to make sure this rule does not trigger with a document that contains a normal line within a HTML block. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_html_block.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_html_block(): """ Test to make sure this rule does trigger with a document that contains a long line within a HTML block. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_html_block.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_html_block.md:2:1: MD013: Line length [Expected: 80, Actual: 89] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_html_block_with_config(): """ Test to make sure this rule does not trigger with a document that contains a long line within a HTML block, but configuration to allow it. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.line_length=$#100", "--strict-config", "scan", "test/resources/rules/md013/bad_html_block.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code )
""" Module to provide tests related to the MD013 rule. """ from test.markdown_scanner import MarkdownScanner import pytest # pylint: disable=too-many-lines @pytest.mark.rules def test_md013_bad_configuration_line_length(): """ Test to verify that a configuration error is thrown when supplying the line_length value with a string that is not an integer. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.line_length=not-integer", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.line_length' must be of type 'int'." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_configuration_line_length_zero(): """ Test to verify that a configuration error is thrown when supplying the line_length value with an integer that is 0. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.line_length=$#0", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.line_length' is not valid: Allowable values are any integer greater than 0." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_configuration_heading_line_length(): """ Test to verify that a configuration error is thrown when supplying the heading_line_length value with a string that is not an integer. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.heading_line_length=not-integer", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.heading_line_length' must be of type 'int'." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_configuration_headings_active(): """ Test to verify that a configuration error is thrown when supplying the headings value with a string that is not a boolean. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.headings=not-integer", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.headings' must be of type 'bool'." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_configuration_code_block_line_length(): """ Test to verify that a configuration error is thrown when supplying the code_block_line_length value with a string that is not an integer. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.code_block_line_length=not-integer", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.code_block_line_length' must be of type 'int'." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_configuration_code_blocks_active(): """ Test to verify that a configuration error is thrown when supplying the code_blocks value with a string that is not a boolean. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.code_blocks=not-integer", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.code_blocks' must be of type 'bool'." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_configuration_strict_mode(): """ Test to verify that a configuration error is thrown when supplying the strict value with a string that is not a boolean. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.strict=not-integer", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.strict' must be of type 'bool'." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_configuration_stern_mode(): """ Test to verify that a configuration error is thrown when supplying the stern value with a string that is not a boolean. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.stern=not-integer", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = "" expected_error = ( "BadPluginError encountered while configuring plugins:\n" + "The value for property 'plugins.md013.stern' must be of type 'bool'." ) # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_small_line(): """ Test to make sure this rule does not trigger with a document that contains a single line with 38 characters. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_small_line_with_config(): """ Test to make sure this rule does trigger with a document that contains a single line with 38 characters, with configuration setting the maximum line length to 25. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.line_length=$#25", "--strict-config", "scan", "test/resources/rules/md013/good_small_line.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/good_small_line.md:1:1: " + "MD013: Line length " + "[Expected: 25, Actual: 38] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_medium_line(): """ Test to make sure this rule does not trigger with a document that contains a single line with 80 characters. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_medium_line.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_medium_line_with_config(): """ Test to make sure this rule does trigger with a document that contains a single line with 80 characters with a configured maximum line length of 80. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.line_length=$#50", "--strict-config", "scan", "test/resources/rules/md013/good_medium_line.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/good_medium_line.md:1:1: " + "MD013: Line length " + "[Expected: 50, Actual: 80] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_long_line(): """ Test to make sure this rule does trigger with a document that contains a single line with 80 characters. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_long_line.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/good_long_line.md:1:1: " + "MD013: Line length " + "[Expected: 80, Actual: 100] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_long_line_with_config(): """ Test to make sure this rule does not trigger with a document that contains a single line with 80 characters with a configured maximum line length of 110. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.line_length=$#110", "--strict-config", "scan", "test/resources/rules/md013/good_long_line.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_medium_line_with_long_last_word(): """ Test to make sure this rule does not trigger with a document that contains a single line the crosses the normal 80 character limit with a 31 character last "word". """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_medium_line_with_very_long_last_word.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_medium_line_with_long_last_word_with_config_strict(): """ Test to make sure this rule does trigger with a document that contains a single line the crosses the normal 80 character limit with a 31 character last "word" and strict mode active. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.strict=$!True", "--strict-config", "scan", "test/resources/rules/md013/good_medium_line_with_very_long_last_word.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/good_medium_line_with_very_long_last_word.md:1:1: " + "MD013: Line length " + "[Expected: 80, Actual: 102] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_medium_line_with_long_last_word_with_config_stern(): """ Test to make sure this rule does not trigger with a document that contains a single line the crosses the normal 80 character limit with a 31 character last "word" and stern mode active. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.stern=$!True", "--strict-config", "scan", "test/resources/rules/md013/good_medium_line_with_very_long_last_word.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/good_medium_line_with_very_long_last_word.md:1:1: " + "MD013: Line length " + "[Expected: 80, Actual: 102] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_medium_line_with_long_last_word(): """ Test to make sure this rule does trigger with a document that contains a single line with multiple words past the 80 character boundary. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_medium_line_with_very_long_last_word.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/bad_medium_line_with_very_long_last_word.md:1:1: " + "MD013: Line length " + "[Expected: 80, Actual: 102] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_medium_line_with_long_last_word_with_config_strict(): """ Test to make sure this rule does trigger with a document that contains a single line with multiple words past the 80 character boundary and strict mode. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.strict=$!True", "--strict-config", "scan", "test/resources/rules/md013/bad_medium_line_with_very_long_last_word.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/bad_medium_line_with_very_long_last_word.md:1:1: " + "MD013: Line length " + "[Expected: 80, Actual: 102] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_medium_line_with_long_last_word_with_config_stern(): """ Test to make sure this rule does trigger with a document that contains a single line with multiple words past the 80 character boundary and stern mode. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.stern=$!True", "--strict-config", "scan", "test/resources/rules/md013/bad_medium_line_with_very_long_last_word.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_paragraph_with_long_line_in_middle(): """ Test to make sure this rule does trigger with a document that contains a multiple lines with a very long line in the middle. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_paragraph_with_long_line_in_middle.md", ] expected_return_code = 1 expected_output = ( "test/resources/rules/md013/bad_paragraph_with_long_line_in_middle.md:3:1: " + "MD013: Line length " + "[Expected: 80, Actual: 91] (line-length)" ) expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_fenced_code_block(): """ Test to make sure this rule does not trigger with a document that contains a good line within a fenced code block. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_fenced_code_block.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_fenced_code_block(): """ Test to make sure this rule does trigger with a document that contains a long line within a fenced code block. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_fenced_code_block.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_fenced_code_block.md:6:1: MD013: Line length [Expected: 80, Actual: 146] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_fenced_code_block_with_config(): """ Test to make sure this rule does trigger with a document that contains a very long line within a fenced code block, even with an extended line length for code blocks. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.code_block_line_length=$#100", "--strict-config", "scan", "test/resources/rules/md013/bad_fenced_code_block.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_fenced_code_block.md:6:1: MD013: Line length [Expected: 100, Actual: 146] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_fenced_code_block_with_config_active(): """ Test to make sure this rule does not trigger with a document that contains a long line within a fenced code block, but with the code_block value turned off. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.code_blocks=$!False", "--strict-config", "scan", "test/resources/rules/md013/bad_fenced_code_block.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_indented_code_block(): """ Test to make sure this rule does not trigger with a document that contains a long line within an indented code block, but with the code_block value turned off. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_indented_code_block.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_indented_code_block(): """ Test to make sure this rule does trigger with a document that contains a long line within an indented code block. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_indented_code_block.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_indented_code_block.md:5:1: MD013: Line length [Expected: 80, Actual: 154] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_indented_code_block_with_config(): """ Test to make sure this rule does not trigger with a document that contains a long line within an indented code block, but with the code_block_line_length set to 100. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.code_block_line_length=$#100", "--strict-config", "scan", "test/resources/rules/md013/bad_indented_code_block.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_indented_code_block.md:5:1: MD013: Line length [Expected: 100, Actual: 154] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_indented_code_block_with_config_active(): """ Test to make sure this rule does not trigger with a document that contains a long line within an indented code block, but with the code_blocks set to False. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.code_blocks=$!False", "--strict-config", "scan", "test/resources/rules/md013/bad_indented_code_block.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_thematic_break(): """ Test to make sure this rule does not trigger with a document that contains a normal line within a thematic break. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_thematic_break.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_thematic_break(): """ Test to make sure this rule does trigger with a document that contains a long line within a thematic break. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_thematic_break.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_thematic_break.md:1:1: MD013: Line length [Expected: 80, Actual: 87] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_thematic_break_with_config(): """ Test to make sure this rule does not trigger with a document that contains a long line within a thematic break, but with a configuration to allow the long line. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.line_length=$#100", "--strict-config", "scan", "test/resources/rules/md013/bad_thematic_break.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_atx_heading(): """ Test to make sure this rule does not trigger with a document that contains a normal line within an Atx Heading. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_atx_heading.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_atx_heading(): """ Test to make sure this rule does trigger with a document that contains a long line within an Atx Heading. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_atx_heading.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_atx_heading.md:1:1: MD013: Line length [Expected: 80, Actual: 88] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_atx_heading_with_config(): """ Test to make sure this rule does not trigger with a document that contains a long line within an Atx Heading, but with configuration to allow it. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.heading_line_length=$#100", "--strict-config", "scan", "test/resources/rules/md013/bad_atx_heading.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_atx_heading_with_config_active(): """ Test to make sure this rule does not trigger with a document that contains a long line within an Atx Heading, but with configuration to exclude headings. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.headings=$!False", "--strict-config", "scan", "test/resources/rules/md013/bad_atx_heading.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_setext_heading(): """ Test to make sure this rule does not trigger with a document that contains a normal line within a SetExt Heading. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_setext_heading.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_setext_heading(): """ Test to make sure this rule does trigger with a document that contains a long line within a SetExt Heading. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_setext_heading.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_setext_heading.md:1:1: MD013: Line length [Expected: 80, Actual: 86] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_setext_heading_with_config(): """ Test to make sure this rule does not trigger with a document that contains a long line within a SetExt Heading, but configuration to allow it. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.heading_line_length=$#100", "--strict-config", "scan", "test/resources/rules/md013/bad_setext_heading.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_setext_heading_with_config_active(): """ Test to make sure this rule does not trigger with a document that contains a long line within a SetExt Heading, but with headings turned off. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.headings=$!False", "--strict-config", "scan", "test/resources/rules/md013/bad_setext_heading.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_good_html_block(): """ Test to make sure this rule does not trigger with a document that contains a normal line within a HTML block. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/good_html_block.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_html_block(): """ Test to make sure this rule does trigger with a document that contains a long line within a HTML block. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md013/bad_html_block.md", ] expected_return_code = 1 expected_output = "test/resources/rules/md013/bad_html_block.md:2:1: MD013: Line length [Expected: 80, Actual: 89] (line-length)" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code ) @pytest.mark.rules def test_md013_bad_html_block_with_config(): """ Test to make sure this rule does not trigger with a document that contains a long line within a HTML block, but configuration to allow it. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md013.line_length=$#100", "--strict-config", "scan", "test/resources/rules/md013/bad_html_block.md", ] expected_return_code = 0 expected_output = "" expected_error = "" # Act execute_results = scanner.invoke_main(arguments=supplied_arguments) # Assert execute_results.assert_results( expected_output, expected_error, expected_return_code )
en
0.940333
Module to provide tests related to the MD013 rule. # pylint: disable=too-many-lines Test to verify that a configuration error is thrown when supplying the line_length value with a string that is not an integer. # Arrange # Act # Assert Test to verify that a configuration error is thrown when supplying the line_length value with an integer that is 0. # Arrange #0", # Act # Assert Test to verify that a configuration error is thrown when supplying the heading_line_length value with a string that is not an integer. # Arrange # Act # Assert Test to verify that a configuration error is thrown when supplying the headings value with a string that is not a boolean. # Arrange # Act # Assert Test to verify that a configuration error is thrown when supplying the code_block_line_length value with a string that is not an integer. # Arrange # Act # Assert Test to verify that a configuration error is thrown when supplying the code_blocks value with a string that is not a boolean. # Arrange # Act # Assert Test to verify that a configuration error is thrown when supplying the strict value with a string that is not a boolean. # Arrange # Act # Assert Test to verify that a configuration error is thrown when supplying the stern value with a string that is not a boolean. # Arrange # Act # Assert Test to make sure this rule does not trigger with a document that contains a single line with 38 characters. # Arrange # Act # Assert Test to make sure this rule does trigger with a document that contains a single line with 38 characters, with configuration setting the maximum line length to 25. # Arrange #25", # Act # Assert Test to make sure this rule does not trigger with a document that contains a single line with 80 characters. # Arrange # Act # Assert Test to make sure this rule does trigger with a document that contains a single line with 80 characters with a configured maximum line length of 80. # Arrange #50", # Act # Assert Test to make sure this rule does trigger with a document that contains a single line with 80 characters. # Arrange # Act # Assert Test to make sure this rule does not trigger with a document that contains a single line with 80 characters with a configured maximum line length of 110. # Arrange #110", # Act # Assert Test to make sure this rule does not trigger with a document that contains a single line the crosses the normal 80 character limit with a 31 character last "word". # Arrange # Act # Assert Test to make sure this rule does trigger with a document that contains a single line the crosses the normal 80 character limit with a 31 character last "word" and strict mode active. # Arrange # Act # Assert Test to make sure this rule does not trigger with a document that contains a single line the crosses the normal 80 character limit with a 31 character last "word" and stern mode active. # Arrange # Act # Assert Test to make sure this rule does trigger with a document that contains a single line with multiple words past the 80 character boundary. # Arrange # Act # Assert Test to make sure this rule does trigger with a document that contains a single line with multiple words past the 80 character boundary and strict mode. # Arrange # Act # Assert Test to make sure this rule does trigger with a document that contains a single line with multiple words past the 80 character boundary and stern mode. # Arrange # Act # Assert Test to make sure this rule does trigger with a document that contains a multiple lines with a very long line in the middle. # Arrange # Act # Assert Test to make sure this rule does not trigger with a document that contains a good line within a fenced code block. # Arrange # Act # Assert Test to make sure this rule does trigger with a document that contains a long line within a fenced code block. # Arrange # Act # Assert Test to make sure this rule does trigger with a document that contains a very long line within a fenced code block, even with an extended line length for code blocks. # Arrange #100", # Act # Assert Test to make sure this rule does not trigger with a document that contains a long line within a fenced code block, but with the code_block value turned off. # Arrange # Act # Assert Test to make sure this rule does not trigger with a document that contains a long line within an indented code block, but with the code_block value turned off. # Arrange # Act # Assert Test to make sure this rule does trigger with a document that contains a long line within an indented code block. # Arrange # Act # Assert Test to make sure this rule does not trigger with a document that contains a long line within an indented code block, but with the code_block_line_length set to 100. # Arrange #100", # Act # Assert Test to make sure this rule does not trigger with a document that contains a long line within an indented code block, but with the code_blocks set to False. # Arrange # Act # Assert Test to make sure this rule does not trigger with a document that contains a normal line within a thematic break. # Arrange # Act # Assert Test to make sure this rule does trigger with a document that contains a long line within a thematic break. # Arrange # Act # Assert Test to make sure this rule does not trigger with a document that contains a long line within a thematic break, but with a configuration to allow the long line. # Arrange #100", # Act # Assert Test to make sure this rule does not trigger with a document that contains a normal line within an Atx Heading. # Arrange # Act # Assert Test to make sure this rule does trigger with a document that contains a long line within an Atx Heading. # Arrange # Act # Assert Test to make sure this rule does not trigger with a document that contains a long line within an Atx Heading, but with configuration to allow it. # Arrange #100", # Act # Assert Test to make sure this rule does not trigger with a document that contains a long line within an Atx Heading, but with configuration to exclude headings. # Arrange # Act # Assert Test to make sure this rule does not trigger with a document that contains a normal line within a SetExt Heading. # Arrange # Act # Assert Test to make sure this rule does trigger with a document that contains a long line within a SetExt Heading. # Arrange # Act # Assert Test to make sure this rule does not trigger with a document that contains a long line within a SetExt Heading, but configuration to allow it. # Arrange #100", # Act # Assert Test to make sure this rule does not trigger with a document that contains a long line within a SetExt Heading, but with headings turned off. # Arrange # Act # Assert Test to make sure this rule does not trigger with a document that contains a normal line within a HTML block. # Arrange # Act # Assert Test to make sure this rule does trigger with a document that contains a long line within a HTML block. # Arrange # Act # Assert Test to make sure this rule does not trigger with a document that contains a long line within a HTML block, but configuration to allow it. # Arrange #100", # Act # Assert
3.406898
3
cli/node_account/help.py
Remmeauth/remme-core-cli
0
6612728
""" Provide help messages for command line interface's node account commands. """ NODE_ACCOUNT_ADDRESS_ARGUMENT_HELP_MESSAGE = 'Node account address to get information about node account by.' ACCOUNT_ADDRESS_TO_ARGUMENT_HELP_MESSAGE = 'Account address to transfer tokens to.' AMOUNT_ARGUMENT_HELP_MESSAGE = 'Amount to transfer.' PRIVATE_KEY_ARGUMENT_HELP_MESSAGE = 'Account\'s private key to transfer tokens from.'
""" Provide help messages for command line interface's node account commands. """ NODE_ACCOUNT_ADDRESS_ARGUMENT_HELP_MESSAGE = 'Node account address to get information about node account by.' ACCOUNT_ADDRESS_TO_ARGUMENT_HELP_MESSAGE = 'Account address to transfer tokens to.' AMOUNT_ARGUMENT_HELP_MESSAGE = 'Amount to transfer.' PRIVATE_KEY_ARGUMENT_HELP_MESSAGE = 'Account\'s private key to transfer tokens from.'
en
0.849806
Provide help messages for command line interface's node account commands.
1.588117
2
atest_v3.py
karianjahi/temperature_app
0
6612729
""" We need to create tests for the temperature.py file to make sure that changes in future are detectable in case of a collaboration. We shall write a class that inherits from TestCase of the unittest package to take advantage of the many elegant testing functionalities in the package. Google 'unittest Testcase' for documentation We shall remain guided by pylint to keep the file to the PEP standard """ # pylint: disable=C0301 # pylint: disable=W0102 # pylint: disable=R0913 # pylint: disable=W0702 import unittest from temperature.data_science_files.temperature import Temperature class TestTemperature(unittest.TestCase): """ This test class inherits from TestCase methods of the unittest """ CITIES_DB_FILE = "temperature/data_science_files/data/worldcities.csv" USER_CITIES = ["Berlin", "Leipzig", "Cologne", "Dortmund", "Karlsruhe"] DATE_OF_REQUEST = "2021-10-18" ASSERT_MESSAGE = "This class displays temperature for these locations: [Berlin, Leipzig, Cologne, Dortmund, Karlsruhe,]" def _testing_instances(self, locations_file=CITIES_DB_FILE, requested_locations=USER_CITIES, date_of_request=DATE_OF_REQUEST, assert_message=ASSERT_MESSAGE, is_all_correct_instance=True): """ Internal method for testing instances """ temp_obj = Temperature(locations_file, requested_locations, date_of_request) if is_all_correct_instance: self.assertEqual(assert_message, str(temp_obj)) else: for instance in range(1, 6): try: temp_obj.confirm_instances(instance) except: with self.assertRaises(ValueError) as error: temp_obj.confirm_instances(instance) self.assertEqual(assert_message, str(error.exception)) return temp_obj def test_confirm_correct_instances(self): """ Testing that the default attributes are actually of the right instance (type) """ self._testing_instances() def test_wrong_type_locations_file(self): """ Deliberately change the type of locations file """ locations_file = {"locations_file": TestTemperature.CITIES_DB_FILE} assert_message = "A string is required as path to locations file" self._testing_instances(locations_file=locations_file, assert_message=assert_message, is_all_correct_instance=False) def test_wrong_type_requested_locations(self): """ Deliberately change the type of user requested locations """ user_locations = {"user_locations": TestTemperature.USER_CITIES} assert_message = "Requested locations should be a list" self._testing_instances(requested_locations=user_locations, assert_message=assert_message, is_all_correct_instance=False) def test_wrong_type_date(self): """ Deliberately change the type of given date """ date = {"date": TestTemperature.DATE_OF_REQUEST} assert_message = f"{date} not a string in the format YYYY-MM-DD" self._testing_instances(date_of_request=date, assert_message=assert_message, is_all_correct_instance=False) def test_wrong_type_requested_location_item(self): """ Test if every item in user given locations is a string """ user_locations = ["Berlin", "Karlsruhe", "Stuttgart", 79241] assert_message = "79241 not a string" self._testing_instances(requested_locations=user_locations, assert_message=assert_message, is_all_correct_instance=False) def test_date_integer_instance(self): """ Deliberately setting a date to be an integer to trigger error """ date = 2021-10-25 assert_message = f'{date} not a string in the format YYYY-MM-DD' self._testing_instances(date_of_request=date, assert_message=assert_message, is_all_correct_instance=False) def test_convert_user_locations_to_ascii(self): """ Test if accents can be converted to ascii """ user_locations = ["Münich", "Berlin", "Düsseldorf", "Köln", "Frankfurt"] assert_message = "This class displays temperature for these locations: [Münich, Berlin, Düsseldorf, Köln, Frankfurt,]" obj = self._testing_instances(assert_message=assert_message, requested_locations=user_locations, is_all_correct_instance=True) expected = ["Munich", "Berlin", "Dusseldorf", "Koln", "Frankfurt"] self.assertEqual(expected, obj.convert_user_locations_to_ascii()) def test_identify_valid_and_invalid_locations(self): """ Test for valid and invalid locations """ user_locations = ["Berlin", "Rome", "Toulouse", "Zagreb", "Bucharest", "Frankfurt"] assert_message = "This class displays temperature for these locations: [Berlin, Rome, Toulouse, Zagreb, Bucharest, Frankfurt,]" obj = self._testing_instances(requested_locations=user_locations, assert_message=assert_message, is_all_correct_instance=True) expected_valid = sorted(["Berlin", "Frankfurt"]) expected_invalid = sorted(["Rome", "Toulouse", "Zagreb", "Bucharest"]) actual_valid = [i.title() for i in sorted(obj.identify_valid_and_invalid_locations()["valid_locations"])] actual_invalid = [i.title() for i in sorted(obj.identify_valid_and_invalid_locations()["invalid_locations"])] self.assertEqual(expected_valid, actual_valid) self.assertEqual(expected_invalid, actual_invalid) def test_error_for_unrecognized_locations(self): """ Raise error if all stations are unrecognized """ user_locations = ["Nairobi", "Kampala", "Jakarta"] assert_message = "This class displays temperature for these locations: [Nairobi, Kampala, Jakarta,]" obj = self._testing_instances(assert_message=assert_message, requested_locations=user_locations, is_all_correct_instance=True) with self.assertRaises(Exception) as error: obj.raise_error_if_all_locations_unrecognized() self.assertEqual("['nairobi', 'kampala', 'jakarta'] not recognized", str(error.exception)) def test_get_geocoordinates(self): """ testing for geocoordinates for berlin """ geo_coords = self._testing_instances().get_geocoordinates() expected_berlin_coords = {"lon": 13.3833, "lat": 52.5167} actual_berlin_coords = geo_coords["berlin"] self.assertEqual(expected_berlin_coords, actual_berlin_coords) def test_api_has_temperature_data(self): """ Testing that API has temperature data """ temp_data = self._testing_instances().get_temperature_data() expected_column_names = TestTemperature.USER_CITIES actual_column_names = [str(i) for i in temp_data.columns] for expected, actual in zip(expected_column_names, actual_column_names): self.assertEqual(expected, actual) def test_weather_api_no_data(self): """ When weather api has found no data """ date = "2024-09-22" expected_message = {"status": 404, "Detail": "date not in range"} status_message = self._testing_instances(date_of_request=date).get_temperature_data() self.assertEqual(expected_message, status_message)
""" We need to create tests for the temperature.py file to make sure that changes in future are detectable in case of a collaboration. We shall write a class that inherits from TestCase of the unittest package to take advantage of the many elegant testing functionalities in the package. Google 'unittest Testcase' for documentation We shall remain guided by pylint to keep the file to the PEP standard """ # pylint: disable=C0301 # pylint: disable=W0102 # pylint: disable=R0913 # pylint: disable=W0702 import unittest from temperature.data_science_files.temperature import Temperature class TestTemperature(unittest.TestCase): """ This test class inherits from TestCase methods of the unittest """ CITIES_DB_FILE = "temperature/data_science_files/data/worldcities.csv" USER_CITIES = ["Berlin", "Leipzig", "Cologne", "Dortmund", "Karlsruhe"] DATE_OF_REQUEST = "2021-10-18" ASSERT_MESSAGE = "This class displays temperature for these locations: [Berlin, Leipzig, Cologne, Dortmund, Karlsruhe,]" def _testing_instances(self, locations_file=CITIES_DB_FILE, requested_locations=USER_CITIES, date_of_request=DATE_OF_REQUEST, assert_message=ASSERT_MESSAGE, is_all_correct_instance=True): """ Internal method for testing instances """ temp_obj = Temperature(locations_file, requested_locations, date_of_request) if is_all_correct_instance: self.assertEqual(assert_message, str(temp_obj)) else: for instance in range(1, 6): try: temp_obj.confirm_instances(instance) except: with self.assertRaises(ValueError) as error: temp_obj.confirm_instances(instance) self.assertEqual(assert_message, str(error.exception)) return temp_obj def test_confirm_correct_instances(self): """ Testing that the default attributes are actually of the right instance (type) """ self._testing_instances() def test_wrong_type_locations_file(self): """ Deliberately change the type of locations file """ locations_file = {"locations_file": TestTemperature.CITIES_DB_FILE} assert_message = "A string is required as path to locations file" self._testing_instances(locations_file=locations_file, assert_message=assert_message, is_all_correct_instance=False) def test_wrong_type_requested_locations(self): """ Deliberately change the type of user requested locations """ user_locations = {"user_locations": TestTemperature.USER_CITIES} assert_message = "Requested locations should be a list" self._testing_instances(requested_locations=user_locations, assert_message=assert_message, is_all_correct_instance=False) def test_wrong_type_date(self): """ Deliberately change the type of given date """ date = {"date": TestTemperature.DATE_OF_REQUEST} assert_message = f"{date} not a string in the format YYYY-MM-DD" self._testing_instances(date_of_request=date, assert_message=assert_message, is_all_correct_instance=False) def test_wrong_type_requested_location_item(self): """ Test if every item in user given locations is a string """ user_locations = ["Berlin", "Karlsruhe", "Stuttgart", 79241] assert_message = "79241 not a string" self._testing_instances(requested_locations=user_locations, assert_message=assert_message, is_all_correct_instance=False) def test_date_integer_instance(self): """ Deliberately setting a date to be an integer to trigger error """ date = 2021-10-25 assert_message = f'{date} not a string in the format YYYY-MM-DD' self._testing_instances(date_of_request=date, assert_message=assert_message, is_all_correct_instance=False) def test_convert_user_locations_to_ascii(self): """ Test if accents can be converted to ascii """ user_locations = ["Münich", "Berlin", "Düsseldorf", "Köln", "Frankfurt"] assert_message = "This class displays temperature for these locations: [Münich, Berlin, Düsseldorf, Köln, Frankfurt,]" obj = self._testing_instances(assert_message=assert_message, requested_locations=user_locations, is_all_correct_instance=True) expected = ["Munich", "Berlin", "Dusseldorf", "Koln", "Frankfurt"] self.assertEqual(expected, obj.convert_user_locations_to_ascii()) def test_identify_valid_and_invalid_locations(self): """ Test for valid and invalid locations """ user_locations = ["Berlin", "Rome", "Toulouse", "Zagreb", "Bucharest", "Frankfurt"] assert_message = "This class displays temperature for these locations: [Berlin, Rome, Toulouse, Zagreb, Bucharest, Frankfurt,]" obj = self._testing_instances(requested_locations=user_locations, assert_message=assert_message, is_all_correct_instance=True) expected_valid = sorted(["Berlin", "Frankfurt"]) expected_invalid = sorted(["Rome", "Toulouse", "Zagreb", "Bucharest"]) actual_valid = [i.title() for i in sorted(obj.identify_valid_and_invalid_locations()["valid_locations"])] actual_invalid = [i.title() for i in sorted(obj.identify_valid_and_invalid_locations()["invalid_locations"])] self.assertEqual(expected_valid, actual_valid) self.assertEqual(expected_invalid, actual_invalid) def test_error_for_unrecognized_locations(self): """ Raise error if all stations are unrecognized """ user_locations = ["Nairobi", "Kampala", "Jakarta"] assert_message = "This class displays temperature for these locations: [Nairobi, Kampala, Jakarta,]" obj = self._testing_instances(assert_message=assert_message, requested_locations=user_locations, is_all_correct_instance=True) with self.assertRaises(Exception) as error: obj.raise_error_if_all_locations_unrecognized() self.assertEqual("['nairobi', 'kampala', 'jakarta'] not recognized", str(error.exception)) def test_get_geocoordinates(self): """ testing for geocoordinates for berlin """ geo_coords = self._testing_instances().get_geocoordinates() expected_berlin_coords = {"lon": 13.3833, "lat": 52.5167} actual_berlin_coords = geo_coords["berlin"] self.assertEqual(expected_berlin_coords, actual_berlin_coords) def test_api_has_temperature_data(self): """ Testing that API has temperature data """ temp_data = self._testing_instances().get_temperature_data() expected_column_names = TestTemperature.USER_CITIES actual_column_names = [str(i) for i in temp_data.columns] for expected, actual in zip(expected_column_names, actual_column_names): self.assertEqual(expected, actual) def test_weather_api_no_data(self): """ When weather api has found no data """ date = "2024-09-22" expected_message = {"status": 404, "Detail": "date not in range"} status_message = self._testing_instances(date_of_request=date).get_temperature_data() self.assertEqual(expected_message, status_message)
en
0.837741
We need to create tests for the temperature.py file to make sure that changes in future are detectable in case of a collaboration. We shall write a class that inherits from TestCase of the unittest package to take advantage of the many elegant testing functionalities in the package. Google 'unittest Testcase' for documentation We shall remain guided by pylint to keep the file to the PEP standard # pylint: disable=C0301 # pylint: disable=W0102 # pylint: disable=R0913 # pylint: disable=W0702 This test class inherits from TestCase methods of the unittest Internal method for testing instances Testing that the default attributes are actually of the right instance (type) Deliberately change the type of locations file Deliberately change the type of user requested locations Deliberately change the type of given date Test if every item in user given locations is a string Deliberately setting a date to be an integer to trigger error Test if accents can be converted to ascii Test for valid and invalid locations Raise error if all stations are unrecognized testing for geocoordinates for berlin Testing that API has temperature data When weather api has found no data
3.753923
4
test.py
hbina/aoihana
0
6612730
#!/usr/bin/python3 from pathlib import Path import subprocess import os import string import sys import threading SOURCE_DIR: str = './tests' BUILD_DIR: str = "./build" C_COMPILER: str = "gcc" def task(filename: Path): output_name = f"{Path(filename).stem}_test" final_output_file = f"{BUILD_DIR}/{output_name}" subprocess.run(args=[C_COMPILER, filename, "-g", "-o", final_output_file]) subprocess.run(args=[final_output_file]) print(f"done testing {final_output_file}") if __name__ == '__main__': Path(f"{BUILD_DIR}").mkdir(parents=True, exist_ok=True) tasks = [] for dirName, subdirList, fileList in os.walk(SOURCE_DIR): for fname in list(filter(lambda x: x.endswith(".c"), fileList)): test_c_file = f"{dirName}/{fname}" print(f"compiling:{test_c_file}") thread = threading.Thread(target=task, args=(test_c_file,)) thread.start() tasks.append(thread) for i, task in enumerate(tasks): task.join()
#!/usr/bin/python3 from pathlib import Path import subprocess import os import string import sys import threading SOURCE_DIR: str = './tests' BUILD_DIR: str = "./build" C_COMPILER: str = "gcc" def task(filename: Path): output_name = f"{Path(filename).stem}_test" final_output_file = f"{BUILD_DIR}/{output_name}" subprocess.run(args=[C_COMPILER, filename, "-g", "-o", final_output_file]) subprocess.run(args=[final_output_file]) print(f"done testing {final_output_file}") if __name__ == '__main__': Path(f"{BUILD_DIR}").mkdir(parents=True, exist_ok=True) tasks = [] for dirName, subdirList, fileList in os.walk(SOURCE_DIR): for fname in list(filter(lambda x: x.endswith(".c"), fileList)): test_c_file = f"{dirName}/{fname}" print(f"compiling:{test_c_file}") thread = threading.Thread(target=task, args=(test_c_file,)) thread.start() tasks.append(thread) for i, task in enumerate(tasks): task.join()
fr
0.386793
#!/usr/bin/python3
2.747931
3
runx.py
Axrid/cv_template
2
6612731
<reponame>Axrid/cv_template # encoding = utf-8 """ 借鉴自NVIDIA的深度学习实验管理工具runx(https://github.com/NVIDIA/runx)。自己重写了一下。 可以按照yml配置文件实现grid_searching。 用法: python runx.py --sweep sweep.yml --show # 默认 python runx.py --sweep sweep.yml --run """ import argparse import misc_utils as utils import random import string import yaml import os def load_yml(file='sweep.yml', op=None): if not os.path.isfile(file): raise FileNotFoundError('File "%s" not found' % file) with open(file, 'r') as f: try: cfg = yaml.safe_load(f.read()) except yaml.YAMLError: raise Exception('Error parsing YAML file: ' + file) if op: return cfg[op] else: return cfg def hash(n): choices = '0123456789abcdef' ans = '' for _ in range(n): ans += choices[random.randint(0, 15)] return ans def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--sweep', type=str, default='sweep.yml', help='configure file, default is "sweep.yml"') parser.add_argument('--show', action='store_true', default=True) parser.add_argument('--run', action='store_true') return parser.parse_args() opt = parse_args() if __name__ == '__main__': cfg = load_yml(opt.sweep) cmd = cfg['cmd'] hparams = cfg['hparams'].items() hparams = list(hparams) n = len(hparams) temp = [''] * n ans = [] def dfs(i): if i >= n: ans.append(temp.copy()) # print(temp) return hparam, choices = hparams[i] for choice in choices: temp[i] = choice dfs(i+1) dfs(0) # for hparam in hparams: for i, one_run in enumerate(ans): command = cmd + ' --tag %s' % hash(8) for (hparam, _), choice in zip(hparams, one_run): command += ' --%s %s' % (hparam, choice) utils.color_print(('%d/%d: ' % ((i+1), len(ans)) + command), 4) if opt.run: os.system(command)
# encoding = utf-8 """ 借鉴自NVIDIA的深度学习实验管理工具runx(https://github.com/NVIDIA/runx)。自己重写了一下。 可以按照yml配置文件实现grid_searching。 用法: python runx.py --sweep sweep.yml --show # 默认 python runx.py --sweep sweep.yml --run """ import argparse import misc_utils as utils import random import string import yaml import os def load_yml(file='sweep.yml', op=None): if not os.path.isfile(file): raise FileNotFoundError('File "%s" not found' % file) with open(file, 'r') as f: try: cfg = yaml.safe_load(f.read()) except yaml.YAMLError: raise Exception('Error parsing YAML file: ' + file) if op: return cfg[op] else: return cfg def hash(n): choices = '0123456789abcdef' ans = '' for _ in range(n): ans += choices[random.randint(0, 15)] return ans def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--sweep', type=str, default='sweep.yml', help='configure file, default is "sweep.yml"') parser.add_argument('--show', action='store_true', default=True) parser.add_argument('--run', action='store_true') return parser.parse_args() opt = parse_args() if __name__ == '__main__': cfg = load_yml(opt.sweep) cmd = cfg['cmd'] hparams = cfg['hparams'].items() hparams = list(hparams) n = len(hparams) temp = [''] * n ans = [] def dfs(i): if i >= n: ans.append(temp.copy()) # print(temp) return hparam, choices = hparams[i] for choice in choices: temp[i] = choice dfs(i+1) dfs(0) # for hparam in hparams: for i, one_run in enumerate(ans): command = cmd + ' --tag %s' % hash(8) for (hparam, _), choice in zip(hparams, one_run): command += ' --%s %s' % (hparam, choice) utils.color_print(('%d/%d: ' % ((i+1), len(ans)) + command), 4) if opt.run: os.system(command)
zh
0.618061
# encoding = utf-8 借鉴自NVIDIA的深度学习实验管理工具runx(https://github.com/NVIDIA/runx)。自己重写了一下。 可以按照yml配置文件实现grid_searching。 用法: python runx.py --sweep sweep.yml --show # 默认 python runx.py --sweep sweep.yml --run # print(temp) # for hparam in hparams:
3.360653
3
auth_service/src/AuthService/change_user_role.py
newgene/biothings_oauth
0
6612732
<filename>auth_service/src/AuthService/change_user_role.py<gh_stars>0 import sys from auth.models import User, UserRole from AuthService.database import Session DB = Session() def change_user_role(user_id, new_role): """ Changes a user's role. @param user_id: ID of the user. @param new_role: The new role to set for the user. """ roles = [r.name for r in UserRole] if new_role.upper() not in roles: raise Exception(f"The given role '{new_role}' is not valid!\n" f"The available roles are: {', '.join(roles)}.") user = DB.query(User).filter(User.id == user_id).first() if not user: raise Exception(f"User with ID = {user_id} was not found!") user.role = new_role.upper() DB.commit() print(f"User with ID = {user_id} is now '{new_role.upper()}'.") if __name__ == "__main__": if len(sys.argv) != 3: raise Exception("Bad script usage!\n" "You must provide user ID with new user role.") change_user_role(int(sys.argv[1]), sys.argv[2])
<filename>auth_service/src/AuthService/change_user_role.py<gh_stars>0 import sys from auth.models import User, UserRole from AuthService.database import Session DB = Session() def change_user_role(user_id, new_role): """ Changes a user's role. @param user_id: ID of the user. @param new_role: The new role to set for the user. """ roles = [r.name for r in UserRole] if new_role.upper() not in roles: raise Exception(f"The given role '{new_role}' is not valid!\n" f"The available roles are: {', '.join(roles)}.") user = DB.query(User).filter(User.id == user_id).first() if not user: raise Exception(f"User with ID = {user_id} was not found!") user.role = new_role.upper() DB.commit() print(f"User with ID = {user_id} is now '{new_role.upper()}'.") if __name__ == "__main__": if len(sys.argv) != 3: raise Exception("Bad script usage!\n" "You must provide user ID with new user role.") change_user_role(int(sys.argv[1]), sys.argv[2])
en
0.456738
Changes a user's role. @param user_id: ID of the user. @param new_role: The new role to set for the user.
2.864535
3
I3/1362.py
AHalic/grafos-URI
0
6612733
<reponame>AHalic/grafos-URI import sys # Dicionario usado pra encontrar o valor no grafo tamanhos_indice = { 'XS': 1, 'S': 2, 'M': 3, 'L': 4, 'XL': 5, 'XXL': 6 } # Procura o vertice de menor peso na arvore def find_min(pesos, arvore, tam): aux_min = sys.maxsize node = tam - 1 # Busca no vetor for i in range(tam): # Procura vertice que ainda não esteja na arvore e tenha menor peso if pesos[i] < aux_min and i not in arvore: aux_min = pesos[i] node = i return node def dijkstra(grafo, tam): # Inicializa o vetor de pesos com um valor muito grande pesos = [sys.maxsize] * tam # Escolhe o ponto inicial e modifica o peso pesos[0] = 0 visitados = set() sumidouro = tam - 1 # Vetor de pais usado para saber qual corte achado (pra ser usado no Ford) pais = [i for i in range(tam)] while sumidouro not in visitados: # Acha o vertice de menor peso e adiciona ele u = find_min(pesos, visitados, tam) visitados.add(u) # Relaxa os vertices vizinhos de u for w in range(tam): dist_w = pesos[u] + grafo[u][w] if grafo[u][w] != 0 and w not in visitados and pesos[w] > dist_w: pesos[w] = dist_w pais[w] = u # Retorna a arvore encontrada return pais def ford_fulkerson(grafo, tam): fluxo_max = 0 sumidouro = tam - 1 # Encontra o corte pais = dijkstra(grafo, tam) # Enquanto for possível alcançar t while pais[sumidouro] != sumidouro: # Encontra no que chegou no sumidouro aux_origem = pais[sumidouro] aux_destino = sumidouro while True: # Altera o fluxo de ida e volta grafo[aux_origem][aux_destino] -= 1 grafo[aux_destino][aux_origem] += 1 # Encontra a conexao aux_destino = aux_origem aux_origem = pais[aux_origem] # Até encontrar o vértice s (origem) if aux_destino == 0: break # Fluxo do corte (neste grafo) sempre é 1 fluxo_max += 1 pais = dijkstra(grafo, tam) return fluxo_max ########### Leitura casos = int(input()) for _ in range(casos): camisas, voluntarios = map(int, input().split()) # Qtd de vertices do grafo: 6 tamanhos de blusa + n voluntarios + origem e sumidouro nos = 6 + voluntarios + 2 # Cria grafo grafo = [[0 for i in range(6 + voluntarios + 2)] for _ in range(6 + voluntarios + 2)] qtd_camisas = int(camisas/6) # Cria conexoes do grafo de blusas para sumidouro for i in range(1, 7): grafo[voluntarios+i][len(grafo)-1] = qtd_camisas # Cria conexoes grafos de voluntarios para blusas for i in range(1, voluntarios+1): tamanho1, tamanho2 = map(str, input().split()) # conexoes origem - voluntarios grafo[0][i] = 1 # conexoes voluntarios - blusas grafo[i][voluntarios+tamanhos_indice[tamanho1]] = 1 grafo[i][voluntarios+tamanhos_indice[tamanho2]] = 1 # Apresenta resposta if ford_fulkerson(grafo, nos) == voluntarios: print("YES") else: print("NO")
import sys # Dicionario usado pra encontrar o valor no grafo tamanhos_indice = { 'XS': 1, 'S': 2, 'M': 3, 'L': 4, 'XL': 5, 'XXL': 6 } # Procura o vertice de menor peso na arvore def find_min(pesos, arvore, tam): aux_min = sys.maxsize node = tam - 1 # Busca no vetor for i in range(tam): # Procura vertice que ainda não esteja na arvore e tenha menor peso if pesos[i] < aux_min and i not in arvore: aux_min = pesos[i] node = i return node def dijkstra(grafo, tam): # Inicializa o vetor de pesos com um valor muito grande pesos = [sys.maxsize] * tam # Escolhe o ponto inicial e modifica o peso pesos[0] = 0 visitados = set() sumidouro = tam - 1 # Vetor de pais usado para saber qual corte achado (pra ser usado no Ford) pais = [i for i in range(tam)] while sumidouro not in visitados: # Acha o vertice de menor peso e adiciona ele u = find_min(pesos, visitados, tam) visitados.add(u) # Relaxa os vertices vizinhos de u for w in range(tam): dist_w = pesos[u] + grafo[u][w] if grafo[u][w] != 0 and w not in visitados and pesos[w] > dist_w: pesos[w] = dist_w pais[w] = u # Retorna a arvore encontrada return pais def ford_fulkerson(grafo, tam): fluxo_max = 0 sumidouro = tam - 1 # Encontra o corte pais = dijkstra(grafo, tam) # Enquanto for possível alcançar t while pais[sumidouro] != sumidouro: # Encontra no que chegou no sumidouro aux_origem = pais[sumidouro] aux_destino = sumidouro while True: # Altera o fluxo de ida e volta grafo[aux_origem][aux_destino] -= 1 grafo[aux_destino][aux_origem] += 1 # Encontra a conexao aux_destino = aux_origem aux_origem = pais[aux_origem] # Até encontrar o vértice s (origem) if aux_destino == 0: break # Fluxo do corte (neste grafo) sempre é 1 fluxo_max += 1 pais = dijkstra(grafo, tam) return fluxo_max ########### Leitura casos = int(input()) for _ in range(casos): camisas, voluntarios = map(int, input().split()) # Qtd de vertices do grafo: 6 tamanhos de blusa + n voluntarios + origem e sumidouro nos = 6 + voluntarios + 2 # Cria grafo grafo = [[0 for i in range(6 + voluntarios + 2)] for _ in range(6 + voluntarios + 2)] qtd_camisas = int(camisas/6) # Cria conexoes do grafo de blusas para sumidouro for i in range(1, 7): grafo[voluntarios+i][len(grafo)-1] = qtd_camisas # Cria conexoes grafos de voluntarios para blusas for i in range(1, voluntarios+1): tamanho1, tamanho2 = map(str, input().split()) # conexoes origem - voluntarios grafo[0][i] = 1 # conexoes voluntarios - blusas grafo[i][voluntarios+tamanhos_indice[tamanho1]] = 1 grafo[i][voluntarios+tamanhos_indice[tamanho2]] = 1 # Apresenta resposta if ford_fulkerson(grafo, nos) == voluntarios: print("YES") else: print("NO")
pt
0.832623
# Dicionario usado pra encontrar o valor no grafo # Procura o vertice de menor peso na arvore # Busca no vetor # Procura vertice que ainda não esteja na arvore e tenha menor peso # Inicializa o vetor de pesos com um valor muito grande # Escolhe o ponto inicial e modifica o peso # Vetor de pais usado para saber qual corte achado (pra ser usado no Ford) # Acha o vertice de menor peso e adiciona ele # Relaxa os vertices vizinhos de u # Retorna a arvore encontrada # Encontra o corte # Enquanto for possível alcançar t # Encontra no que chegou no sumidouro # Altera o fluxo de ida e volta # Encontra a conexao # Até encontrar o vértice s (origem) # Fluxo do corte (neste grafo) sempre é 1 ########### Leitura # Qtd de vertices do grafo: 6 tamanhos de blusa + n voluntarios + origem e sumidouro # Cria grafo # Cria conexoes do grafo de blusas para sumidouro # Cria conexoes grafos de voluntarios para blusas # conexoes origem - voluntarios # conexoes voluntarios - blusas # Apresenta resposta
3.367745
3
tensorkit/flows/act_norm.py
lizeyan/tensorkit
0
6612734
<filename>tensorkit/flows/act_norm.py from functools import partial from typing import * from .. import init, tensor as T from ..tensor import (Tensor, Module, reshape, shape, int_range, calculate_mean_and_var, assert_finite, float_scalar_like, maximum, log, sqrt) from ..layers import * from ..typing_ import * from .core import * __all__ = [ 'ActNorm', 'ActNorm1d', 'ActNorm2d', 'ActNorm3d', ] class ActNorm(FeatureMappingFlow): """ ActNorm proposed by (Kingma & Dhariwal, 2018). `y = (x + bias) * scale; log_det = y / scale - bias` `bias` and `scale` are initialized such that `y` will have zero mean and unit variance for the initial mini-batch of `x`. It can be initialized only through the forward pass. You may need to use :meth:`BaseFlow.invert()` to get a inverted flow if you need to initialize the parameters via the opposite direction. """ __constants__ = FeatureMappingFlow.__constants__ + ( 'num_features', 'scale_type', 'epsilon', ) num_features: int scale: Module scale_type: str epsilon: float initialized: bool def __init__(self, num_features: int, axis: int = -1, event_ndims: int = 1, scale: Union[str, ActNormScaleType] = 'exp', initialized: bool = False, dtype: str = T.float_x(), device: Optional[str] = None, epsilon: float = T.EPSILON): """ Construct a new :class:`ActNorm` instance. Args: num_features: The size of the feature axis. scale: One of {"exp", "linear"}. If "exp", ``y = (x + bias) * tf.exp(log_scale)``. If "linear", ``y = (x + bias) * scale``. Defaults to "exp". axis: The axis to apply ActNorm. Dimensions not in `axis` will be averaged out when computing the mean of activations. Default `-1`, the last dimension. All items of the `axis` should be covered by `event_ndims`. event_ndims: Number of value dimensions in both `x` and `y`. `x.ndims - event_ndims == log_det.ndims` and `y.ndims - event_ndims == log_det.ndims`. initialized: Whether or not the variables have been initialized? Defaults to :obj:`False`, where the first input `x` in the forward pass will be used to initialize the variables. dtype: Dtype of the parameters. device: The device where to place new tensors and variables. epsilon: The infinitesimal constant to avoid dividing by zero or taking logarithm of zero. """ # validate the arguments scale_type = ActNormScaleType(scale) epsilon = float(epsilon) if scale_type == ActNormScaleType.EXP: scale = ExpScale() pre_scale_init = partial(init.fill, fill_value=0.) elif scale_type == ActNormScaleType.LINEAR: scale = LinearScale(epsilon=epsilon) pre_scale_init = partial(init.fill, fill_value=1.) else: # pragma: no cover raise ValueError(f'Unsupported `scale_type`: {scale_type}') device = device or T.current_device() # construct the layer super().__init__(axis=axis, event_ndims=event_ndims, explicitly_invertible=True) self.num_features = num_features self.scale = scale self.scale_type = scale_type.value self.epsilon = epsilon self.initialized = initialized add_parameter( self, 'pre_scale', T.variable([num_features], dtype=dtype, initializer=pre_scale_init, device=device), ) add_parameter( self, 'bias', T.variable([num_features], dtype=dtype, initializer=init.zeros, device=device), ) @T.jit_method def set_initialized(self, initialized: bool = True) -> None: self.initialized = initialized @T.jit_method def calculate_bias_and_pre_scale_for_init(self, input: Tensor) -> Tuple[Tensor, Tensor]: # PyTorch 1.3.1 bug: cannot mark this method as returning `None`. input_rank = T.rank(input) if not isinstance(input, Tensor) or input_rank < self.x_event_ndims + 1: raise ValueError( '`input` is required to be a tensor with at least {} dimensions: ' 'got input shape {}.'. format(self.x_event_ndims, shape(input)) ) # calculate the axis to reduce feature_axis = input_rank + self.axis reduce_axis = ( int_range(0, feature_axis) + int_range(feature_axis + 1, input_rank) ) # calculate sample mean and variance input_mean, input_var = calculate_mean_and_var( input, axis=reduce_axis, unbiased=True) input_var = assert_finite(input_var, 'input_var') # calculate the initial_value for `bias` bias = -input_mean # calculate the initial value for `pre_scale` epsilon = float_scalar_like(self.epsilon, input_var) if self.scale_type == 'exp': pre_scale = -0.5 * log(maximum(input_var, epsilon)) else: pre_scale = 1. / sqrt(maximum(input_var, epsilon)) return bias, pre_scale @T.jit_ignore def _initialize_act_norm(self, input: Tensor) -> bool: bias, pre_scale = self.calculate_bias_and_pre_scale_for_init(input) with T.no_grad(): T.assign(self.bias, bias) T.assign(self.pre_scale, pre_scale) self.set_initialized(True) return False @T.jit_method def _transform(self, input: Tensor, input_log_det: Optional[Tensor], inverse: bool, compute_log_det: bool ) -> Tuple[Tensor, Optional[Tensor]]: # initialize the parameters if not self.initialized: if inverse: raise RuntimeError( '`ActNorm` must be initialized with `inverse = False`.') # self.initialize_with_input(input) self._initialize_act_norm(input) self.set_initialized(True) # do transformation shape_aligned = [self.num_features] + [1] * (-self.axis - 1) shift = reshape(self.bias, shape_aligned) pre_scale = reshape(self.pre_scale, shape_aligned) input = input if inverse else input + shift event_ndims = self.x_event_ndims input, input_log_det = self.scale( input=input, pre_scale=pre_scale, event_ndims=event_ndims, input_log_det=input_log_det, compute_log_det=compute_log_det, inverse=inverse, ) if inverse: input = input - shift return input, input_log_det class ActNormNd(ActNorm): def __init__(self, num_features: int, scale: Union[str, ActNormScaleType] = 'exp', initialized: bool = False, dtype: str = T.float_x(), device: Optional[str] = None, epsilon: float = T.EPSILON): """ Construct a new convolutional :class:`ActNorm` instance. Args: num_features: The size of the feature axis. scale: One of {"exp", "linear"}. If "exp", ``y = (x + bias) * tf.exp(log_scale)``. If "linear", ``y = (x + bias) * scale``. Defaults to "exp". initialized: Whether or not the variables have been initialized? Defaults to :obj:`False`, where the first input `x` in the forward pass will be used to initialize the variables. dtype: Dtype of the parameters. device: The device where to place new tensors and variables. epsilon: The infinitesimal constant to avoid dividing by zero or taking logarithm of zero. """ spatial_ndims = self._get_spatial_ndims() feature_axis = -1 if T.IS_CHANNEL_LAST else -(spatial_ndims + 1) super().__init__( num_features=num_features, axis=feature_axis, event_ndims=spatial_ndims + 1, scale=scale, initialized=initialized, dtype=dtype, device=device, epsilon=epsilon, ) def _get_spatial_ndims(self) -> int: raise NotImplementedError() class ActNorm1d(ActNormNd): """1D convolutional ActNorm flow.""" def _get_spatial_ndims(self) -> int: return 1 class ActNorm2d(ActNormNd): """2D convolutional ActNorm flow.""" def _get_spatial_ndims(self) -> int: return 2 class ActNorm3d(ActNormNd): """3D convolutional ActNorm flow.""" def _get_spatial_ndims(self) -> int: return 3
<filename>tensorkit/flows/act_norm.py from functools import partial from typing import * from .. import init, tensor as T from ..tensor import (Tensor, Module, reshape, shape, int_range, calculate_mean_and_var, assert_finite, float_scalar_like, maximum, log, sqrt) from ..layers import * from ..typing_ import * from .core import * __all__ = [ 'ActNorm', 'ActNorm1d', 'ActNorm2d', 'ActNorm3d', ] class ActNorm(FeatureMappingFlow): """ ActNorm proposed by (Kingma & Dhariwal, 2018). `y = (x + bias) * scale; log_det = y / scale - bias` `bias` and `scale` are initialized such that `y` will have zero mean and unit variance for the initial mini-batch of `x`. It can be initialized only through the forward pass. You may need to use :meth:`BaseFlow.invert()` to get a inverted flow if you need to initialize the parameters via the opposite direction. """ __constants__ = FeatureMappingFlow.__constants__ + ( 'num_features', 'scale_type', 'epsilon', ) num_features: int scale: Module scale_type: str epsilon: float initialized: bool def __init__(self, num_features: int, axis: int = -1, event_ndims: int = 1, scale: Union[str, ActNormScaleType] = 'exp', initialized: bool = False, dtype: str = T.float_x(), device: Optional[str] = None, epsilon: float = T.EPSILON): """ Construct a new :class:`ActNorm` instance. Args: num_features: The size of the feature axis. scale: One of {"exp", "linear"}. If "exp", ``y = (x + bias) * tf.exp(log_scale)``. If "linear", ``y = (x + bias) * scale``. Defaults to "exp". axis: The axis to apply ActNorm. Dimensions not in `axis` will be averaged out when computing the mean of activations. Default `-1`, the last dimension. All items of the `axis` should be covered by `event_ndims`. event_ndims: Number of value dimensions in both `x` and `y`. `x.ndims - event_ndims == log_det.ndims` and `y.ndims - event_ndims == log_det.ndims`. initialized: Whether or not the variables have been initialized? Defaults to :obj:`False`, where the first input `x` in the forward pass will be used to initialize the variables. dtype: Dtype of the parameters. device: The device where to place new tensors and variables. epsilon: The infinitesimal constant to avoid dividing by zero or taking logarithm of zero. """ # validate the arguments scale_type = ActNormScaleType(scale) epsilon = float(epsilon) if scale_type == ActNormScaleType.EXP: scale = ExpScale() pre_scale_init = partial(init.fill, fill_value=0.) elif scale_type == ActNormScaleType.LINEAR: scale = LinearScale(epsilon=epsilon) pre_scale_init = partial(init.fill, fill_value=1.) else: # pragma: no cover raise ValueError(f'Unsupported `scale_type`: {scale_type}') device = device or T.current_device() # construct the layer super().__init__(axis=axis, event_ndims=event_ndims, explicitly_invertible=True) self.num_features = num_features self.scale = scale self.scale_type = scale_type.value self.epsilon = epsilon self.initialized = initialized add_parameter( self, 'pre_scale', T.variable([num_features], dtype=dtype, initializer=pre_scale_init, device=device), ) add_parameter( self, 'bias', T.variable([num_features], dtype=dtype, initializer=init.zeros, device=device), ) @T.jit_method def set_initialized(self, initialized: bool = True) -> None: self.initialized = initialized @T.jit_method def calculate_bias_and_pre_scale_for_init(self, input: Tensor) -> Tuple[Tensor, Tensor]: # PyTorch 1.3.1 bug: cannot mark this method as returning `None`. input_rank = T.rank(input) if not isinstance(input, Tensor) or input_rank < self.x_event_ndims + 1: raise ValueError( '`input` is required to be a tensor with at least {} dimensions: ' 'got input shape {}.'. format(self.x_event_ndims, shape(input)) ) # calculate the axis to reduce feature_axis = input_rank + self.axis reduce_axis = ( int_range(0, feature_axis) + int_range(feature_axis + 1, input_rank) ) # calculate sample mean and variance input_mean, input_var = calculate_mean_and_var( input, axis=reduce_axis, unbiased=True) input_var = assert_finite(input_var, 'input_var') # calculate the initial_value for `bias` bias = -input_mean # calculate the initial value for `pre_scale` epsilon = float_scalar_like(self.epsilon, input_var) if self.scale_type == 'exp': pre_scale = -0.5 * log(maximum(input_var, epsilon)) else: pre_scale = 1. / sqrt(maximum(input_var, epsilon)) return bias, pre_scale @T.jit_ignore def _initialize_act_norm(self, input: Tensor) -> bool: bias, pre_scale = self.calculate_bias_and_pre_scale_for_init(input) with T.no_grad(): T.assign(self.bias, bias) T.assign(self.pre_scale, pre_scale) self.set_initialized(True) return False @T.jit_method def _transform(self, input: Tensor, input_log_det: Optional[Tensor], inverse: bool, compute_log_det: bool ) -> Tuple[Tensor, Optional[Tensor]]: # initialize the parameters if not self.initialized: if inverse: raise RuntimeError( '`ActNorm` must be initialized with `inverse = False`.') # self.initialize_with_input(input) self._initialize_act_norm(input) self.set_initialized(True) # do transformation shape_aligned = [self.num_features] + [1] * (-self.axis - 1) shift = reshape(self.bias, shape_aligned) pre_scale = reshape(self.pre_scale, shape_aligned) input = input if inverse else input + shift event_ndims = self.x_event_ndims input, input_log_det = self.scale( input=input, pre_scale=pre_scale, event_ndims=event_ndims, input_log_det=input_log_det, compute_log_det=compute_log_det, inverse=inverse, ) if inverse: input = input - shift return input, input_log_det class ActNormNd(ActNorm): def __init__(self, num_features: int, scale: Union[str, ActNormScaleType] = 'exp', initialized: bool = False, dtype: str = T.float_x(), device: Optional[str] = None, epsilon: float = T.EPSILON): """ Construct a new convolutional :class:`ActNorm` instance. Args: num_features: The size of the feature axis. scale: One of {"exp", "linear"}. If "exp", ``y = (x + bias) * tf.exp(log_scale)``. If "linear", ``y = (x + bias) * scale``. Defaults to "exp". initialized: Whether or not the variables have been initialized? Defaults to :obj:`False`, where the first input `x` in the forward pass will be used to initialize the variables. dtype: Dtype of the parameters. device: The device where to place new tensors and variables. epsilon: The infinitesimal constant to avoid dividing by zero or taking logarithm of zero. """ spatial_ndims = self._get_spatial_ndims() feature_axis = -1 if T.IS_CHANNEL_LAST else -(spatial_ndims + 1) super().__init__( num_features=num_features, axis=feature_axis, event_ndims=spatial_ndims + 1, scale=scale, initialized=initialized, dtype=dtype, device=device, epsilon=epsilon, ) def _get_spatial_ndims(self) -> int: raise NotImplementedError() class ActNorm1d(ActNormNd): """1D convolutional ActNorm flow.""" def _get_spatial_ndims(self) -> int: return 1 class ActNorm2d(ActNormNd): """2D convolutional ActNorm flow.""" def _get_spatial_ndims(self) -> int: return 2 class ActNorm3d(ActNormNd): """3D convolutional ActNorm flow.""" def _get_spatial_ndims(self) -> int: return 3
en
0.668807
ActNorm proposed by (Kingma & Dhariwal, 2018). `y = (x + bias) * scale; log_det = y / scale - bias` `bias` and `scale` are initialized such that `y` will have zero mean and unit variance for the initial mini-batch of `x`. It can be initialized only through the forward pass. You may need to use :meth:`BaseFlow.invert()` to get a inverted flow if you need to initialize the parameters via the opposite direction. Construct a new :class:`ActNorm` instance. Args: num_features: The size of the feature axis. scale: One of {"exp", "linear"}. If "exp", ``y = (x + bias) * tf.exp(log_scale)``. If "linear", ``y = (x + bias) * scale``. Defaults to "exp". axis: The axis to apply ActNorm. Dimensions not in `axis` will be averaged out when computing the mean of activations. Default `-1`, the last dimension. All items of the `axis` should be covered by `event_ndims`. event_ndims: Number of value dimensions in both `x` and `y`. `x.ndims - event_ndims == log_det.ndims` and `y.ndims - event_ndims == log_det.ndims`. initialized: Whether or not the variables have been initialized? Defaults to :obj:`False`, where the first input `x` in the forward pass will be used to initialize the variables. dtype: Dtype of the parameters. device: The device where to place new tensors and variables. epsilon: The infinitesimal constant to avoid dividing by zero or taking logarithm of zero. # validate the arguments # pragma: no cover # construct the layer # PyTorch 1.3.1 bug: cannot mark this method as returning `None`. # calculate the axis to reduce # calculate sample mean and variance # calculate the initial_value for `bias` # calculate the initial value for `pre_scale` # initialize the parameters # self.initialize_with_input(input) # do transformation Construct a new convolutional :class:`ActNorm` instance. Args: num_features: The size of the feature axis. scale: One of {"exp", "linear"}. If "exp", ``y = (x + bias) * tf.exp(log_scale)``. If "linear", ``y = (x + bias) * scale``. Defaults to "exp". initialized: Whether or not the variables have been initialized? Defaults to :obj:`False`, where the first input `x` in the forward pass will be used to initialize the variables. dtype: Dtype of the parameters. device: The device where to place new tensors and variables. epsilon: The infinitesimal constant to avoid dividing by zero or taking logarithm of zero. 1D convolutional ActNorm flow. 2D convolutional ActNorm flow. 3D convolutional ActNorm flow.
2.772462
3
edb/tools/test/__init__.py
rongfengliang/edgedb-pg-expose
0
6612735
<filename>edb/tools/test/__init__.py<gh_stars>0 # # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import multiprocessing import os import platform import sys import unittest import click from edb.tools import edbcommands from .decorators import not_implemented from .decorators import xfail from .decorators import skip from . import loader from . import runner from . import styles __all__ = ('not_implemented', 'xfail', 'skip') @edbcommands.command() @click.argument('files', nargs=-1, metavar='[file or directory]...') @click.option('-v', '--verbose', is_flag=True, help='increase verbosity') @click.option('-q', '--quiet', is_flag=True, help='decrease verbosity') @click.option('--output-format', type=click.Choice(runner.OutputFormat.__members__), help='test progress output style', default=runner.OutputFormat.auto.value) @click.option('--warnings/--no-warnings', help='enable or disable warnings (enabled by default)', default=True) @click.option('-j', '--jobs', type=int, default=lambda: os.cpu_count() // 2, help='number of parallel processes to use') @click.option('-k', '--include', type=str, multiple=True, metavar='REGEXP', help='only run tests which match the given regular expression') @click.option('-e', '--exclude', type=str, multiple=True, metavar='REGEXP', help='do not run tests which match the given regular expression') @click.option('-x', '--failfast', is_flag=True, help='stop tests after a first failure/error') @click.option('--cov', type=str, multiple=True, help='file path or package name to measure code coverage for') def test(*, files, jobs, include, exclude, verbose, quiet, output_format, warnings, failfast, cov): """Run EdgeDB test suite. Discovers and runs tests in the specified files or directories. If no files or directories are specified, current directory is assumed. """ if quiet: if verbose: click.secho( 'Warning: both --quiet and --verbose are ' 'specified, assuming --quiet.', fg='yellow') verbosity = 0 elif verbose: verbosity = 2 else: verbosity = 1 if platform.system().lower() == 'darwin': # A "fork" without "exec" is broken on macOS since 10.14: # https://www.wefearchange.org/2018/11/forkmacos.rst.html multiprocessing.set_start_method('spawn') output_format = runner.OutputFormat(output_format) if verbosity > 1 and output_format is runner.OutputFormat.stacked: click.secho( 'Error: cannot use stacked output format in verbose mode.', fg='red') sys.exit(1) if not files: cwd = os.path.abspath(os.getcwd()) if os.path.exists(os.path.join(cwd, 'tests')): files = ('tests',) else: click.secho( 'Error: no test path specified and no "tests" directory found', fg='red') sys.exit(1) for file in files: if not os.path.exists(file): click.secho( f'Error: test path {file!r} does not exist', fg='red') sys.exit(1) suite = unittest.TestSuite() total = 0 total_unfiltered = 0 if verbosity > 0: def _update_progress(n, unfiltered_n): nonlocal total, total_unfiltered total += n total_unfiltered += unfiltered_n click.echo(styles.status( f'Collected {total}/{total_unfiltered} tests.\r'), nl=False) else: _update_progress = None test_loader = loader.TestLoader( verbosity=verbosity, exclude=exclude, include=include, progress_cb=_update_progress) for file in files: if not os.path.exists(file) and verbosity > 0: click.echo(styles.warning( f'Warning: {file}: no such file or directory.')) if os.path.isdir(file): tests = test_loader.discover(file) else: tests = test_loader.discover( os.path.dirname(file), pattern=os.path.basename(file)) suite.addTest(tests) jobs = max(min(total, jobs), 1) if verbosity > 0: click.echo() click.echo(styles.status( f'Using up to {jobs} processes to run tests.')) if cov: try: import coverage # NoQA except ImportError: click.secho( 'Error: "coverage" package is missing, cannot run tests ' 'with --cov') sys.exit(1) test_runner = runner.ParallelTextTestRunner( verbosity=verbosity, output_format=output_format, warnings=warnings, num_workers=jobs, failfast=failfast, coverage=cov) result = test_runner.run(suite) sys.exit(0 if result.wasSuccessful() else 1)
<filename>edb/tools/test/__init__.py<gh_stars>0 # # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import multiprocessing import os import platform import sys import unittest import click from edb.tools import edbcommands from .decorators import not_implemented from .decorators import xfail from .decorators import skip from . import loader from . import runner from . import styles __all__ = ('not_implemented', 'xfail', 'skip') @edbcommands.command() @click.argument('files', nargs=-1, metavar='[file or directory]...') @click.option('-v', '--verbose', is_flag=True, help='increase verbosity') @click.option('-q', '--quiet', is_flag=True, help='decrease verbosity') @click.option('--output-format', type=click.Choice(runner.OutputFormat.__members__), help='test progress output style', default=runner.OutputFormat.auto.value) @click.option('--warnings/--no-warnings', help='enable or disable warnings (enabled by default)', default=True) @click.option('-j', '--jobs', type=int, default=lambda: os.cpu_count() // 2, help='number of parallel processes to use') @click.option('-k', '--include', type=str, multiple=True, metavar='REGEXP', help='only run tests which match the given regular expression') @click.option('-e', '--exclude', type=str, multiple=True, metavar='REGEXP', help='do not run tests which match the given regular expression') @click.option('-x', '--failfast', is_flag=True, help='stop tests after a first failure/error') @click.option('--cov', type=str, multiple=True, help='file path or package name to measure code coverage for') def test(*, files, jobs, include, exclude, verbose, quiet, output_format, warnings, failfast, cov): """Run EdgeDB test suite. Discovers and runs tests in the specified files or directories. If no files or directories are specified, current directory is assumed. """ if quiet: if verbose: click.secho( 'Warning: both --quiet and --verbose are ' 'specified, assuming --quiet.', fg='yellow') verbosity = 0 elif verbose: verbosity = 2 else: verbosity = 1 if platform.system().lower() == 'darwin': # A "fork" without "exec" is broken on macOS since 10.14: # https://www.wefearchange.org/2018/11/forkmacos.rst.html multiprocessing.set_start_method('spawn') output_format = runner.OutputFormat(output_format) if verbosity > 1 and output_format is runner.OutputFormat.stacked: click.secho( 'Error: cannot use stacked output format in verbose mode.', fg='red') sys.exit(1) if not files: cwd = os.path.abspath(os.getcwd()) if os.path.exists(os.path.join(cwd, 'tests')): files = ('tests',) else: click.secho( 'Error: no test path specified and no "tests" directory found', fg='red') sys.exit(1) for file in files: if not os.path.exists(file): click.secho( f'Error: test path {file!r} does not exist', fg='red') sys.exit(1) suite = unittest.TestSuite() total = 0 total_unfiltered = 0 if verbosity > 0: def _update_progress(n, unfiltered_n): nonlocal total, total_unfiltered total += n total_unfiltered += unfiltered_n click.echo(styles.status( f'Collected {total}/{total_unfiltered} tests.\r'), nl=False) else: _update_progress = None test_loader = loader.TestLoader( verbosity=verbosity, exclude=exclude, include=include, progress_cb=_update_progress) for file in files: if not os.path.exists(file) and verbosity > 0: click.echo(styles.warning( f'Warning: {file}: no such file or directory.')) if os.path.isdir(file): tests = test_loader.discover(file) else: tests = test_loader.discover( os.path.dirname(file), pattern=os.path.basename(file)) suite.addTest(tests) jobs = max(min(total, jobs), 1) if verbosity > 0: click.echo() click.echo(styles.status( f'Using up to {jobs} processes to run tests.')) if cov: try: import coverage # NoQA except ImportError: click.secho( 'Error: "coverage" package is missing, cannot run tests ' 'with --cov') sys.exit(1) test_runner = runner.ParallelTextTestRunner( verbosity=verbosity, output_format=output_format, warnings=warnings, num_workers=jobs, failfast=failfast, coverage=cov) result = test_runner.run(suite) sys.exit(0 if result.wasSuccessful() else 1)
en
0.82691
# # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Run EdgeDB test suite. Discovers and runs tests in the specified files or directories. If no files or directories are specified, current directory is assumed. # A "fork" without "exec" is broken on macOS since 10.14: # https://www.wefearchange.org/2018/11/forkmacos.rst.html # NoQA
1.936163
2
tests/broker/test_add_address.py
ned21/aquilon
7
6612736
#!/usr/bin/env python # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008-2013,2015-2019 Contributor # # 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. """Module for testing the add address command.""" import unittest if __name__ == "__main__": from broker import utils utils.import_depends() from ipaddress import IPv6Address, ip_address from broker.brokertest import TestBrokerCommand from eventstest import EventsTestMixin from dnstest import inaddr_ptr, in6addr_ptr class TestAddAddress(EventsTestMixin, TestBrokerCommand): def event_add_arecord(self, fqdn, ip, reverse=None, ttl=None, dns_environment='internal', network_environment='internal', reverse_dns_environment=None): # Determine the IP type ip = ip_address(unicode(ip)) if isinstance(ip, IPv6Address): inaddr = in6addr_ptr rrtype = 'AAAA' else: inaddr = inaddr_ptr rrtype = 'A' # Prepare the records a_record = { 'target': str(ip), 'targetNetworkEnvironmentName': network_environment, 'rrtype': rrtype, } ptr_record = { 'target': ( fqdn if reverse is None else reverse ), 'targetEnvironmentName': dns_environment, 'rrtype': 'PTR', } if ttl is not None: a_record['ttl'] = ttl ptr_record['ttl'] = ttl # Add the records in the expected events self.event_add_dns( fqdn=[ fqdn, inaddr(ip), ], dns_environment=[ dns_environment, reverse_dns_environment or network_environment, ], dns_records=[ [a_record, ], [ptr_record, ], ], ) def test_100_basic(self): self.event_add_arecord( fqdn='arecord13.aqd-unittest.ms.com', ip=str(self.net['unknown0'].usable[13]), dns_environment='internal', ) self.dsdb_expect_add("arecord13.aqd-unittest.ms.com", self.net["unknown0"].usable[13]) command = ["add_address", "--ip=%s" % self.net["unknown0"].usable[13], "--fqdn=arecord13.aqd-unittest.ms.com"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "Please provide a GRN/EON_ID!", command) def test_101_basic_grn(self): self.event_add_arecord( fqdn='arecord13.aqd-unittest.ms.com', ip=str(self.net['unknown0'].usable[13]), dns_environment='internal', ) self.dsdb_expect_add("arecord13.aqd-unittest.ms.com", self.net["unknown0"].usable[13]) command = ["add_address", "--ip=%s" % self.net["unknown0"].usable[13], "--fqdn=arecord13.aqd-unittest.ms.com", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify() self.events_verify() def test_105_verifybasic(self): net = self.net["unknown0"] command = ["show_address", "--fqdn=arecord13.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: arecord13.aqd-unittest.ms.com", command) self.matchoutput(out, "IP: %s" % net.usable[13], command) self.matchoutput(out, "Network: %s [%s]" % (net.name, net), command) self.matchoutput(out, "Network Environment: internal", command) self.matchclean(out, "Reverse", command) self.matchclean(out, "TTL", command) def test_110_basic_ipv6(self): self.event_add_arecord( fqdn='ipv6test.aqd-unittest.ms.com', ip=str(self.net['ipv6_test'].usable[1]), dns_environment='internal', ) command = ["add_address", "--ip", self.net["ipv6_test"].usable[1], "--fqdn", "ipv6test.aqd-unittest.ms.com", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify(empty=True) self.events_verify() def test_115_verify_basic_ipv6(self): net = self.net["ipv6_test"] command = ["show_address", "--fqdn=ipv6test.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "IP: %s" % net.usable[1], command) self.matchoutput(out, "Network: %s [%s]" % (net.name, net), command) def test_200_add_defaultenv(self): default = self.config.get("site", "default_dns_environment") self.event_add_arecord( fqdn='arecord14.aqd-unittest.ms.com', ip=str(self.net['unknown0'].usable[14]), reverse='arecord13.aqd-unittest.ms.com', dns_environment=default, ) self.dsdb_expect_add("arecord14.aqd-unittest.ms.com", self.net["unknown0"].usable[14]) command = ["add_address", "--ip=%s" % self.net["unknown0"].usable[14], "--fqdn=arecord14.aqd-unittest.ms.com", "--reverse_ptr=arecord13.aqd-unittest.ms.com", "--dns_environment=%s" % default, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify() self.events_verify() def test_210_add_utenv_noreverse(self): # The reverse does not exist in this environment command = ["add_address", "--ip", self.net["unknown1"].usable[14], "--fqdn", "arecord14.aqd-unittest.ms.com", "--reverse_ptr", "arecord13.aqd-unittest.ms.com", "--dns_environment", "ut-env", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.notfoundtest(command) self.matchoutput(out, "Target FQDN arecord13.aqd-unittest.ms.com does " "not exist in DNS environment ut-env.", command) def test_220_add_utenv(self): self.event_add_arecord( fqdn='arecord14.aqd-unittest.ms.com', ip=str(self.net['unknown1'].usable[14]), dns_environment='ut-env', ) # Different IP in this environment command = ["add_address", "--ip", self.net["unknown1"].usable[14], "--fqdn", "arecord14.aqd-unittest.ms.com", "--dns_environment", "ut-env", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.events_verify() def test_230_verifydefaultenv(self): default = self.config.get("site", "default_dns_environment") command = ["show_address", "--fqdn=arecord14.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: arecord14.aqd-unittest.ms.com", command) self.matchoutput(out, "DNS Environment: %s" % default, command) self.matchoutput(out, "IP: %s" % self.net["unknown0"].usable[14], command) self.matchoutput(out, "Reverse PTR: arecord13.aqd-unittest.ms.com", command) def test_230_verifyutenv(self): command = ["show_address", "--fqdn=arecord14.aqd-unittest.ms.com", "--dns_environment", "ut-env"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: arecord14.aqd-unittest.ms.com", command) self.matchoutput(out, "DNS Environment: ut-env", command) self.matchoutput(out, "IP: %s" % self.net["unknown1"].usable[14], command) self.matchclean(out, "Reverse", command) def test_300_ipfromip(self): self.event_add_arecord( fqdn='arecord15.aqd-unittest.ms.com', ip=str(self.net['unknown0'].usable[15]), dns_environment='internal', ) self.dsdb_expect_add("arecord15.aqd-unittest.ms.com", self.net["unknown0"].usable[15]) command = ["add_address", "--ipalgorithm=max", "--ipfromip=%s" % self.net["unknown0"].ip, "--fqdn=arecord15.aqd-unittest.ms.com", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify() self.events_verify() def test_310_verifyipfromip(self): command = ["show_address", "--fqdn=arecord15.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: arecord15.aqd-unittest.ms.com", command) self.matchoutput(out, "IP: %s" % self.net["unknown0"].usable[15], command) self.matchclean(out, "Reverse", command) def test_320_verifyaudit(self): command = ["search_audit", "--command", "add_address", "--keyword", "arecord15.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "[Result: ip=%s]" % self.net["unknown0"].usable[15], command) def test_330_add_name_with_digit_prefix(self): fqdn = "1record42.aqd-unittest.ms.com" ip = self.net["unknown0"].usable[42] dns_env = "external" self.event_add_arecord( fqdn=fqdn, ip=str(ip), dns_environment=dns_env, ) command = ["add_address", "--ip", ip, "--fqdn", fqdn, "--dns_environment", dns_env, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) command = ["show_address", "--fqdn", fqdn, "--dns_environment", dns_env] out = self.commandtest(command) self.matchoutput(out, "DNS Record: %s" % fqdn, command) self.matchoutput(out, "IP: %s" % ip, command) self.matchclean(out, "Reverse", command) self.events_verify() def test_400_dsdbfailure(self): self.dsdb_expect_add("arecord16.aqd-unittest.ms.com", self.net["unknown0"].usable[16], fail=True) command = ["add_address", "--ip", self.net["unknown0"].usable[16], "--fqdn", "arecord16.aqd-unittest.ms.com", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "Could not add address to DSDB", command) self.dsdb_verify() def test_410_verifydsdbfailure(self): command = ["search", "dns", "--fqdn", "arecord16.aqd-unittest.ms.com"] self.notfoundtest(command) def test_420_failnetaddress(self): ip = self.net["unknown0"].ip command = ["add", "address", "--fqdn", "netaddress.aqd-unittest.ms.com", "--ip", ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "IP address %s is the address of network " % ip, command) def test_420_failnetaddressv6(self): ip = self.net["ipv6_test"].network_address command = ["add_address", "--fqdn", "netaddress6.aqd-unittest.ms.com", "--ip", ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "IP address %s is the address of network " % ip, command) def test_425_failbroadcast(self): ip = self.net["unknown0"].broadcast_address command = ["add", "address", "--fqdn", "broadcast.aqd-unittest.ms.com", "--ip", ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "IP address %s is the broadcast address of " "network " % ip, command) def test_425_failbroadcastv6(self): ip = self.net["ipv6_test"].broadcast_address command = ["add", "address", "--fqdn", "broadcast.aqd-unittest.ms.com", "--ip", ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "IP address %s is the broadcast address of " "network " % ip, command) def test_426_failv6mapped(self): ipv4 = self.net["unknown0"].ip ipv6 = IPv6Address(u"::ffff:%s" % ipv4) command = ["add", "address", "--fqdn", "broadcast.aqd-unittest.ms.com", "--ip", ipv6, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "IPv6-mapped IPv4 addresses are not supported.", command) def test_440_failbadenv(self): ip = self.net["unknown0"].usable[16] command = ["add", "address", "--fqdn", "no-such-env.aqd-unittest.ms.com", "--ip", ip, "--dns_environment", "no-such-env", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.notfoundtest(command) self.matchoutput(out, "DNS Environment no-such-env not found.", command) def test_450_add_too_long_name(self): ip = self.net["unknown0"].usable[16] cmd = ['add', 'address', '--fqdn', # 1 2 3 4 5 6 's234567890123456789012345678901234567890123456789012345678901234' + '.aqd-unittest.ms.com', '--dns_environment', 'internal', '--ip', ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(cmd) self.matchoutput(out, "is more than the maximum 63 allowed.", cmd) def test_455_add_invalid_name(self): ip = self.net["unknown0"].usable[16] command = ['add', 'address', '--fqdn', 'foo-.aqd-unittest.ms.com', '--dns_environment', 'internal', '--ip', ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "Illegal DNS name format 'foo-'.", command) def test_460_restricted_domain(self): ip = self.net["unknown0"].usable[-1] command = ["add", "address", "--fqdn", "foo.restrict.aqd-unittest.ms.com", "--ip", ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "DNS Domain restrict.aqd-unittest.ms.com is " "restricted, adding extra addresses is not allowed.", command) def test_470_restricted_reverse(self): ip = self.net["unknown0"].usable[32] self.event_add_arecord( fqdn='arecord17.aqd-unittest.ms.com', ip=str(ip), reverse='reverse.restrict.aqd-unittest.ms.com', dns_environment='internal', ) self.dsdb_expect_add("arecord17.aqd-unittest.ms.com", ip) command = ["add", "address", "--fqdn", "arecord17.aqd-unittest.ms.com", "--reverse_ptr", "reverse.restrict.aqd-unittest.ms.com", "--ip", ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm err = self.statustest(command) self.matchoutput(err, "WARNING: Will create a reference to " "reverse.restrict.aqd-unittest.ms.com, but trying to " "resolve it resulted in an error: Name or service " "not known", command) self.dsdb_verify() self.events_verify() def test_471_verify_reverse(self): command = ["search", "dns", "--fullinfo", "--fqdn", "reverse.restrict.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "Reserved Name: reverse.restrict.aqd-unittest.ms.com", command) command = ["show", "address", "--fqdn", "arecord17.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "Reverse PTR: reverse.restrict.aqd-unittest.ms.com", command) def test_500_addunittest20eth1(self): ip = self.net["zebra_eth1"].usable[0] fqdn = "unittest20-e1.aqd-unittest.ms.com" self.event_add_arecord( fqdn=fqdn, ip=str(ip), dns_environment='internal', ) self.dsdb_expect_add(fqdn, ip) command = ["add", "address", "--ip", ip, "--fqdn", fqdn, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify() self.events_verify() def test_600_addip_with_network_env(self): ip = "192.168.3.1" fqdn = "cardenvtest600.aqd-unittest.ms.com" self.event_add_arecord( fqdn=fqdn, ip=str(ip), dns_environment='ut-env', network_environment='cardenv', reverse_dns_environment='ut-env', ) command = ["add", "address", "--ip", ip, "--fqdn", fqdn, "--network_environment", "cardenv", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) # External IP addresses should not be added to DSDB self.dsdb_verify(empty=True) command = ["show_address", "--fqdn=%s" % fqdn, "--network_environment", "cardenv"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: %s" % fqdn, command) self.matchoutput(out, "IP: %s" % ip, command) self.matchoutput(out, "DNS Environment: ut-env", command) self.matchoutput(out, "Network Environment: cardenv", command) self.events_verify() def test_610_addipfromip_with_network_env(self): fqdn = "cardenvtest610.aqd-unittest.ms.com" self.event_add_arecord( fqdn=fqdn, ip='192.168.3.5', dns_environment='ut-env', network_environment='cardenv', reverse_dns_environment='ut-env', ) command = ["add", "address", "--ipfromip", "192.168.3.0", "--fqdn", fqdn, "--network_environment", "cardenv", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) # External IP addresses should not be added to DSDB self.dsdb_verify(empty=True) command = ["show_address", "--fqdn=%s" % fqdn, "--network_environment", "cardenv"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: %s" % fqdn, command) self.matchoutput(out, "IP: %s" % "192.168.3.5", command) self.matchoutput(out, "DNS Environment: ut-env", command) self.matchoutput(out, "Network Environment: cardenv", command) self.events_verify() def test_620_addexternalip_in_interanldns(self): ip = "192.168.3.4" fqdn = "cardenvtest620.aqd-unittest.ms.com" default = self.config.get("site", "default_dns_environment") command = ["add", "address", "--ip", ip, "--fqdn", fqdn, "--dns_environment", default, "--network_environment", "cardenv", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "Entering external IP addresses to the internal DNS environment is not allowed", command) def test_700_ttl(self): self.event_add_arecord( fqdn='arecord40.aqd-unittest.ms.com', ip=str(self.net['unknown0'].usable[40]), ttl=300, dns_environment='internal', ) self.dsdb_expect_add("arecord40.aqd-unittest.ms.com", self.net["unknown0"].usable[40]) command = ["add_address", "--ip=%s" % self.net["unknown0"].usable[40], "--fqdn=arecord40.aqd-unittest.ms.com", "--ttl", 300, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify() self.events_verify() def test_720_verifyttl(self): net = self.net["unknown0"] command = ["show_address", "--fqdn=arecord40.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: arecord40.aqd-unittest.ms.com", command) self.matchoutput(out, "IP: %s" % net.usable[40], command) self.matchoutput(out, "Network: %s [%s]" % (net.name, net), command) self.matchoutput(out, "Network Environment: internal", command) self.matchoutput(out, "TTL: 300", command) self.matchclean(out, "Reverse", command) def test_730_badttl(self): command = ["add_address", "--ip=%s" % self.net["unknown0"].usable[41], "--fqdn=arecord41.aqd-unittest.ms.com", "--ttl", 2147483648, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "TTL must be between 0 and 2147483647.", command) def test_800_grn(self): self.event_add_arecord( fqdn='arecord50.aqd-unittest.ms.com', ip=str(self.net['unknown0'].usable[50]), dns_environment='internal', ) self.dsdb_expect_add("arecord50.aqd-unittest.ms.com", self.net["unknown0"].usable[50]) command = ["add_address", "--ip=%s" % self.net["unknown0"].usable[50], "--fqdn=arecord50.aqd-unittest.ms.com", "--grn", "grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify() self.events_verify() def test_820_verifygrn(self): net = self.net["unknown0"] command = ["show_address", "--fqdn=arecord50.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: arecord50.aqd-unittest.ms.com", command) self.matchoutput(out, "IP: %s" % net.usable[50], command) self.matchoutput(out, "Network: %s [%s]" % (net.name, net), command) self.matchoutput(out, "Network Environment: internal", command) self.matchoutput(out, "Owned by GRN: grn:/ms/ei/aquilon/aqd", command) self.matchclean(out, "Reverse", command) def test_830_eon_id(self): self.event_add_arecord( fqdn='arecord51.aqd-unittest.ms.com', ip=str(self.net['unknown0'].usable[51]), dns_environment='internal', ) self.dsdb_expect_add("arecord51.aqd-unittest.ms.com", self.net["unknown0"].usable[51]) command = ["add_address", "--ip=%s" % self.net["unknown0"].usable[51], "--fqdn=arecord51.aqd-unittest.ms.com", "--eon_id", "3"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify() self.events_verify() def test_840_verifygrn(self): net = self.net["unknown0"] command = ["show_address", "--fqdn=arecord51.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: arecord51.aqd-unittest.ms.com", command) self.matchoutput(out, "IP: %s" % net.usable[51], command) self.matchoutput(out, "Network: %s [%s]" % (net.name, net), command) self.matchoutput(out, "Network Environment: internal", command) self.matchoutput(out, "Owned by GRN: grn:/ms/ei/aquilon/unittest", command) self.matchclean(out, "Reverse", command) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestAddAddress) unittest.TextTestRunner(verbosity=2).run(suite)
#!/usr/bin/env python # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008-2013,2015-2019 Contributor # # 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. """Module for testing the add address command.""" import unittest if __name__ == "__main__": from broker import utils utils.import_depends() from ipaddress import IPv6Address, ip_address from broker.brokertest import TestBrokerCommand from eventstest import EventsTestMixin from dnstest import inaddr_ptr, in6addr_ptr class TestAddAddress(EventsTestMixin, TestBrokerCommand): def event_add_arecord(self, fqdn, ip, reverse=None, ttl=None, dns_environment='internal', network_environment='internal', reverse_dns_environment=None): # Determine the IP type ip = ip_address(unicode(ip)) if isinstance(ip, IPv6Address): inaddr = in6addr_ptr rrtype = 'AAAA' else: inaddr = inaddr_ptr rrtype = 'A' # Prepare the records a_record = { 'target': str(ip), 'targetNetworkEnvironmentName': network_environment, 'rrtype': rrtype, } ptr_record = { 'target': ( fqdn if reverse is None else reverse ), 'targetEnvironmentName': dns_environment, 'rrtype': 'PTR', } if ttl is not None: a_record['ttl'] = ttl ptr_record['ttl'] = ttl # Add the records in the expected events self.event_add_dns( fqdn=[ fqdn, inaddr(ip), ], dns_environment=[ dns_environment, reverse_dns_environment or network_environment, ], dns_records=[ [a_record, ], [ptr_record, ], ], ) def test_100_basic(self): self.event_add_arecord( fqdn='arecord13.aqd-unittest.ms.com', ip=str(self.net['unknown0'].usable[13]), dns_environment='internal', ) self.dsdb_expect_add("arecord13.aqd-unittest.ms.com", self.net["unknown0"].usable[13]) command = ["add_address", "--ip=%s" % self.net["unknown0"].usable[13], "--fqdn=arecord13.aqd-unittest.ms.com"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "Please provide a GRN/EON_ID!", command) def test_101_basic_grn(self): self.event_add_arecord( fqdn='arecord13.aqd-unittest.ms.com', ip=str(self.net['unknown0'].usable[13]), dns_environment='internal', ) self.dsdb_expect_add("arecord13.aqd-unittest.ms.com", self.net["unknown0"].usable[13]) command = ["add_address", "--ip=%s" % self.net["unknown0"].usable[13], "--fqdn=arecord13.aqd-unittest.ms.com", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify() self.events_verify() def test_105_verifybasic(self): net = self.net["unknown0"] command = ["show_address", "--fqdn=arecord13.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: arecord13.aqd-unittest.ms.com", command) self.matchoutput(out, "IP: %s" % net.usable[13], command) self.matchoutput(out, "Network: %s [%s]" % (net.name, net), command) self.matchoutput(out, "Network Environment: internal", command) self.matchclean(out, "Reverse", command) self.matchclean(out, "TTL", command) def test_110_basic_ipv6(self): self.event_add_arecord( fqdn='ipv6test.aqd-unittest.ms.com', ip=str(self.net['ipv6_test'].usable[1]), dns_environment='internal', ) command = ["add_address", "--ip", self.net["ipv6_test"].usable[1], "--fqdn", "ipv6test.aqd-unittest.ms.com", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify(empty=True) self.events_verify() def test_115_verify_basic_ipv6(self): net = self.net["ipv6_test"] command = ["show_address", "--fqdn=ipv6test.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "IP: %s" % net.usable[1], command) self.matchoutput(out, "Network: %s [%s]" % (net.name, net), command) def test_200_add_defaultenv(self): default = self.config.get("site", "default_dns_environment") self.event_add_arecord( fqdn='arecord14.aqd-unittest.ms.com', ip=str(self.net['unknown0'].usable[14]), reverse='arecord13.aqd-unittest.ms.com', dns_environment=default, ) self.dsdb_expect_add("arecord14.aqd-unittest.ms.com", self.net["unknown0"].usable[14]) command = ["add_address", "--ip=%s" % self.net["unknown0"].usable[14], "--fqdn=arecord14.aqd-unittest.ms.com", "--reverse_ptr=arecord13.aqd-unittest.ms.com", "--dns_environment=%s" % default, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify() self.events_verify() def test_210_add_utenv_noreverse(self): # The reverse does not exist in this environment command = ["add_address", "--ip", self.net["unknown1"].usable[14], "--fqdn", "arecord14.aqd-unittest.ms.com", "--reverse_ptr", "arecord13.aqd-unittest.ms.com", "--dns_environment", "ut-env", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.notfoundtest(command) self.matchoutput(out, "Target FQDN arecord13.aqd-unittest.ms.com does " "not exist in DNS environment ut-env.", command) def test_220_add_utenv(self): self.event_add_arecord( fqdn='arecord14.aqd-unittest.ms.com', ip=str(self.net['unknown1'].usable[14]), dns_environment='ut-env', ) # Different IP in this environment command = ["add_address", "--ip", self.net["unknown1"].usable[14], "--fqdn", "arecord14.aqd-unittest.ms.com", "--dns_environment", "ut-env", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.events_verify() def test_230_verifydefaultenv(self): default = self.config.get("site", "default_dns_environment") command = ["show_address", "--fqdn=arecord14.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: arecord14.aqd-unittest.ms.com", command) self.matchoutput(out, "DNS Environment: %s" % default, command) self.matchoutput(out, "IP: %s" % self.net["unknown0"].usable[14], command) self.matchoutput(out, "Reverse PTR: arecord13.aqd-unittest.ms.com", command) def test_230_verifyutenv(self): command = ["show_address", "--fqdn=arecord14.aqd-unittest.ms.com", "--dns_environment", "ut-env"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: arecord14.aqd-unittest.ms.com", command) self.matchoutput(out, "DNS Environment: ut-env", command) self.matchoutput(out, "IP: %s" % self.net["unknown1"].usable[14], command) self.matchclean(out, "Reverse", command) def test_300_ipfromip(self): self.event_add_arecord( fqdn='arecord15.aqd-unittest.ms.com', ip=str(self.net['unknown0'].usable[15]), dns_environment='internal', ) self.dsdb_expect_add("arecord15.aqd-unittest.ms.com", self.net["unknown0"].usable[15]) command = ["add_address", "--ipalgorithm=max", "--ipfromip=%s" % self.net["unknown0"].ip, "--fqdn=arecord15.aqd-unittest.ms.com", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify() self.events_verify() def test_310_verifyipfromip(self): command = ["show_address", "--fqdn=arecord15.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: arecord15.aqd-unittest.ms.com", command) self.matchoutput(out, "IP: %s" % self.net["unknown0"].usable[15], command) self.matchclean(out, "Reverse", command) def test_320_verifyaudit(self): command = ["search_audit", "--command", "add_address", "--keyword", "arecord15.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "[Result: ip=%s]" % self.net["unknown0"].usable[15], command) def test_330_add_name_with_digit_prefix(self): fqdn = "1record42.aqd-unittest.ms.com" ip = self.net["unknown0"].usable[42] dns_env = "external" self.event_add_arecord( fqdn=fqdn, ip=str(ip), dns_environment=dns_env, ) command = ["add_address", "--ip", ip, "--fqdn", fqdn, "--dns_environment", dns_env, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) command = ["show_address", "--fqdn", fqdn, "--dns_environment", dns_env] out = self.commandtest(command) self.matchoutput(out, "DNS Record: %s" % fqdn, command) self.matchoutput(out, "IP: %s" % ip, command) self.matchclean(out, "Reverse", command) self.events_verify() def test_400_dsdbfailure(self): self.dsdb_expect_add("arecord16.aqd-unittest.ms.com", self.net["unknown0"].usable[16], fail=True) command = ["add_address", "--ip", self.net["unknown0"].usable[16], "--fqdn", "arecord16.aqd-unittest.ms.com", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "Could not add address to DSDB", command) self.dsdb_verify() def test_410_verifydsdbfailure(self): command = ["search", "dns", "--fqdn", "arecord16.aqd-unittest.ms.com"] self.notfoundtest(command) def test_420_failnetaddress(self): ip = self.net["unknown0"].ip command = ["add", "address", "--fqdn", "netaddress.aqd-unittest.ms.com", "--ip", ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "IP address %s is the address of network " % ip, command) def test_420_failnetaddressv6(self): ip = self.net["ipv6_test"].network_address command = ["add_address", "--fqdn", "netaddress6.aqd-unittest.ms.com", "--ip", ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "IP address %s is the address of network " % ip, command) def test_425_failbroadcast(self): ip = self.net["unknown0"].broadcast_address command = ["add", "address", "--fqdn", "broadcast.aqd-unittest.ms.com", "--ip", ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "IP address %s is the broadcast address of " "network " % ip, command) def test_425_failbroadcastv6(self): ip = self.net["ipv6_test"].broadcast_address command = ["add", "address", "--fqdn", "broadcast.aqd-unittest.ms.com", "--ip", ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "IP address %s is the broadcast address of " "network " % ip, command) def test_426_failv6mapped(self): ipv4 = self.net["unknown0"].ip ipv6 = IPv6Address(u"::ffff:%s" % ipv4) command = ["add", "address", "--fqdn", "broadcast.aqd-unittest.ms.com", "--ip", ipv6, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "IPv6-mapped IPv4 addresses are not supported.", command) def test_440_failbadenv(self): ip = self.net["unknown0"].usable[16] command = ["add", "address", "--fqdn", "no-such-env.aqd-unittest.ms.com", "--ip", ip, "--dns_environment", "no-such-env", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.notfoundtest(command) self.matchoutput(out, "DNS Environment no-such-env not found.", command) def test_450_add_too_long_name(self): ip = self.net["unknown0"].usable[16] cmd = ['add', 'address', '--fqdn', # 1 2 3 4 5 6 's234567890123456789012345678901234567890123456789012345678901234' + '.aqd-unittest.ms.com', '--dns_environment', 'internal', '--ip', ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(cmd) self.matchoutput(out, "is more than the maximum 63 allowed.", cmd) def test_455_add_invalid_name(self): ip = self.net["unknown0"].usable[16] command = ['add', 'address', '--fqdn', 'foo-.aqd-unittest.ms.com', '--dns_environment', 'internal', '--ip', ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "Illegal DNS name format 'foo-'.", command) def test_460_restricted_domain(self): ip = self.net["unknown0"].usable[-1] command = ["add", "address", "--fqdn", "foo.restrict.aqd-unittest.ms.com", "--ip", ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "DNS Domain restrict.aqd-unittest.ms.com is " "restricted, adding extra addresses is not allowed.", command) def test_470_restricted_reverse(self): ip = self.net["unknown0"].usable[32] self.event_add_arecord( fqdn='arecord17.aqd-unittest.ms.com', ip=str(ip), reverse='reverse.restrict.aqd-unittest.ms.com', dns_environment='internal', ) self.dsdb_expect_add("arecord17.aqd-unittest.ms.com", ip) command = ["add", "address", "--fqdn", "arecord17.aqd-unittest.ms.com", "--reverse_ptr", "reverse.restrict.aqd-unittest.ms.com", "--ip", ip, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm err = self.statustest(command) self.matchoutput(err, "WARNING: Will create a reference to " "reverse.restrict.aqd-unittest.ms.com, but trying to " "resolve it resulted in an error: Name or service " "not known", command) self.dsdb_verify() self.events_verify() def test_471_verify_reverse(self): command = ["search", "dns", "--fullinfo", "--fqdn", "reverse.restrict.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "Reserved Name: reverse.restrict.aqd-unittest.ms.com", command) command = ["show", "address", "--fqdn", "arecord17.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "Reverse PTR: reverse.restrict.aqd-unittest.ms.com", command) def test_500_addunittest20eth1(self): ip = self.net["zebra_eth1"].usable[0] fqdn = "unittest20-e1.aqd-unittest.ms.com" self.event_add_arecord( fqdn=fqdn, ip=str(ip), dns_environment='internal', ) self.dsdb_expect_add(fqdn, ip) command = ["add", "address", "--ip", ip, "--fqdn", fqdn, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify() self.events_verify() def test_600_addip_with_network_env(self): ip = "192.168.3.1" fqdn = "cardenvtest600.aqd-unittest.ms.com" self.event_add_arecord( fqdn=fqdn, ip=str(ip), dns_environment='ut-env', network_environment='cardenv', reverse_dns_environment='ut-env', ) command = ["add", "address", "--ip", ip, "--fqdn", fqdn, "--network_environment", "cardenv", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) # External IP addresses should not be added to DSDB self.dsdb_verify(empty=True) command = ["show_address", "--fqdn=%s" % fqdn, "--network_environment", "cardenv"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: %s" % fqdn, command) self.matchoutput(out, "IP: %s" % ip, command) self.matchoutput(out, "DNS Environment: ut-env", command) self.matchoutput(out, "Network Environment: cardenv", command) self.events_verify() def test_610_addipfromip_with_network_env(self): fqdn = "cardenvtest610.aqd-unittest.ms.com" self.event_add_arecord( fqdn=fqdn, ip='192.168.3.5', dns_environment='ut-env', network_environment='cardenv', reverse_dns_environment='ut-env', ) command = ["add", "address", "--ipfromip", "192.168.3.0", "--fqdn", fqdn, "--network_environment", "cardenv", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) # External IP addresses should not be added to DSDB self.dsdb_verify(empty=True) command = ["show_address", "--fqdn=%s" % fqdn, "--network_environment", "cardenv"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: %s" % fqdn, command) self.matchoutput(out, "IP: %s" % "192.168.3.5", command) self.matchoutput(out, "DNS Environment: ut-env", command) self.matchoutput(out, "Network Environment: cardenv", command) self.events_verify() def test_620_addexternalip_in_interanldns(self): ip = "192.168.3.4" fqdn = "cardenvtest620.aqd-unittest.ms.com" default = self.config.get("site", "default_dns_environment") command = ["add", "address", "--ip", ip, "--fqdn", fqdn, "--dns_environment", default, "--network_environment", "cardenv", "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "Entering external IP addresses to the internal DNS environment is not allowed", command) def test_700_ttl(self): self.event_add_arecord( fqdn='arecord40.aqd-unittest.ms.com', ip=str(self.net['unknown0'].usable[40]), ttl=300, dns_environment='internal', ) self.dsdb_expect_add("arecord40.aqd-unittest.ms.com", self.net["unknown0"].usable[40]) command = ["add_address", "--ip=%s" % self.net["unknown0"].usable[40], "--fqdn=arecord40.aqd-unittest.ms.com", "--ttl", 300, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify() self.events_verify() def test_720_verifyttl(self): net = self.net["unknown0"] command = ["show_address", "--fqdn=arecord40.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: arecord40.aqd-unittest.ms.com", command) self.matchoutput(out, "IP: %s" % net.usable[40], command) self.matchoutput(out, "Network: %s [%s]" % (net.name, net), command) self.matchoutput(out, "Network Environment: internal", command) self.matchoutput(out, "TTL: 300", command) self.matchclean(out, "Reverse", command) def test_730_badttl(self): command = ["add_address", "--ip=%s" % self.net["unknown0"].usable[41], "--fqdn=arecord41.aqd-unittest.ms.com", "--ttl", 2147483648, "--grn=grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm out = self.badrequesttest(command) self.matchoutput(out, "TTL must be between 0 and 2147483647.", command) def test_800_grn(self): self.event_add_arecord( fqdn='arecord50.aqd-unittest.ms.com', ip=str(self.net['unknown0'].usable[50]), dns_environment='internal', ) self.dsdb_expect_add("arecord50.aqd-unittest.ms.com", self.net["unknown0"].usable[50]) command = ["add_address", "--ip=%s" % self.net["unknown0"].usable[50], "--fqdn=arecord50.aqd-unittest.ms.com", "--grn", "grn:/ms/ei/aquilon/aqd"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify() self.events_verify() def test_820_verifygrn(self): net = self.net["unknown0"] command = ["show_address", "--fqdn=arecord50.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: arecord50.aqd-unittest.ms.com", command) self.matchoutput(out, "IP: %s" % net.usable[50], command) self.matchoutput(out, "Network: %s [%s]" % (net.name, net), command) self.matchoutput(out, "Network Environment: internal", command) self.matchoutput(out, "Owned by GRN: grn:/ms/ei/aquilon/aqd", command) self.matchclean(out, "Reverse", command) def test_830_eon_id(self): self.event_add_arecord( fqdn='arecord51.aqd-unittest.ms.com', ip=str(self.net['unknown0'].usable[51]), dns_environment='internal', ) self.dsdb_expect_add("arecord51.aqd-unittest.ms.com", self.net["unknown0"].usable[51]) command = ["add_address", "--ip=%s" % self.net["unknown0"].usable[51], "--fqdn=arecord51.aqd-unittest.ms.com", "--eon_id", "3"] + self.valid_just_tcm self.noouttest(command) self.dsdb_verify() self.events_verify() def test_840_verifygrn(self): net = self.net["unknown0"] command = ["show_address", "--fqdn=arecord51.aqd-unittest.ms.com"] out = self.commandtest(command) self.matchoutput(out, "DNS Record: arecord51.aqd-unittest.ms.com", command) self.matchoutput(out, "IP: %s" % net.usable[51], command) self.matchoutput(out, "Network: %s [%s]" % (net.name, net), command) self.matchoutput(out, "Network Environment: internal", command) self.matchoutput(out, "Owned by GRN: grn:/ms/ei/aquilon/unittest", command) self.matchclean(out, "Reverse", command) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestAddAddress) unittest.TextTestRunner(verbosity=2).run(suite)
en
0.803817
#!/usr/bin/env python # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008-2013,2015-2019 Contributor # # 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. Module for testing the add address command. # Determine the IP type # Prepare the records # Add the records in the expected events # The reverse does not exist in this environment # Different IP in this environment # 1 2 3 4 5 6 # External IP addresses should not be added to DSDB # External IP addresses should not be added to DSDB
2.16873
2
06_Projektion.py
JoshuaJoost/CVIS
0
6612737
__author__ = "<NAME> (1626034)" __maintainer = __author__ __date__ = "2020-04-27" __version__ = "1.0" __status__ = "Finished" import numpy as np import cv2 ## --- Task 1 Projection # --- Constants Task 1 # focal lenght fx = 460 fy = 460 # Translation of the image main point to adapt to the coordinate system of the image plane cx = 320 cy = 240 # Image resolution imageExercise1 = np.zeros((640, 480)) # 3D Room points roomPoints3D = np.array([[[10],[10],[100]], [[33],[22],[111]], [[100],[100],[1000]], [[20],[-100],[100]]]) # calibration matrix, contains intrinsic parameters k = np.array([[fx,0,cx],[0,fy,cy],[0,0,1]], dtype=np.float32) # World and camera coordinate system are identical extrinsicMatrix = np.concatenate((np.eye(3), np.zeros((3,1))),axis=1) # Projection matrix p = np.dot(k, extrinsicMatrix) # using homegeneous coordinate system # :param arg2: cartesian3DRoomPoint need to be shape 3x1 # :return: return cartesian 2D imageplane point def calc3DRoomPointTo2DPointOnImagePlane(projectionMatrix, cartesian3DRoomPoint): if not len(cartesian3DRoomPoint.shape) == 2 or not cartesian3DRoomPoint.shape[0] == 3 or not cartesian3DRoomPoint.shape[1] == 1: roomPointDim = "" for i in range(len(cartesian3DRoomPoint.shape)): roomPointDim = roomPointDim + str(cartesian3DRoomPoint.shape[i]) if i < len(cartesian3DRoomPoint.shape) - 1: roomPointDim = roomPointDim + "x" pass pass raise ValueError(f"Der kartesische 3D-Raumpunkt muss ein 3x1 Vektor sein, gegeben {roomPointDim}") pass # convert cartesian 3D room point to homogeneous 3D room point homogeneous3DRoomPoint = np.reshape(np.concatenate((np.reshape(cartesian3DRoomPoint, (1,-1)), np.ones((cartesian3DRoomPoint.shape[1],1))), axis=1), (-1,1)) # Calculate 2D homogenuous image plane point homogeneous2DImagePlanePoint = np.dot(p, homogeneous3DRoomPoint) # Convert 2D homogenuous to 2D cartesian point cartesian2DImagePlanePoint = np.zeros((homogeneous2DImagePlanePoint.shape[0] - 1, homogeneous2DImagePlanePoint.shape[1])) for i in range(cartesian2DImagePlanePoint.shape[0]): cartesian2DImagePlanePoint[i] = homogeneous2DImagePlanePoint[i] / homogeneous2DImagePlanePoint[-1] pass return cartesian2DImagePlanePoint pass ## --- Determining the pixel position with own function imagePlanePoints2D = np.zeros((roomPoints3D.shape[0], roomPoints3D.shape[1] - 1, roomPoints3D.shape[2])) for i in range(roomPoints3D.shape[0]): cartesicImagePlanePointCoords = calc3DRoomPointTo2DPointOnImagePlane(p, roomPoints3D[i]) imagePlanePoints2D[i][0] = cartesicImagePlanePointCoords[0] imagePlanePoints2D[i][1] = cartesicImagePlanePointCoords[1] pass print(imagePlanePoints2D) ## --- Determining the pixel position using the openCV function cartesicImagePlanePoint = cv2.projectPoints(np.reshape(np.float32(roomPoints3D[:]), (-1,3)), np.eye(3), np.zeros((1,3)), k, None) #print(cartesicImagePlanePoint[0]) # own and cv2 projection identical ## --- Liegen alle Pixel im Bild? # No Pixel 4 is too low on the y-axis and therefore lies outside the image plane ## --- Was fällt bei den Bildpunkten von X1 und X3 auf? # Pixel X1 and X3 are projected on the same spot of the image plane
__author__ = "<NAME> (1626034)" __maintainer = __author__ __date__ = "2020-04-27" __version__ = "1.0" __status__ = "Finished" import numpy as np import cv2 ## --- Task 1 Projection # --- Constants Task 1 # focal lenght fx = 460 fy = 460 # Translation of the image main point to adapt to the coordinate system of the image plane cx = 320 cy = 240 # Image resolution imageExercise1 = np.zeros((640, 480)) # 3D Room points roomPoints3D = np.array([[[10],[10],[100]], [[33],[22],[111]], [[100],[100],[1000]], [[20],[-100],[100]]]) # calibration matrix, contains intrinsic parameters k = np.array([[fx,0,cx],[0,fy,cy],[0,0,1]], dtype=np.float32) # World and camera coordinate system are identical extrinsicMatrix = np.concatenate((np.eye(3), np.zeros((3,1))),axis=1) # Projection matrix p = np.dot(k, extrinsicMatrix) # using homegeneous coordinate system # :param arg2: cartesian3DRoomPoint need to be shape 3x1 # :return: return cartesian 2D imageplane point def calc3DRoomPointTo2DPointOnImagePlane(projectionMatrix, cartesian3DRoomPoint): if not len(cartesian3DRoomPoint.shape) == 2 or not cartesian3DRoomPoint.shape[0] == 3 or not cartesian3DRoomPoint.shape[1] == 1: roomPointDim = "" for i in range(len(cartesian3DRoomPoint.shape)): roomPointDim = roomPointDim + str(cartesian3DRoomPoint.shape[i]) if i < len(cartesian3DRoomPoint.shape) - 1: roomPointDim = roomPointDim + "x" pass pass raise ValueError(f"Der kartesische 3D-Raumpunkt muss ein 3x1 Vektor sein, gegeben {roomPointDim}") pass # convert cartesian 3D room point to homogeneous 3D room point homogeneous3DRoomPoint = np.reshape(np.concatenate((np.reshape(cartesian3DRoomPoint, (1,-1)), np.ones((cartesian3DRoomPoint.shape[1],1))), axis=1), (-1,1)) # Calculate 2D homogenuous image plane point homogeneous2DImagePlanePoint = np.dot(p, homogeneous3DRoomPoint) # Convert 2D homogenuous to 2D cartesian point cartesian2DImagePlanePoint = np.zeros((homogeneous2DImagePlanePoint.shape[0] - 1, homogeneous2DImagePlanePoint.shape[1])) for i in range(cartesian2DImagePlanePoint.shape[0]): cartesian2DImagePlanePoint[i] = homogeneous2DImagePlanePoint[i] / homogeneous2DImagePlanePoint[-1] pass return cartesian2DImagePlanePoint pass ## --- Determining the pixel position with own function imagePlanePoints2D = np.zeros((roomPoints3D.shape[0], roomPoints3D.shape[1] - 1, roomPoints3D.shape[2])) for i in range(roomPoints3D.shape[0]): cartesicImagePlanePointCoords = calc3DRoomPointTo2DPointOnImagePlane(p, roomPoints3D[i]) imagePlanePoints2D[i][0] = cartesicImagePlanePointCoords[0] imagePlanePoints2D[i][1] = cartesicImagePlanePointCoords[1] pass print(imagePlanePoints2D) ## --- Determining the pixel position using the openCV function cartesicImagePlanePoint = cv2.projectPoints(np.reshape(np.float32(roomPoints3D[:]), (-1,3)), np.eye(3), np.zeros((1,3)), k, None) #print(cartesicImagePlanePoint[0]) # own and cv2 projection identical ## --- Liegen alle Pixel im Bild? # No Pixel 4 is too low on the y-axis and therefore lies outside the image plane ## --- Was fällt bei den Bildpunkten von X1 und X3 auf? # Pixel X1 and X3 are projected on the same spot of the image plane
en
0.610692
## --- Task 1 Projection # --- Constants Task 1 # focal lenght # Translation of the image main point to adapt to the coordinate system of the image plane # Image resolution # 3D Room points # calibration matrix, contains intrinsic parameters # World and camera coordinate system are identical # Projection matrix # using homegeneous coordinate system # :param arg2: cartesian3DRoomPoint need to be shape 3x1 # :return: return cartesian 2D imageplane point # convert cartesian 3D room point to homogeneous 3D room point # Calculate 2D homogenuous image plane point # Convert 2D homogenuous to 2D cartesian point ## --- Determining the pixel position with own function ## --- Determining the pixel position using the openCV function #print(cartesicImagePlanePoint[0]) # own and cv2 projection identical ## --- Liegen alle Pixel im Bild? # No Pixel 4 is too low on the y-axis and therefore lies outside the image plane ## --- Was fällt bei den Bildpunkten von X1 und X3 auf? # Pixel X1 and X3 are projected on the same spot of the image plane
2.458443
2
setup.py
Nico-Curti/rFBP
7
6612738
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re import sys import json import platform import warnings try: from setuptools import setup from setuptools import Extension from setuptools import find_packages import setuptools setuptools_version = setuptools.__version__.split('.') if int(setuptools_version[0]) >= 50: warnings.warn('The setuptools version found is >= 50.* ' 'This version could lead to ModuleNotFoundError of basic packages ' '(ref. https://github.com/Nico-Curti/rFBP/issues/5). ' 'We suggest to temporary downgrade the setuptools version to 49.3.0 to workaround this setuptools issue.', ImportWarning) from setuptools import dist dist.Distribution().fetch_build_eggs(['numpy>=1.15', 'Cython>=0.29']) except ImportError: from distutils.core import setup from distutils.core import Extension from distutils.core import find_packages import numpy as np from distutils import sysconfig from Cython.Distutils import build_ext from distutils.sysconfig import customize_compiler from distutils.command.sdist import sdist as _sdist def get_requires (requirements_filename): ''' What packages are required for this module to be executed? Parameters ---------- requirements_filename : str filename of requirements (e.g requirements.txt) Returns ------- requirements : list list of required packages ''' with open(requirements_filename, 'r') as fp: requirements = fp.read() return list(filter(lambda x: x != '', requirements.split())) def get_ext_filename_without_platform_suffix (filename): name, ext = os.path.splitext(filename) ext_suffix = sysconfig.get_config_var('EXT_SUFFIX') if ext_suffix == ext: return filename ext_suffix = ext_suffix.replace(ext, '') idx = name.find(ext_suffix) if idx == -1: return filename else: return name[:idx] + ext class rfbp_build_ext (build_ext): ''' Custom build type ''' def get_ext_filename (self, ext_name): if platform.system() == 'Windows': # The default EXT_SUFFIX of windows include the PEP 3149 tags of compiled modules # In this case I rewrite a custom version of the original distutils.command.build_ext.get_ext_filename function ext_path = ext_name.split('.') ext_suffix = '.pyd' filename = os.path.join(*ext_path) + ext_suffix else: filename = super().get_ext_filename(ext_name) return get_ext_filename_without_platform_suffix(filename) def build_extensions (self): customize_compiler(self.compiler) try: self.compiler.compiler_so.remove('-Wstrict-prototypes') except (AttributeError, ValueError): pass build_ext.build_extensions(self) class sdist(_sdist): def run(self): self.run_command("build_ext") _sdist.run(self) def read_description (readme_filename): ''' Description package from filename Parameters ---------- readme_filename : str filename with readme information (e.g README.md) Returns ------- description : str str with description ''' try: with open(readme_filename, 'r') as fp: description = '\n' description += fp.read() except FileNotFoundError: return '' def read_dependencies_build (dependencies_filename): ''' Read the json of dependencies ''' with open(dependencies_filename, 'r') as fp: dependecies = json.load(fp) return dependecies def read_version (CMakeLists): ''' Read version from variables set in CMake file Parameters ---------- CMakeLists : string Main CMakefile filename or path Returns ------- version : tuple Version as (major, minor, revision) of strings ''' major = re.compile(r'set\s+\(RFBP_MAJOR\s+(\d+)\)') minor = re.compile(r'set\s+\(RFBP_MINOR\s+(\d+)\)') revision = re.compile(r'set\s+\(RFBP_REVISION\s+(\d+)\)') with open(CMakeLists, 'r') as fp: cmake = fp.read() major_v = major.findall(cmake)[0] minor_v = minor.findall(cmake)[0] revision_v = revision.findall(cmake)[0] version = map(int, (major_v, minor_v, revision_v)) return tuple(version) def dump_version_file (here, version_filename): ''' Dump the __version__.py file as python script Parameters ---------- here : string Local path where the CMakeLists.txt file is stored version_filename: string Filename or path where to save the __version__.py filename ''' VERSION = read_version(os.path.join(here, './CMakeLists.txt')) script = '''#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = ['<NAME>', "<NAME>"] __email__ = ['<EMAIL>', '<EMAIL>'] __version__ = '{}.{}.{}' '''.format(*VERSION) with open(version_filename, 'w') as fp: fp.write(script) here = os.path.abspath(os.path.dirname(__file__)).replace('\\', '/') # Package meta-data. NAME = 'ReplicatedFocusingBeliefPropagation' DESCRIPTION = 'Replicated Focusing Belief Propagation algorithm.' EMAIL = '<EMAIL>, <EMAIL>' AUTHOR = "<NAME>, <NAME>" REQUIRES_PYTHON = '>=3.5' VERSION = None KEYWORDS = "belief-propagation deep-neural-networks spin-glass" CPP_COMPILER = platform.python_compiler() README_FILENAME = os.path.join(here, 'README.md') REQUIREMENTS_FILENAME = os.path.join(here, 'requirements.txt') DEPENDENCIES_FILENAME = os.path.join(here, 'ReplicatedFocusingBeliefPropagation', 'dependencies.json') VERSION_FILENAME = os.path.join(here, 'ReplicatedFocusingBeliefPropagation', '__version__.py') ENABLE_OMP = False BUILD_SCORER = False # Import the README and use it as the long-description. # Note: this will only work if 'README.md' is present in your MANIFEST.in file! try: LONG_DESCRIPTION = read_description(README_FILENAME) except FileNotFoundError: LONG_DESCRIPTION = DESCRIPTION current_python = sys.executable.split('/bin')[0] numpy_dir = current_python + '/lib/python{0}.{1}/site-packages/numpy/core/include'.format(sys.version_info.major, sys.version_info.minor) if os.path.isdir(numpy_dir): os.environ['CFLAGS'] = '-I' + numpy_dir dump_version_file(here, VERSION_FILENAME) # Load the package's __version__.py module as a dictionary. about = {} if not VERSION: with open(VERSION_FILENAME) as fp: exec(fp.read(), about) else: about['__version__'] = VERSION # parse version variables and add them to command line as definitions Version = about['__version__'].split('.') URL = 'https://github.com/Nico-Curti/rFBP'#/archive/v{}.tar.gz'.format(about['__version__']) # Read dependecies graph dependencies = read_dependencies_build(DEPENDENCIES_FILENAME) # Set compiler variables define_args = [ '-DMAJOR={}'.format(Version[0]), '-DMINOR={}'.format(Version[1]), '-DREVISION={}'.format(Version[2]), '-DSTATS', '-DNDEBUG', '-DVERBOSE', '-DNPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION', '-DPWD="{}"'.format(here) ] if 'GCC' in CPP_COMPILER or 'Clang' in CPP_COMPILER: cpp_compiler_args = ['-std=c++1z', '-std=gnu++1z', '-g0'] compile_args = [ '-Wno-unused-function', # disable unused-function warnings '-Wno-narrowing', # disable narrowing conversion warnings # enable common warnings flags '-Wall', '-Wextra', '-Wno-unused-result', '-Wno-unknown-pragmas', '-Wfatal-errors', '-Wpedantic', '-march=native', ] try: compiler, compiler_version = CPP_COMPILER.split() except ValueError: compiler, compiler_version = (CPP_COMPILER, '0') if compiler == 'GCC' and BUILD_SCORER: BUILD_SCORER = True if int(compiler_version[0]) > 4 else False if ENABLE_OMP and compiler == 'GCC': linker_args = ['-fopenmp'] else: linker_args = [] if compiler == 'Clang': print('OpenMP support disabled. It can be used only with gcc compiler.', file=sys.stderr) elif 'MSC' in CPP_COMPILER: cpp_compiler_args = ['/std:c++latest', '/Ox'] compile_args = ['/Wall', '/W3'] if ENABLE_OMP: linker_args = ['/openmp'] else: linker_args = [] else: raise ValueError('Unknown c++ compiler arg') if BUILD_SCORER: scorer_include = [os.path.join(os.getcwd(), 'scorer', 'include'), os.path.join(os.getcwd(), 'scorer', 'scorer', 'include'),] else: scorer_include = [] whole_compiler_args = sum([cpp_compiler_args, compile_args, define_args, linker_args], []) cmdclass = {'build_ext': rfbp_build_ext, 'sdist': sdist} # Where the magic happens: setup( name = NAME, version = about['__version__'], description = DESCRIPTION, long_description = LONG_DESCRIPTION, long_description_content_type = 'text/markdown', author = AUTHOR, author_email = EMAIL, maintainer = AUTHOR, maintainer_email = EMAIL, python_requires = REQUIRES_PYTHON, install_requires = get_requires(REQUIREMENTS_FILENAME), url = URL, download_url = '{}/archive/v{}.tar.gz'.format(URL, about['__version__']), keywords = KEYWORDS, setup_requires = [# Setuptools 18.0 properly handles Cython extensions. 'setuptools>=18.0', 'numpy>=1.15' 'Cython>=0.29'], packages = find_packages(include=['ReplicatedFocusingBeliefPropagation', 'ReplicatedFocusingBeliefPropagation.*'], exclude=('test', 'example')), include_package_data = True, data_files = [('', ['CMakeLists.txt', 'README.md', 'LICENSE']), ('scripts', ['./scripts/download_atanherf.py'])], platforms = 'any', classifiers = [ # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers #'License :: OSI Approved :: GPL License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Operating System :: POSIX :: Linux', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy' ], license = 'MIT', cmdclass = cmdclass, ext_modules = [ Extension(name='.'.join(['ReplicatedFocusingBeliefPropagation', 'lib', name]), sources=values['sources'], include_dirs=sum([values['include_dirs'], [np.get_include()]], []), libraries=values['libraries'], library_dirs=[ os.path.join(here, 'lib'), os.path.join('usr', 'lib'), os.path.join('usr', 'local', 'lib'), ], # path to .a or .so file(s) extra_compile_args = whole_compiler_args, extra_link_args = linker_args, language='c++' ) for name, values in dependencies.items() ], )
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re import sys import json import platform import warnings try: from setuptools import setup from setuptools import Extension from setuptools import find_packages import setuptools setuptools_version = setuptools.__version__.split('.') if int(setuptools_version[0]) >= 50: warnings.warn('The setuptools version found is >= 50.* ' 'This version could lead to ModuleNotFoundError of basic packages ' '(ref. https://github.com/Nico-Curti/rFBP/issues/5). ' 'We suggest to temporary downgrade the setuptools version to 49.3.0 to workaround this setuptools issue.', ImportWarning) from setuptools import dist dist.Distribution().fetch_build_eggs(['numpy>=1.15', 'Cython>=0.29']) except ImportError: from distutils.core import setup from distutils.core import Extension from distutils.core import find_packages import numpy as np from distutils import sysconfig from Cython.Distutils import build_ext from distutils.sysconfig import customize_compiler from distutils.command.sdist import sdist as _sdist def get_requires (requirements_filename): ''' What packages are required for this module to be executed? Parameters ---------- requirements_filename : str filename of requirements (e.g requirements.txt) Returns ------- requirements : list list of required packages ''' with open(requirements_filename, 'r') as fp: requirements = fp.read() return list(filter(lambda x: x != '', requirements.split())) def get_ext_filename_without_platform_suffix (filename): name, ext = os.path.splitext(filename) ext_suffix = sysconfig.get_config_var('EXT_SUFFIX') if ext_suffix == ext: return filename ext_suffix = ext_suffix.replace(ext, '') idx = name.find(ext_suffix) if idx == -1: return filename else: return name[:idx] + ext class rfbp_build_ext (build_ext): ''' Custom build type ''' def get_ext_filename (self, ext_name): if platform.system() == 'Windows': # The default EXT_SUFFIX of windows include the PEP 3149 tags of compiled modules # In this case I rewrite a custom version of the original distutils.command.build_ext.get_ext_filename function ext_path = ext_name.split('.') ext_suffix = '.pyd' filename = os.path.join(*ext_path) + ext_suffix else: filename = super().get_ext_filename(ext_name) return get_ext_filename_without_platform_suffix(filename) def build_extensions (self): customize_compiler(self.compiler) try: self.compiler.compiler_so.remove('-Wstrict-prototypes') except (AttributeError, ValueError): pass build_ext.build_extensions(self) class sdist(_sdist): def run(self): self.run_command("build_ext") _sdist.run(self) def read_description (readme_filename): ''' Description package from filename Parameters ---------- readme_filename : str filename with readme information (e.g README.md) Returns ------- description : str str with description ''' try: with open(readme_filename, 'r') as fp: description = '\n' description += fp.read() except FileNotFoundError: return '' def read_dependencies_build (dependencies_filename): ''' Read the json of dependencies ''' with open(dependencies_filename, 'r') as fp: dependecies = json.load(fp) return dependecies def read_version (CMakeLists): ''' Read version from variables set in CMake file Parameters ---------- CMakeLists : string Main CMakefile filename or path Returns ------- version : tuple Version as (major, minor, revision) of strings ''' major = re.compile(r'set\s+\(RFBP_MAJOR\s+(\d+)\)') minor = re.compile(r'set\s+\(RFBP_MINOR\s+(\d+)\)') revision = re.compile(r'set\s+\(RFBP_REVISION\s+(\d+)\)') with open(CMakeLists, 'r') as fp: cmake = fp.read() major_v = major.findall(cmake)[0] minor_v = minor.findall(cmake)[0] revision_v = revision.findall(cmake)[0] version = map(int, (major_v, minor_v, revision_v)) return tuple(version) def dump_version_file (here, version_filename): ''' Dump the __version__.py file as python script Parameters ---------- here : string Local path where the CMakeLists.txt file is stored version_filename: string Filename or path where to save the __version__.py filename ''' VERSION = read_version(os.path.join(here, './CMakeLists.txt')) script = '''#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = ['<NAME>', "<NAME>"] __email__ = ['<EMAIL>', '<EMAIL>'] __version__ = '{}.{}.{}' '''.format(*VERSION) with open(version_filename, 'w') as fp: fp.write(script) here = os.path.abspath(os.path.dirname(__file__)).replace('\\', '/') # Package meta-data. NAME = 'ReplicatedFocusingBeliefPropagation' DESCRIPTION = 'Replicated Focusing Belief Propagation algorithm.' EMAIL = '<EMAIL>, <EMAIL>' AUTHOR = "<NAME>, <NAME>" REQUIRES_PYTHON = '>=3.5' VERSION = None KEYWORDS = "belief-propagation deep-neural-networks spin-glass" CPP_COMPILER = platform.python_compiler() README_FILENAME = os.path.join(here, 'README.md') REQUIREMENTS_FILENAME = os.path.join(here, 'requirements.txt') DEPENDENCIES_FILENAME = os.path.join(here, 'ReplicatedFocusingBeliefPropagation', 'dependencies.json') VERSION_FILENAME = os.path.join(here, 'ReplicatedFocusingBeliefPropagation', '__version__.py') ENABLE_OMP = False BUILD_SCORER = False # Import the README and use it as the long-description. # Note: this will only work if 'README.md' is present in your MANIFEST.in file! try: LONG_DESCRIPTION = read_description(README_FILENAME) except FileNotFoundError: LONG_DESCRIPTION = DESCRIPTION current_python = sys.executable.split('/bin')[0] numpy_dir = current_python + '/lib/python{0}.{1}/site-packages/numpy/core/include'.format(sys.version_info.major, sys.version_info.minor) if os.path.isdir(numpy_dir): os.environ['CFLAGS'] = '-I' + numpy_dir dump_version_file(here, VERSION_FILENAME) # Load the package's __version__.py module as a dictionary. about = {} if not VERSION: with open(VERSION_FILENAME) as fp: exec(fp.read(), about) else: about['__version__'] = VERSION # parse version variables and add them to command line as definitions Version = about['__version__'].split('.') URL = 'https://github.com/Nico-Curti/rFBP'#/archive/v{}.tar.gz'.format(about['__version__']) # Read dependecies graph dependencies = read_dependencies_build(DEPENDENCIES_FILENAME) # Set compiler variables define_args = [ '-DMAJOR={}'.format(Version[0]), '-DMINOR={}'.format(Version[1]), '-DREVISION={}'.format(Version[2]), '-DSTATS', '-DNDEBUG', '-DVERBOSE', '-DNPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION', '-DPWD="{}"'.format(here) ] if 'GCC' in CPP_COMPILER or 'Clang' in CPP_COMPILER: cpp_compiler_args = ['-std=c++1z', '-std=gnu++1z', '-g0'] compile_args = [ '-Wno-unused-function', # disable unused-function warnings '-Wno-narrowing', # disable narrowing conversion warnings # enable common warnings flags '-Wall', '-Wextra', '-Wno-unused-result', '-Wno-unknown-pragmas', '-Wfatal-errors', '-Wpedantic', '-march=native', ] try: compiler, compiler_version = CPP_COMPILER.split() except ValueError: compiler, compiler_version = (CPP_COMPILER, '0') if compiler == 'GCC' and BUILD_SCORER: BUILD_SCORER = True if int(compiler_version[0]) > 4 else False if ENABLE_OMP and compiler == 'GCC': linker_args = ['-fopenmp'] else: linker_args = [] if compiler == 'Clang': print('OpenMP support disabled. It can be used only with gcc compiler.', file=sys.stderr) elif 'MSC' in CPP_COMPILER: cpp_compiler_args = ['/std:c++latest', '/Ox'] compile_args = ['/Wall', '/W3'] if ENABLE_OMP: linker_args = ['/openmp'] else: linker_args = [] else: raise ValueError('Unknown c++ compiler arg') if BUILD_SCORER: scorer_include = [os.path.join(os.getcwd(), 'scorer', 'include'), os.path.join(os.getcwd(), 'scorer', 'scorer', 'include'),] else: scorer_include = [] whole_compiler_args = sum([cpp_compiler_args, compile_args, define_args, linker_args], []) cmdclass = {'build_ext': rfbp_build_ext, 'sdist': sdist} # Where the magic happens: setup( name = NAME, version = about['__version__'], description = DESCRIPTION, long_description = LONG_DESCRIPTION, long_description_content_type = 'text/markdown', author = AUTHOR, author_email = EMAIL, maintainer = AUTHOR, maintainer_email = EMAIL, python_requires = REQUIRES_PYTHON, install_requires = get_requires(REQUIREMENTS_FILENAME), url = URL, download_url = '{}/archive/v{}.tar.gz'.format(URL, about['__version__']), keywords = KEYWORDS, setup_requires = [# Setuptools 18.0 properly handles Cython extensions. 'setuptools>=18.0', 'numpy>=1.15' 'Cython>=0.29'], packages = find_packages(include=['ReplicatedFocusingBeliefPropagation', 'ReplicatedFocusingBeliefPropagation.*'], exclude=('test', 'example')), include_package_data = True, data_files = [('', ['CMakeLists.txt', 'README.md', 'LICENSE']), ('scripts', ['./scripts/download_atanherf.py'])], platforms = 'any', classifiers = [ # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers #'License :: OSI Approved :: GPL License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Operating System :: POSIX :: Linux', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy' ], license = 'MIT', cmdclass = cmdclass, ext_modules = [ Extension(name='.'.join(['ReplicatedFocusingBeliefPropagation', 'lib', name]), sources=values['sources'], include_dirs=sum([values['include_dirs'], [np.get_include()]], []), libraries=values['libraries'], library_dirs=[ os.path.join(here, 'lib'), os.path.join('usr', 'lib'), os.path.join('usr', 'local', 'lib'), ], # path to .a or .so file(s) extra_compile_args = whole_compiler_args, extra_link_args = linker_args, language='c++' ) for name, values in dependencies.items() ], )
en
0.612203
#!/usr/bin/env python # -*- coding: utf-8 -*- What packages are required for this module to be executed? Parameters ---------- requirements_filename : str filename of requirements (e.g requirements.txt) Returns ------- requirements : list list of required packages Custom build type # The default EXT_SUFFIX of windows include the PEP 3149 tags of compiled modules # In this case I rewrite a custom version of the original distutils.command.build_ext.get_ext_filename function Description package from filename Parameters ---------- readme_filename : str filename with readme information (e.g README.md) Returns ------- description : str str with description Read the json of dependencies Read version from variables set in CMake file Parameters ---------- CMakeLists : string Main CMakefile filename or path Returns ------- version : tuple Version as (major, minor, revision) of strings Dump the __version__.py file as python script Parameters ---------- here : string Local path where the CMakeLists.txt file is stored version_filename: string Filename or path where to save the __version__.py filename #!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = ['<NAME>', "<NAME>"] __email__ = ['<EMAIL>', '<EMAIL>'] __version__ = '{}.{}.{}' # Package meta-data. # Import the README and use it as the long-description. # Note: this will only work if 'README.md' is present in your MANIFEST.in file! # Load the package's __version__.py module as a dictionary. # parse version variables and add them to command line as definitions # Read dependecies graph # Set compiler variables # disable unused-function warnings # disable narrowing conversion warnings # enable common warnings flags # Where the magic happens: # Setuptools 18.0 properly handles Cython extensions. # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers #'License :: OSI Approved :: GPL License', # path to .a or .so file(s)
1.955812
2
visdialch/encoders/__init__.py
joel99/visdial-challenge-starter-pytorch
0
6612739
from visdialch.encoders.bu_lf import BottomUpLateFusionEncoder from visdialch.encoders.lf import LateFusionEncoder def Encoder(model_config, *args): name_enc_map = { 'lf': LateFusionEncoder, 'bu_lf': BottomUpLateFusionEncoder } return name_enc_map[model_config["encoder"]](model_config, *args)
from visdialch.encoders.bu_lf import BottomUpLateFusionEncoder from visdialch.encoders.lf import LateFusionEncoder def Encoder(model_config, *args): name_enc_map = { 'lf': LateFusionEncoder, 'bu_lf': BottomUpLateFusionEncoder } return name_enc_map[model_config["encoder"]](model_config, *args)
none
1
1.924909
2
bin/aws_access.py
macks22/elasticsearch-playground
0
6612740
access_key = "AWS_ACCESS_KEY" secret_access_key = "AWS_SECRET_ACCESS_KEY" associate_tag = "AWS_PRODUCT_ADVERTISING_API_ASSOCIATE_TAG"
access_key = "AWS_ACCESS_KEY" secret_access_key = "AWS_SECRET_ACCESS_KEY" associate_tag = "AWS_PRODUCT_ADVERTISING_API_ASSOCIATE_TAG"
none
1
0.907573
1
nomadgram/users/migrations/0003_auto_20200127_2142.py
GBlueffect/nomardgram
0
6612741
<reponame>GBlueffect/nomardgram<filename>nomadgram/users/migrations/0003_auto_20200127_2142.py # Generated by Django 2.2.9 on 2020-01-27 12:42 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0002_auto_20200127_1655'), ] operations = [ migrations.AddField( model_name='user', name='follewers', field=models.ManyToManyField(related_name='_user_follewers_+', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='user', name='following', field=models.ManyToManyField(related_name='_user_following_+', to=settings.AUTH_USER_MODEL), ), ]
# Generated by Django 2.2.9 on 2020-01-27 12:42 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0002_auto_20200127_1655'), ] operations = [ migrations.AddField( model_name='user', name='follewers', field=models.ManyToManyField(related_name='_user_follewers_+', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='user', name='following', field=models.ManyToManyField(related_name='_user_following_+', to=settings.AUTH_USER_MODEL), ), ]
en
0.8119
# Generated by Django 2.2.9 on 2020-01-27 12:42
1.656752
2
PySS/scan_3D.py
manpan-1/steel_toolbox
2
6612742
# -*- coding: utf-8 -*- """ Module containing methods related to 3D scanning. """ import numpy as np from stl import mesh import os from PySS import analytic_geometry as ag import pickle from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D class Scan3D: """ 3D model data. Class of 3D objects. Can be imported from an .stl file of a .txt file of list of node coordinates. """ def __init__(self, scanned_data=None): self.scanned_data = scanned_data self.grouped_data = None self.centre = None self.size = None @classmethod def from_stl_file(cls, fh, del_original=None): """ Import stl file. Alternative constructor, creates a Scan3D object by reading data from an .stl file. In case the file is created by Creaform's software (it is detected using name of the solid object as described in it's frist line), it is corrected accordingly before importing. The original file is renamed by adding '_old' before the extension or they can be deleted automatically if specified so. Parameters ---------- fh : str File path. del_original : bool, optional Keep or delete the original file. Default is keep. """ with open(fh, 'r') as f: fl = f.readlines(1)[0] identifier = fl.split(None, 1)[1] if identifier == 'ASCII STL file generated with VxScan by Creaform.\n': # Repair the file format Scan3D.repair_stl_file_structure(fh, del_original=del_original) return cls(scanned_data=Scan3D.array2points(mesh.Mesh.from_file(fh))) @classmethod def from_pickle(cls, fh): """ Method for importing a pickle file containing x, y, z, coordinates. Used to import data exported from blender. The pickle file is should contain a list of lists. """ with open(fh, 'rb') as fh: return cls(scanned_data=Scan3D.array2points(np.array(pickle.load(fh)))) @classmethod def from_coordinates_file(cls, fh): """ Method reading text files containing x, y, z coordinates. Used to import data from 3D scanning files. """ # Open the requested file. with open(fh, 'r') as f: # Number of points. n_of_points = len(f.readlines()) # Initialise a numpy array for the values. scanned_data = np.empty([n_of_points, 3]) # Reset the file read cursor and loop over the lines of the file populating the numpy array. f.seek(0) for i, l in enumerate(f): scanned_data[i] = l.split() return cls(scanned_data=Scan3D.array2points(scanned_data)) @staticmethod def repair_stl_file_structure(fh, del_original=None): """ Repair header-footer of files created by Creaform's package. The .stl files created by Creaform's software are missing standard .stl header and footer. This method will create a copy of the requested file with proper header-footer using the filename (without the extension) as a name of the solid. Parameters ---------- fh : str File path. del_original : bool, optional Keep or delete the original file. Default is keep. """ if del_original is None: del_original = False solid_name = os.path.splitext(os.path.basename(fh))[0] start_line = "solid " + solid_name + "\n" end_line = "endsolid " + solid_name old_file = os.path.splitext(fh)[0] + 'old.stl' os.rename(fh, old_file) with open(old_file) as fin: lines = fin.readlines() lines[0] = start_line lines.append(end_line) with open(fh, 'w') as fout: for line in lines: fout.write(line) if del_original: os.remove(old_file) @staticmethod def array2points(array): """ Convert an array of coordinates to a list of Point3D objects. Parameters ---------- array : {n*3} np.ndarray Returns ------- list of Point3D. """ if isinstance(array, np.ndarray): if np.shape(array)[1] == 3: point_list = [] for i in array: point_list.append(ag.Point3D.from_coordinates(i[0], i[1], i[2])) return point_list else: print('Wrong array dimensions. The array must have 3 columns.') return NotImplemented else: print('Wrong input. Input must be np.ndarray') return NotImplemented # TODO:Docstring... def sort_on_axis(self, axis=None): """ Sort scanned data. The scanned points are sorted for a given axis. :param axis: :return: """ if axis is None: axis = 0 self.scanned_data.sort(key=lambda x: x.coords[axis]) # TODO:Docstring... def quantize(self, axis=None, tolerance=None): """ Group the scanned data. The points with difference on a given axis smaller than the tolerance are grouped together and stored in a list in the attribute `grouped_data`. :param axis: :param tolerance: :return: """ if axis is None: axis = 0 if tolerance is None: tolerance = 1e-4 self.sort_on_axis(axis=axis) self.grouped_data = [[self.scanned_data[0]]] for point in self.scanned_data: if abs(point.coords[axis] - self.grouped_data[-1][0].coords[axis]) < tolerance: self.grouped_data[-1].append(point) else: self.grouped_data.append([point]) def centre_size(self): """ Get the centre and the range of the data points. Used in combination with the plotting methods to define the bounding box. """ # Bounding box of the points. x_min = min([i.coords[0] for i in self.scanned_data]) x_max = max([i.coords[0] for i in self.scanned_data]) y_min = min([i.coords[1] for i in self.scanned_data]) y_max = max([i.coords[1] for i in self.scanned_data]) z_min = min([i.coords[2] for i in self.scanned_data]) z_max = max([i.coords[2] for i in self.scanned_data]) x_range = abs(x_max - x_min) y_range = abs(y_max - y_min) z_range = abs(z_max - z_min) x_mid = (x_max + x_min) / 2 y_mid = (y_max + y_min) / 2 z_mid = (z_min + z_max) / 2 self.centre = np.r_[x_mid, y_mid, z_mid] self.size = np.r_[x_range, y_range, z_range] # TODO: fix: the method stopped working after the Point3D implementation. Currently commented. # def plot_surf(self): # """ # Method plotting the model as a 3D surface. # """ # # Create the x, y, z numpy # x = [i[0] for i in self.scanned_data] # y = [i[1] for i in self.scanned_data] # z = [i[2] for i in self.scanned_data] # # # Create a figure. # fig = plt.figure() # ax = fig.gca(projection='3d') # # # Plot the data # ax.plot_trisurf(x, y, z) class FlatFace(Scan3D): """ Subclass of the Scan3D class, specifically for flat faces. Used for the individual faces of the polygonal specimens. """ def __init__(self, scanned_data=None): self.face2ref_dist = None self.ref_plane = None super().__init__(scanned_data) def fit_plane(self): """ Fit a plane on the scanned data. The Plane3D object is assigned in the `self.ref_plane`. The fitted plane is returned using the analytic_geometry.lstsq_planar_fit with the optional argument lay_on_xy=True. See analytic_geometry.lstsq_planar_fit documentation. """ self.ref_plane = ag.Plane3D.from_fitting(self.scanned_data, lay_on_xy=True) def offset_face(self, offset, offset_points=False): """ Offset the plane and (optionally) the scanned data points. Useful for translating translating the scanned surface to the mid line. :param offset: :param offset_points: :return: """ self.ref_plane.offset_plane(offset) if offset_points: point_list = [ag.Point3D(p.coords + self.ref_plane.plane_coeff[:3] * offset) for p in self.scanned_data] self.scanned_data = np.array(point_list) def calc_face2ref_dist(self): """Calculates distances from facet points to the reference plane.""" if self.ref_plane: self.face2ref_dist = [] for x in self.scanned_data: self.face2ref_dist.append(x.distance_to_plane(self.ref_plane)) def plot_face(self, fig=None, reduced=None): """ Surface plotter. Plot the 3d points and the fitted plane. Parameters ---------- fig : Object of class matplotlib.figure.Figure, optional The figure window to be used for plotting. By default, a new window is created. reduced: float, optional A reduced randomly selected subset of points is plotted (in case the data is too dense for plotting). The rediced size is given as a ratio of the total number of points, e.g `reduced=0.5` plots half the points. By default, all points are plotted. """ # Average and range of the points. self.centre_size() x_lims = [self.centre[0] - self.size[0] / 2., self.centre[0] + self.size[0] / 2.] y_lims = [self.centre[1] - self.size[1] / 2., self.centre[1] + self.size[1] / 2.] x, y = np.meshgrid(x_lims, y_lims) # evaluate the plane function on the grid. z = self.ref_plane.z_return(x, y) # or expressed using matrix/vector product # z = np.dot(np.c_[xx, yy, np.ones(xx.shape)], self.plane_coeff).reshape(x.shape) plot_dim = max(self.size[0], self.size[1], self.size[2]) # Quadratic:evaluate it on a grid # z = np.dot(np.c_[np.ones(xx.shape), xx, yy, xx * yy, xx ** 2, yy ** 2], self.plane_coeff).reshape(x.shape) # Get a figure to plot on if fig is None: fig = plt.figure() ax = Axes3D(fig) else: ax = fig.get_axes()[0] # Plot the plane ax.plot_surface(x, y, z, rstride=1, cstride=1, alpha=0.2) # Make a randomly selected subset of points acc. to the input arg 'reduced=x'. if isinstance(reduced, float) and (0 < reduced < 1): i = np.random.choice( len(self.scanned_data[:, 0]), size=round(len(self.scanned_data[:, 0]) * reduced), replace=False ) else: i = range(0, len(self.scanned_data[:, 0])) # Plot the points ax.scatter(self.scanned_data[i, 0], self.scanned_data[i, 1], self.scanned_data[i, 2], c='r', s=50) plt.xlabel('x') plt.ylabel('y') ax.set_zlabel('z') ax.set_xlim3d(self.centre[0] - plot_dim / 2, self.centre[0] + plot_dim / 2) ax.set_ylim3d(self.centre[1] - plot_dim / 2, self.centre[1] + plot_dim / 2) ax.set_zlim3d(self.centre[2] - plot_dim / 2, self.centre[2] + plot_dim / 2) # ax.axis('tight') plt.show() # Return the figure handle. return fig class RoundedEdge(Scan3D): """ A scanned rounded edge. """ def __init__(self, scanned_data=None): self.theoretical_edge = None self.edge_points = None self.circles = None self.edge2ref_dist = None self.ref_line = None super().__init__(scanned_data) def add_theoretical_edge(self, line): """ Add a reference line for the edge. Useful when the rounded edge lies between flat faces and the theoretical edge is at their intersection. Parameters ---------- line : Line3D Theoretical edge line to be added. This line should be calculated as the intersection of the facets sharing this edge. """ if isinstance(line, ag.Line3D): self.theoretical_edge = line else: print("ref_line must be Line3D") return NotImplemented def fit_circles(self, axis=None, offset=None): """ Fit a series of circles along the length of the rounded edge. The scanned data are first grouped together based on their z-coordinate ant then a horizontal circle is fitted for each group of points. :return: """ if axis is None: axis = 0 if offset is None: offset = 0 self.quantize(axis=axis) self.circles = [] for x in self.grouped_data: self.circles.append(ag.Circle2D.from_fitting(x)) self.circles[-1].radius = self.circles[-1].radius + offset # TODO: Docstrings parameters... def calc_edge_points(self, other): """ Intersect scanned points with a surface between the reference line and a given line. This function is used to find points on the scanned rounded corner. Circles are fitted on the scanned points on different positions. Then the circles are intersected with the line passing through the reference line of the edge and another given line (e.g. the centre of the column). A list of points is generated which represent the real edge of rounded corner. :param other: :return: """ if isinstance(other, ag.Line3D): self.edge_points = [] # Loop through the circles that represent the edge roundness at different heights. for circle in self.circles: # Get the z-coordinate (height) of the current point z_current = circle.points[0].coords[2] #print('Finding edge point at height {}'.format(z_current)) # Get the x-y coordinates of the edge reference line and the mid-line for the given height, z. ref_line_point = self.theoretical_edge.xy_for_z(z_current) other_line_point = other.xy_for_z(z_current) # Create a temporary line object from the two points. intersection_line = ag.Line2D.from_2_points(ref_line_point[:2], other_line_point[:2]) # Intersect this temporary line with the current circle. line_circle_intersection = circle.intersect_with_line(intersection_line) # If the line does not intersect with the current circle, print on screen and continue. if line_circle_intersection is None: print("Line and circle at height {} do not intersect. Point ignored.".format(z_current)) else: # If the line intersects with the circle, select the outermost of the two intersection points. if np.linalg.norm(line_circle_intersection[0]) > np.linalg.norm(line_circle_intersection[1]): outer = line_circle_intersection[0] else: outer = line_circle_intersection[1] # Append the point to the list of edge_points self.edge_points.append(ag.Point3D(np.append(outer, z_current))) else: print('The input object is not of the class `Line3D`') return NotImplemented def calc_ref_line(self): """ Calculate the reference line. The reference line for the edge is defined as the best fit straight line to the edge points. For more information on the edge points, see the `intersect_data` method. """ self.ref_line = ag.Line3D.from_fitting(self.edge_points) def calc_edge2ref_dist(self): """Calculate distances of edge points to the reference line.""" if self.ref_line and not self.ref_line is NotImplemented: self.edge2ref_dist = [] for x in self.edge_points: self.edge2ref_dist.append(x.distance_to_line(self.theoretical_edge)) else: print('No reference line. First, add a reference line to the object. Check if the fitting process on the ' 'edge points converged. Edge ignored.') return NotImplemented def main(): print('Module successfully loaded.') if __name__ == "__main__": main()
# -*- coding: utf-8 -*- """ Module containing methods related to 3D scanning. """ import numpy as np from stl import mesh import os from PySS import analytic_geometry as ag import pickle from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D class Scan3D: """ 3D model data. Class of 3D objects. Can be imported from an .stl file of a .txt file of list of node coordinates. """ def __init__(self, scanned_data=None): self.scanned_data = scanned_data self.grouped_data = None self.centre = None self.size = None @classmethod def from_stl_file(cls, fh, del_original=None): """ Import stl file. Alternative constructor, creates a Scan3D object by reading data from an .stl file. In case the file is created by Creaform's software (it is detected using name of the solid object as described in it's frist line), it is corrected accordingly before importing. The original file is renamed by adding '_old' before the extension or they can be deleted automatically if specified so. Parameters ---------- fh : str File path. del_original : bool, optional Keep or delete the original file. Default is keep. """ with open(fh, 'r') as f: fl = f.readlines(1)[0] identifier = fl.split(None, 1)[1] if identifier == 'ASCII STL file generated with VxScan by Creaform.\n': # Repair the file format Scan3D.repair_stl_file_structure(fh, del_original=del_original) return cls(scanned_data=Scan3D.array2points(mesh.Mesh.from_file(fh))) @classmethod def from_pickle(cls, fh): """ Method for importing a pickle file containing x, y, z, coordinates. Used to import data exported from blender. The pickle file is should contain a list of lists. """ with open(fh, 'rb') as fh: return cls(scanned_data=Scan3D.array2points(np.array(pickle.load(fh)))) @classmethod def from_coordinates_file(cls, fh): """ Method reading text files containing x, y, z coordinates. Used to import data from 3D scanning files. """ # Open the requested file. with open(fh, 'r') as f: # Number of points. n_of_points = len(f.readlines()) # Initialise a numpy array for the values. scanned_data = np.empty([n_of_points, 3]) # Reset the file read cursor and loop over the lines of the file populating the numpy array. f.seek(0) for i, l in enumerate(f): scanned_data[i] = l.split() return cls(scanned_data=Scan3D.array2points(scanned_data)) @staticmethod def repair_stl_file_structure(fh, del_original=None): """ Repair header-footer of files created by Creaform's package. The .stl files created by Creaform's software are missing standard .stl header and footer. This method will create a copy of the requested file with proper header-footer using the filename (without the extension) as a name of the solid. Parameters ---------- fh : str File path. del_original : bool, optional Keep or delete the original file. Default is keep. """ if del_original is None: del_original = False solid_name = os.path.splitext(os.path.basename(fh))[0] start_line = "solid " + solid_name + "\n" end_line = "endsolid " + solid_name old_file = os.path.splitext(fh)[0] + 'old.stl' os.rename(fh, old_file) with open(old_file) as fin: lines = fin.readlines() lines[0] = start_line lines.append(end_line) with open(fh, 'w') as fout: for line in lines: fout.write(line) if del_original: os.remove(old_file) @staticmethod def array2points(array): """ Convert an array of coordinates to a list of Point3D objects. Parameters ---------- array : {n*3} np.ndarray Returns ------- list of Point3D. """ if isinstance(array, np.ndarray): if np.shape(array)[1] == 3: point_list = [] for i in array: point_list.append(ag.Point3D.from_coordinates(i[0], i[1], i[2])) return point_list else: print('Wrong array dimensions. The array must have 3 columns.') return NotImplemented else: print('Wrong input. Input must be np.ndarray') return NotImplemented # TODO:Docstring... def sort_on_axis(self, axis=None): """ Sort scanned data. The scanned points are sorted for a given axis. :param axis: :return: """ if axis is None: axis = 0 self.scanned_data.sort(key=lambda x: x.coords[axis]) # TODO:Docstring... def quantize(self, axis=None, tolerance=None): """ Group the scanned data. The points with difference on a given axis smaller than the tolerance are grouped together and stored in a list in the attribute `grouped_data`. :param axis: :param tolerance: :return: """ if axis is None: axis = 0 if tolerance is None: tolerance = 1e-4 self.sort_on_axis(axis=axis) self.grouped_data = [[self.scanned_data[0]]] for point in self.scanned_data: if abs(point.coords[axis] - self.grouped_data[-1][0].coords[axis]) < tolerance: self.grouped_data[-1].append(point) else: self.grouped_data.append([point]) def centre_size(self): """ Get the centre and the range of the data points. Used in combination with the plotting methods to define the bounding box. """ # Bounding box of the points. x_min = min([i.coords[0] for i in self.scanned_data]) x_max = max([i.coords[0] for i in self.scanned_data]) y_min = min([i.coords[1] for i in self.scanned_data]) y_max = max([i.coords[1] for i in self.scanned_data]) z_min = min([i.coords[2] for i in self.scanned_data]) z_max = max([i.coords[2] for i in self.scanned_data]) x_range = abs(x_max - x_min) y_range = abs(y_max - y_min) z_range = abs(z_max - z_min) x_mid = (x_max + x_min) / 2 y_mid = (y_max + y_min) / 2 z_mid = (z_min + z_max) / 2 self.centre = np.r_[x_mid, y_mid, z_mid] self.size = np.r_[x_range, y_range, z_range] # TODO: fix: the method stopped working after the Point3D implementation. Currently commented. # def plot_surf(self): # """ # Method plotting the model as a 3D surface. # """ # # Create the x, y, z numpy # x = [i[0] for i in self.scanned_data] # y = [i[1] for i in self.scanned_data] # z = [i[2] for i in self.scanned_data] # # # Create a figure. # fig = plt.figure() # ax = fig.gca(projection='3d') # # # Plot the data # ax.plot_trisurf(x, y, z) class FlatFace(Scan3D): """ Subclass of the Scan3D class, specifically for flat faces. Used for the individual faces of the polygonal specimens. """ def __init__(self, scanned_data=None): self.face2ref_dist = None self.ref_plane = None super().__init__(scanned_data) def fit_plane(self): """ Fit a plane on the scanned data. The Plane3D object is assigned in the `self.ref_plane`. The fitted plane is returned using the analytic_geometry.lstsq_planar_fit with the optional argument lay_on_xy=True. See analytic_geometry.lstsq_planar_fit documentation. """ self.ref_plane = ag.Plane3D.from_fitting(self.scanned_data, lay_on_xy=True) def offset_face(self, offset, offset_points=False): """ Offset the plane and (optionally) the scanned data points. Useful for translating translating the scanned surface to the mid line. :param offset: :param offset_points: :return: """ self.ref_plane.offset_plane(offset) if offset_points: point_list = [ag.Point3D(p.coords + self.ref_plane.plane_coeff[:3] * offset) for p in self.scanned_data] self.scanned_data = np.array(point_list) def calc_face2ref_dist(self): """Calculates distances from facet points to the reference plane.""" if self.ref_plane: self.face2ref_dist = [] for x in self.scanned_data: self.face2ref_dist.append(x.distance_to_plane(self.ref_plane)) def plot_face(self, fig=None, reduced=None): """ Surface plotter. Plot the 3d points and the fitted plane. Parameters ---------- fig : Object of class matplotlib.figure.Figure, optional The figure window to be used for plotting. By default, a new window is created. reduced: float, optional A reduced randomly selected subset of points is plotted (in case the data is too dense for plotting). The rediced size is given as a ratio of the total number of points, e.g `reduced=0.5` plots half the points. By default, all points are plotted. """ # Average and range of the points. self.centre_size() x_lims = [self.centre[0] - self.size[0] / 2., self.centre[0] + self.size[0] / 2.] y_lims = [self.centre[1] - self.size[1] / 2., self.centre[1] + self.size[1] / 2.] x, y = np.meshgrid(x_lims, y_lims) # evaluate the plane function on the grid. z = self.ref_plane.z_return(x, y) # or expressed using matrix/vector product # z = np.dot(np.c_[xx, yy, np.ones(xx.shape)], self.plane_coeff).reshape(x.shape) plot_dim = max(self.size[0], self.size[1], self.size[2]) # Quadratic:evaluate it on a grid # z = np.dot(np.c_[np.ones(xx.shape), xx, yy, xx * yy, xx ** 2, yy ** 2], self.plane_coeff).reshape(x.shape) # Get a figure to plot on if fig is None: fig = plt.figure() ax = Axes3D(fig) else: ax = fig.get_axes()[0] # Plot the plane ax.plot_surface(x, y, z, rstride=1, cstride=1, alpha=0.2) # Make a randomly selected subset of points acc. to the input arg 'reduced=x'. if isinstance(reduced, float) and (0 < reduced < 1): i = np.random.choice( len(self.scanned_data[:, 0]), size=round(len(self.scanned_data[:, 0]) * reduced), replace=False ) else: i = range(0, len(self.scanned_data[:, 0])) # Plot the points ax.scatter(self.scanned_data[i, 0], self.scanned_data[i, 1], self.scanned_data[i, 2], c='r', s=50) plt.xlabel('x') plt.ylabel('y') ax.set_zlabel('z') ax.set_xlim3d(self.centre[0] - plot_dim / 2, self.centre[0] + plot_dim / 2) ax.set_ylim3d(self.centre[1] - plot_dim / 2, self.centre[1] + plot_dim / 2) ax.set_zlim3d(self.centre[2] - plot_dim / 2, self.centre[2] + plot_dim / 2) # ax.axis('tight') plt.show() # Return the figure handle. return fig class RoundedEdge(Scan3D): """ A scanned rounded edge. """ def __init__(self, scanned_data=None): self.theoretical_edge = None self.edge_points = None self.circles = None self.edge2ref_dist = None self.ref_line = None super().__init__(scanned_data) def add_theoretical_edge(self, line): """ Add a reference line for the edge. Useful when the rounded edge lies between flat faces and the theoretical edge is at their intersection. Parameters ---------- line : Line3D Theoretical edge line to be added. This line should be calculated as the intersection of the facets sharing this edge. """ if isinstance(line, ag.Line3D): self.theoretical_edge = line else: print("ref_line must be Line3D") return NotImplemented def fit_circles(self, axis=None, offset=None): """ Fit a series of circles along the length of the rounded edge. The scanned data are first grouped together based on their z-coordinate ant then a horizontal circle is fitted for each group of points. :return: """ if axis is None: axis = 0 if offset is None: offset = 0 self.quantize(axis=axis) self.circles = [] for x in self.grouped_data: self.circles.append(ag.Circle2D.from_fitting(x)) self.circles[-1].radius = self.circles[-1].radius + offset # TODO: Docstrings parameters... def calc_edge_points(self, other): """ Intersect scanned points with a surface between the reference line and a given line. This function is used to find points on the scanned rounded corner. Circles are fitted on the scanned points on different positions. Then the circles are intersected with the line passing through the reference line of the edge and another given line (e.g. the centre of the column). A list of points is generated which represent the real edge of rounded corner. :param other: :return: """ if isinstance(other, ag.Line3D): self.edge_points = [] # Loop through the circles that represent the edge roundness at different heights. for circle in self.circles: # Get the z-coordinate (height) of the current point z_current = circle.points[0].coords[2] #print('Finding edge point at height {}'.format(z_current)) # Get the x-y coordinates of the edge reference line and the mid-line for the given height, z. ref_line_point = self.theoretical_edge.xy_for_z(z_current) other_line_point = other.xy_for_z(z_current) # Create a temporary line object from the two points. intersection_line = ag.Line2D.from_2_points(ref_line_point[:2], other_line_point[:2]) # Intersect this temporary line with the current circle. line_circle_intersection = circle.intersect_with_line(intersection_line) # If the line does not intersect with the current circle, print on screen and continue. if line_circle_intersection is None: print("Line and circle at height {} do not intersect. Point ignored.".format(z_current)) else: # If the line intersects with the circle, select the outermost of the two intersection points. if np.linalg.norm(line_circle_intersection[0]) > np.linalg.norm(line_circle_intersection[1]): outer = line_circle_intersection[0] else: outer = line_circle_intersection[1] # Append the point to the list of edge_points self.edge_points.append(ag.Point3D(np.append(outer, z_current))) else: print('The input object is not of the class `Line3D`') return NotImplemented def calc_ref_line(self): """ Calculate the reference line. The reference line for the edge is defined as the best fit straight line to the edge points. For more information on the edge points, see the `intersect_data` method. """ self.ref_line = ag.Line3D.from_fitting(self.edge_points) def calc_edge2ref_dist(self): """Calculate distances of edge points to the reference line.""" if self.ref_line and not self.ref_line is NotImplemented: self.edge2ref_dist = [] for x in self.edge_points: self.edge2ref_dist.append(x.distance_to_line(self.theoretical_edge)) else: print('No reference line. First, add a reference line to the object. Check if the fitting process on the ' 'edge points converged. Edge ignored.') return NotImplemented def main(): print('Module successfully loaded.') if __name__ == "__main__": main()
en
0.81665
# -*- coding: utf-8 -*- Module containing methods related to 3D scanning. 3D model data. Class of 3D objects. Can be imported from an .stl file of a .txt file of list of node coordinates. Import stl file. Alternative constructor, creates a Scan3D object by reading data from an .stl file. In case the file is created by Creaform's software (it is detected using name of the solid object as described in it's frist line), it is corrected accordingly before importing. The original file is renamed by adding '_old' before the extension or they can be deleted automatically if specified so. Parameters ---------- fh : str File path. del_original : bool, optional Keep or delete the original file. Default is keep. # Repair the file format Method for importing a pickle file containing x, y, z, coordinates. Used to import data exported from blender. The pickle file is should contain a list of lists. Method reading text files containing x, y, z coordinates. Used to import data from 3D scanning files. # Open the requested file. # Number of points. # Initialise a numpy array for the values. # Reset the file read cursor and loop over the lines of the file populating the numpy array. Repair header-footer of files created by Creaform's package. The .stl files created by Creaform's software are missing standard .stl header and footer. This method will create a copy of the requested file with proper header-footer using the filename (without the extension) as a name of the solid. Parameters ---------- fh : str File path. del_original : bool, optional Keep or delete the original file. Default is keep. Convert an array of coordinates to a list of Point3D objects. Parameters ---------- array : {n*3} np.ndarray Returns ------- list of Point3D. # TODO:Docstring... Sort scanned data. The scanned points are sorted for a given axis. :param axis: :return: # TODO:Docstring... Group the scanned data. The points with difference on a given axis smaller than the tolerance are grouped together and stored in a list in the attribute `grouped_data`. :param axis: :param tolerance: :return: Get the centre and the range of the data points. Used in combination with the plotting methods to define the bounding box. # Bounding box of the points. # TODO: fix: the method stopped working after the Point3D implementation. Currently commented. # def plot_surf(self): # """ # Method plotting the model as a 3D surface. # """ # # Create the x, y, z numpy # x = [i[0] for i in self.scanned_data] # y = [i[1] for i in self.scanned_data] # z = [i[2] for i in self.scanned_data] # # # Create a figure. # fig = plt.figure() # ax = fig.gca(projection='3d') # # # Plot the data # ax.plot_trisurf(x, y, z) Subclass of the Scan3D class, specifically for flat faces. Used for the individual faces of the polygonal specimens. Fit a plane on the scanned data. The Plane3D object is assigned in the `self.ref_plane`. The fitted plane is returned using the analytic_geometry.lstsq_planar_fit with the optional argument lay_on_xy=True. See analytic_geometry.lstsq_planar_fit documentation. Offset the plane and (optionally) the scanned data points. Useful for translating translating the scanned surface to the mid line. :param offset: :param offset_points: :return: Calculates distances from facet points to the reference plane. Surface plotter. Plot the 3d points and the fitted plane. Parameters ---------- fig : Object of class matplotlib.figure.Figure, optional The figure window to be used for plotting. By default, a new window is created. reduced: float, optional A reduced randomly selected subset of points is plotted (in case the data is too dense for plotting). The rediced size is given as a ratio of the total number of points, e.g `reduced=0.5` plots half the points. By default, all points are plotted. # Average and range of the points. # evaluate the plane function on the grid. # or expressed using matrix/vector product # z = np.dot(np.c_[xx, yy, np.ones(xx.shape)], self.plane_coeff).reshape(x.shape) # Quadratic:evaluate it on a grid # z = np.dot(np.c_[np.ones(xx.shape), xx, yy, xx * yy, xx ** 2, yy ** 2], self.plane_coeff).reshape(x.shape) # Get a figure to plot on # Plot the plane # Make a randomly selected subset of points acc. to the input arg 'reduced=x'. # Plot the points # ax.axis('tight') # Return the figure handle. A scanned rounded edge. Add a reference line for the edge. Useful when the rounded edge lies between flat faces and the theoretical edge is at their intersection. Parameters ---------- line : Line3D Theoretical edge line to be added. This line should be calculated as the intersection of the facets sharing this edge. Fit a series of circles along the length of the rounded edge. The scanned data are first grouped together based on their z-coordinate ant then a horizontal circle is fitted for each group of points. :return: # TODO: Docstrings parameters... Intersect scanned points with a surface between the reference line and a given line. This function is used to find points on the scanned rounded corner. Circles are fitted on the scanned points on different positions. Then the circles are intersected with the line passing through the reference line of the edge and another given line (e.g. the centre of the column). A list of points is generated which represent the real edge of rounded corner. :param other: :return: # Loop through the circles that represent the edge roundness at different heights. # Get the z-coordinate (height) of the current point #print('Finding edge point at height {}'.format(z_current)) # Get the x-y coordinates of the edge reference line and the mid-line for the given height, z. # Create a temporary line object from the two points. # Intersect this temporary line with the current circle. # If the line does not intersect with the current circle, print on screen and continue. # If the line intersects with the circle, select the outermost of the two intersection points. # Append the point to the list of edge_points Calculate the reference line. The reference line for the edge is defined as the best fit straight line to the edge points. For more information on the edge points, see the `intersect_data` method. Calculate distances of edge points to the reference line.
2.939959
3
microquake/processors/clean_data.py
jeanphilippemercier/microquake
0
6612743
from microquake.processors.processing_unit import ProcessingUnit from microquake.core.stream import Stream from loguru import logger import numpy as np from microquake.core.settings import settings class Processor(ProcessingUnit): @property def module_name(self): return "clean_data" def process(self, **kwargs): """ Process event and returns its classification. """ waveform = kwargs["waveform"] black_list = settings.get('sensors').black_list starttime = waveform[0].stats.starttime endtime = waveform[0].stats.endtime inventory = self.settings.inventory for tr in waveform: if tr.stats.starttime < starttime: starttime = tr.stats.starttime if tr.stats.endtime > endtime: endtime = tr.stats.endtime waveform.trim(starttime, endtime, pad=True, fill_value=0) trs = [] for i, tr in enumerate(waveform): if inventory.select(tr.stats.station) is None: continue if tr.stats.station not in black_list: if np.any(np.isnan(tr.data)): continue if np.sum(tr.data ** 2) > 0: trs.append(tr) logger.info('The seismograms have been cleaned, %d trace remaining' % len(trs)) return Stream(traces=trs) # def legacy_pipeline_handler(self, msg_in, res): # """ # legacy pipeline handler # """ # cat, waveform = self.app.deserialise_message(msg_in) # cat = self.output_catalog(cat) # return cat, waveform
from microquake.processors.processing_unit import ProcessingUnit from microquake.core.stream import Stream from loguru import logger import numpy as np from microquake.core.settings import settings class Processor(ProcessingUnit): @property def module_name(self): return "clean_data" def process(self, **kwargs): """ Process event and returns its classification. """ waveform = kwargs["waveform"] black_list = settings.get('sensors').black_list starttime = waveform[0].stats.starttime endtime = waveform[0].stats.endtime inventory = self.settings.inventory for tr in waveform: if tr.stats.starttime < starttime: starttime = tr.stats.starttime if tr.stats.endtime > endtime: endtime = tr.stats.endtime waveform.trim(starttime, endtime, pad=True, fill_value=0) trs = [] for i, tr in enumerate(waveform): if inventory.select(tr.stats.station) is None: continue if tr.stats.station not in black_list: if np.any(np.isnan(tr.data)): continue if np.sum(tr.data ** 2) > 0: trs.append(tr) logger.info('The seismograms have been cleaned, %d trace remaining' % len(trs)) return Stream(traces=trs) # def legacy_pipeline_handler(self, msg_in, res): # """ # legacy pipeline handler # """ # cat, waveform = self.app.deserialise_message(msg_in) # cat = self.output_catalog(cat) # return cat, waveform
en
0.392573
Process event and returns its classification. # def legacy_pipeline_handler(self, msg_in, res): # """ # legacy pipeline handler # """ # cat, waveform = self.app.deserialise_message(msg_in) # cat = self.output_catalog(cat) # return cat, waveform
2.360741
2
dayone.py
lardissone/DayOneLogger
7
6612744
<filename>dayone.py #!/usr/bin/env python """ DayOneLogger - Log anything you add to a folder to Day One Author: <NAME> <<EMAIL>> More Info: https://github.com/lardissone/DayOneLogger """ import os import sys import uuid import plistlib import platform import arrow from utils import get_dropbox_path, get_icloud_path import services as sources # Settings ------- IFTTT_DIR = os.path.expanduser('~/Dropbox/IFTTT/DayOneLogger') # Dropbox: DAYONE_DIR = get_dropbox_path() # iCloud: # DAYONE_DIR = get_icloud_path() SERVICES = [ 'github', 'reminders', 'tweets', 'movies', 'places', 'tracks', 'wakatime', 'todoist' ] # TODO: find a way to get `tzlocal` working on OSX to get these values TIME_ZONE = 'America/Argentina/Buenos_Aires' TIME_ZONE_OFFSET = 3 ENTRY_TAGS = ['daily'] # ---------------- DEBUG = False # if True, it doesn't writes to Day One LOCAL_PATH = os.path.dirname(os.path.realpath(__file__)) SYNC_FILE = os.path.join(LOCAL_PATH, '.last_sync') try: if not DEBUG: with open(SYNC_FILE) as f: LAST_SYNC = f.read() else: LAST_SYNC = str(arrow.now().replace(weeks=-1)) except IOError: LAST_SYNC = str(arrow.get('2001-01-01').datetime) class DayOneLogger(object): data = { 'days': [], 'entries': {} } services_titles = { 'places': '### Places', 'github': '### Github', 'reminders': '### Reminders', 'movies': '### Movies', 'tracks': '### Loved tracks', 'tweets': '### Tweets', 'wakatime': '### Coding stats', 'todoist': '### Todoist completed tasks', } services_used = [] def __init__(self, last_sync): self.last_sync = arrow.get(last_sync).datetime def _group_by_day(self, entries): for e in entries: day = e['date'].date() if day not in self.data['days']: self.data['days'].append(day) self.data['entries'][day] = {} if not e['service'] in self.data['entries'][day]: self.data['entries'][day][e['service']] = [] self.data['entries'][day][e['service']].append(e) def _generate_markdown(self): """ Generates a single markdown output for all entries """ self.data['md'] = {} for day in sorted(self.data['days']): if day in self.data['entries']: title = '# Things done on %s' md = [title % arrow.get(day).format('MMMM DD, YYYY')] entries = self.data['entries'][day] for service in self.services_used: if service in entries: md += ['', self.services_titles[service]] sorted_list = sorted( entries[service], key=lambda k: k['date'] ) md += [m['md'] for m in sorted_list] md += [''] * 2 self.data['md'][day] = '\n'.join(x.decode('utf-8') for x in md) def _save_to_day_one(self): for day in sorted(self.data['days'])[:-1]: #for day in sorted(self.data['days']): uuid_val = uuid.uuid1().hex.upper() utc_time = arrow.utcnow() filename = os.path.join(DAYONE_DIR, uuid_val + ".doentry") now = arrow.now() entry_date = arrow.get(day) entry_date = entry_date.replace(hour=now.hour, minute=now.minute) entry_date = entry_date.replace(hours=TIME_ZONE_OFFSET).datetime entry_plist = { 'Creation Date': entry_date, 'Starred': False, 'Entry Text': self.data['md'][day], 'Time Zone': TIME_ZONE, 'UUID': uuid_val, 'Tags': ENTRY_TAGS, 'Creator': { 'Device Agent': platform.uname()[0], 'Generation Date': utc_time.datetime, 'Host Name': platform.node(), 'OS Agent': platform.platform(), 'Software Agent': 'DayOneLogger' } } if not DEBUG: plistlib.writePlist(entry_plist, filename) def process(self, services, markdown=True, save=True): entries = [] self.services_used = services for service in services: source = __import__('services.%s' % service) source = getattr(sources, service) s = getattr(source, service)(IFTTT_DIR, LAST_SYNC, DEBUG) entries += s.parse() if not entries: print 'nothing to process this time...' sys.exit() self._group_by_day(entries) if markdown: self._generate_markdown() if save: self._save_to_day_one() last_entry = arrow.now().replace( days=-1, hour=23, minute=59, second=59) if not DEBUG: with open(SYNC_FILE, 'w') as f: f.write(str(last_entry.datetime)) if __name__ == '__main__': do = DayOneLogger(LAST_SYNC) do.process(SERVICES)
<filename>dayone.py #!/usr/bin/env python """ DayOneLogger - Log anything you add to a folder to Day One Author: <NAME> <<EMAIL>> More Info: https://github.com/lardissone/DayOneLogger """ import os import sys import uuid import plistlib import platform import arrow from utils import get_dropbox_path, get_icloud_path import services as sources # Settings ------- IFTTT_DIR = os.path.expanduser('~/Dropbox/IFTTT/DayOneLogger') # Dropbox: DAYONE_DIR = get_dropbox_path() # iCloud: # DAYONE_DIR = get_icloud_path() SERVICES = [ 'github', 'reminders', 'tweets', 'movies', 'places', 'tracks', 'wakatime', 'todoist' ] # TODO: find a way to get `tzlocal` working on OSX to get these values TIME_ZONE = 'America/Argentina/Buenos_Aires' TIME_ZONE_OFFSET = 3 ENTRY_TAGS = ['daily'] # ---------------- DEBUG = False # if True, it doesn't writes to Day One LOCAL_PATH = os.path.dirname(os.path.realpath(__file__)) SYNC_FILE = os.path.join(LOCAL_PATH, '.last_sync') try: if not DEBUG: with open(SYNC_FILE) as f: LAST_SYNC = f.read() else: LAST_SYNC = str(arrow.now().replace(weeks=-1)) except IOError: LAST_SYNC = str(arrow.get('2001-01-01').datetime) class DayOneLogger(object): data = { 'days': [], 'entries': {} } services_titles = { 'places': '### Places', 'github': '### Github', 'reminders': '### Reminders', 'movies': '### Movies', 'tracks': '### Loved tracks', 'tweets': '### Tweets', 'wakatime': '### Coding stats', 'todoist': '### Todoist completed tasks', } services_used = [] def __init__(self, last_sync): self.last_sync = arrow.get(last_sync).datetime def _group_by_day(self, entries): for e in entries: day = e['date'].date() if day not in self.data['days']: self.data['days'].append(day) self.data['entries'][day] = {} if not e['service'] in self.data['entries'][day]: self.data['entries'][day][e['service']] = [] self.data['entries'][day][e['service']].append(e) def _generate_markdown(self): """ Generates a single markdown output for all entries """ self.data['md'] = {} for day in sorted(self.data['days']): if day in self.data['entries']: title = '# Things done on %s' md = [title % arrow.get(day).format('MMMM DD, YYYY')] entries = self.data['entries'][day] for service in self.services_used: if service in entries: md += ['', self.services_titles[service]] sorted_list = sorted( entries[service], key=lambda k: k['date'] ) md += [m['md'] for m in sorted_list] md += [''] * 2 self.data['md'][day] = '\n'.join(x.decode('utf-8') for x in md) def _save_to_day_one(self): for day in sorted(self.data['days'])[:-1]: #for day in sorted(self.data['days']): uuid_val = uuid.uuid1().hex.upper() utc_time = arrow.utcnow() filename = os.path.join(DAYONE_DIR, uuid_val + ".doentry") now = arrow.now() entry_date = arrow.get(day) entry_date = entry_date.replace(hour=now.hour, minute=now.minute) entry_date = entry_date.replace(hours=TIME_ZONE_OFFSET).datetime entry_plist = { 'Creation Date': entry_date, 'Starred': False, 'Entry Text': self.data['md'][day], 'Time Zone': TIME_ZONE, 'UUID': uuid_val, 'Tags': ENTRY_TAGS, 'Creator': { 'Device Agent': platform.uname()[0], 'Generation Date': utc_time.datetime, 'Host Name': platform.node(), 'OS Agent': platform.platform(), 'Software Agent': 'DayOneLogger' } } if not DEBUG: plistlib.writePlist(entry_plist, filename) def process(self, services, markdown=True, save=True): entries = [] self.services_used = services for service in services: source = __import__('services.%s' % service) source = getattr(sources, service) s = getattr(source, service)(IFTTT_DIR, LAST_SYNC, DEBUG) entries += s.parse() if not entries: print 'nothing to process this time...' sys.exit() self._group_by_day(entries) if markdown: self._generate_markdown() if save: self._save_to_day_one() last_entry = arrow.now().replace( days=-1, hour=23, minute=59, second=59) if not DEBUG: with open(SYNC_FILE, 'w') as f: f.write(str(last_entry.datetime)) if __name__ == '__main__': do = DayOneLogger(LAST_SYNC) do.process(SERVICES)
en
0.532644
#!/usr/bin/env python DayOneLogger - Log anything you add to a folder to Day One Author: <NAME> <<EMAIL>> More Info: https://github.com/lardissone/DayOneLogger # Settings ------- # Dropbox: # iCloud: # DAYONE_DIR = get_icloud_path() # TODO: find a way to get `tzlocal` working on OSX to get these values # ---------------- # if True, it doesn't writes to Day One ## Places', ## Github', ## Reminders', ## Movies', ## Loved tracks', ## Tweets', ## Coding stats', ## Todoist completed tasks', Generates a single markdown output for all entries #for day in sorted(self.data['days']):
2.509091
3
search/models.py
rajeshwariC/WeVoteServer
0
6612745
# search/models.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from ballot.models import BallotReturnedManager from config.base import get_environment_variable from candidate.models import CandidateCampaign from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from elasticsearch import Elasticsearch from election.models import Election from measure.models import ContestMeasure from office.models import ContestOffice from organization.models import Organization import wevote_functions.admin from wevote_functions.functions import positive_value_exists logger = wevote_functions.admin.get_logger(__name__) STATE_CODE_MAP = { 'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas', 'AS': 'American Samoa', 'AZ': 'Arizona', 'CA': 'California', 'CO': 'Colorado', 'CT': 'Connecticut', 'DC': 'District of Columbia', 'DE': 'Delaware', 'FL': 'Florida', 'GA': 'Georgia', 'GU': 'Guam', 'HI': 'Hawaii', 'IA': 'Iowa', 'ID': 'Idaho', 'IL': 'Illinois', 'IN': 'Indiana', 'KS': 'Kansas', 'KY': 'Kentucky', 'LA': 'Louisiana', 'MA': 'Massachusetts', 'MD': 'Maryland', 'ME': 'Maine', 'MI': 'Michigan', 'MN': 'Minnesota', 'MO': 'Missouri', 'MP': 'Northern Mariana Islands', 'MS': 'Mississippi', 'MT': 'Montana', 'NA': 'National', 'NC': 'North Carolina', 'ND': 'North Dakota', 'NE': 'Nebraska', 'NH': 'New Hampshire', 'NJ': 'New Jersey', 'NM': 'New Mexico', 'NV': 'Nevada', 'NY': 'New York', 'OH': 'Ohio', 'OK': 'Oklahoma', 'OR': 'Oregon', 'PA': 'Pennsylvania', 'PR': 'Puerto Rico', 'RI': 'Rhode Island', 'SC': 'South Carolina', 'SD': 'South Dakota', 'TN': 'Tennessee', 'TX': 'Texas', 'UT': 'Utah', 'VA': 'Virginia', 'VI': 'Virgin Islands', 'VT': 'Vermont', 'WA': 'Washington', 'WI': 'Wisconsin', 'WV': 'West Virginia', 'WY': 'Wyoming', } def convert_state_code_to_state_text(incoming_state_code): for state_code, state_name in STATE_CODE_MAP.items(): if incoming_state_code.lower() == state_code.lower(): return state_name else: return "" ELASTIC_SEARCH_CONNECTION_STRING = get_environment_variable("ELASTIC_SEARCH_CONNECTION_STRING") if positive_value_exists(ELASTIC_SEARCH_CONNECTION_STRING): elastic_search_object = Elasticsearch( [ELASTIC_SEARCH_CONNECTION_STRING], timeout=2, max_retries=2, retry_on_timeout=True, maxsize=100 ) # CandidateCampaign @receiver(post_save, sender=CandidateCampaign) def save_candidate_campaign_signal(sender, instance, **kwargs): # logger.debug("search.save_candidate_campaign_signal") if 'elastic_search_object' in globals(): doc = { "candidate_name": instance.candidate_name, "candidate_twitter_handle": instance.candidate_twitter_handle, "twitter_name": instance.twitter_name, "party": instance.party, "google_civic_election_id": instance.google_civic_election_id, "state_code": instance.state_code, "we_vote_id": instance.we_vote_id } try: res = elastic_search_object.index(index="candidates", doc_type='candidate', id=instance.id, body=doc) if res["_shards"]["successful"] <= 1: logger.error("failed to index CandidateCampaign " + str(instance.we_vote_id)) except Exception as err: status = "SAVE_CANDIDATE_CAMPAIGN_SIGNAL, err: " + str(err) logger.error(status) @receiver(post_delete, sender=CandidateCampaign) def delete_candidate_campaign_signal(sender, instance, **kwargs): # logger.debug("search.delete_CandidateCampaign_signal") if 'elastic_search_object' in globals(): try: res = elastic_search_object.delete(index="candidates", doc_type='candidate', id=instance.id) if res["_shards"]["successful"] <= 1: logger.error("failed to delete CandidateCampaign " + str(instance.we_vote_id)) except Exception as err: status = "DELETE_CANDIDATE_CAMPAIGN_SIGNAL, err: " + str(err) logger.error(status) # ContestMeasure @receiver(post_save, sender=ContestMeasure) def save_contest_measure_signal(sender, instance, **kwargs): # logger.debug("search.save_ContestMeasure_signal") if 'elastic_search_object' in globals(): doc = { "we_vote_id": instance.we_vote_id, "measure_subtitle": instance.measure_subtitle, "measure_text": instance.measure_text, "measure_title": instance.measure_title, "google_civic_election_id": instance.google_civic_election_id, "state_code": instance.state_code } try: res = elastic_search_object.index(index="measures", doc_type='measure', id=instance.id, body=doc) if res["_shards"]["successful"] <= 1: logger.error("failed to index ContestMeasure " + str(instance.we_vote_id)) except Exception as err: status = "SAVE_CONTEST_MEASURE_SIGNAL, err: " + str(err) logger.error(status) @receiver(post_delete, sender=ContestMeasure) def delete_contest_measure_signal(sender, instance, **kwargs): # logger.debug("search.delete_ContestMeasure_signal") if 'elastic_search_object' in globals(): try: res = elastic_search_object.delete(index="measures", doc_type='measure', id=instance.id) if res["_shards"]["successful"] <= 1: logger.error("failed to delete ContestMeasure " + str(instance.we_vote_id)) except Exception as err: status = "DELETE_CONTEST_MEASURE_SIGNAL, err: " + str(err) logger.error(status) # ContestOffice @receiver(post_save, sender=ContestOffice) def save_contest_office_signal(sender, instance, **kwargs): # logger.debug("search.save_ContestOffice_signal") if 'elastic_search_object' in globals(): doc = { "we_vote_id": instance.we_vote_id, "office_name": instance.office_name, "google_civic_election_id": instance.google_civic_election_id, "state_code": instance.state_code } try: res = elastic_search_object.index(index="offices", doc_type='office', id=instance.id, body=doc) if res["_shards"]["successful"] <= 1: logger.error("failed to index ContestOffice " + str(instance.we_vote_id)) except Exception as err: status = "SAVE_CONTEST_OFFICE_SIGNAL, err: " + str(err) logger.error(status) @receiver(post_delete, sender=ContestOffice) def delete_contest_office_signal(sender, instance, **kwargs): # logger.debug("search.delete_ContestOffice_signal") if 'elastic_search_object' in globals(): try: res = elastic_search_object.delete(index="offices", doc_type='office', id=instance.id) if res["_shards"]["successful"] <= 1: logger.error("failed to delete ContestOffice " + str(instance.we_vote_id)) except Exception as err: status = "DELETE_CONTEST_OFFICE_SIGNAL, err: " + str(err) logger.error(status) # Election @receiver(post_save, sender=Election) def save_election_signal(sender, instance, **kwargs): # logger.debug("search.save_Election_signal") if 'elastic_search_object' in globals(): ballot_returned_manager = BallotReturnedManager() if ballot_returned_manager.should_election_search_data_be_saved(instance.google_civic_election_id): doc = { "election_name": instance.election_name, "election_day_text": instance.election_day_text, "google_civic_election_id": instance.google_civic_election_id, "state_code": instance.state_code, "state_name": convert_state_code_to_state_text(instance.state_code) } try: res = elastic_search_object.index(index="elections", doc_type='election', id=instance.id, body=doc) if res["_shards"]["successful"] <= 1: logger.error("failed to index Election " + str(instance.election_name)) except Exception as err: status = "SAVE_ELECTION_SIGNAL, err: " + str(err) logger.error(status) else: try: res = elastic_search_object.delete(index="elections", doc_type='election', id=instance.id) if res["_shards"]["successful"] <= 1: logger.error("failed to delete1 Election " + str(instance.election_name)) except Exception as err: status = "DELETE_ELECTION_SIGNAL1, err: " + str(err) logger.error(status) @receiver(post_delete, sender=Election) def delete_election_signal(sender, instance, **kwargs): # logger.debug("search.delete_Election_signal") if 'elastic_search_object' in globals(): try: res = elastic_search_object.delete(index="elections", doc_type='election', id=instance.id) if res["_shards"]["successful"] <= 1: logger.error("failed to delete2 Election " + str(instance.election_name)) except Exception as err: status = "DELETE_ELECTION_SIGNAL2, err: " + str(err) logger.error(status) # Organization @receiver(post_save, sender=Organization) def save_organization_signal(sender, instance, **kwargs): # logger.debug("search.save_Organization_signal") if 'elastic_search_object' in globals(): doc = { "we_vote_id": instance.we_vote_id, "organization_name": instance.organization_name, "organization_twitter_handle": instance.organization_twitter_handle, "organization_website": instance.organization_website, "twitter_description": instance.twitter_description, "state_served_code": instance.state_served_code, } try: res = elastic_search_object.index(index="organizations", doc_type='organization', id=instance.id, body=doc) if res["_shards"]["successful"] <= 1: logger.error("failed to index Organization " + str(instance.we_vote_id)) except Exception as err: status = "SAVE_ORGANIZATION_SIGNAL, err: " + str(err) logger.error(status) @receiver(post_delete, sender=Organization) def delete_organization_signal(sender, instance, **kwargs): # logger.debug("search.delete_Organization_signal") if 'elastic_search_object' in globals(): try: res = elastic_search_object.delete(index="organizations", doc_type='organization', id=instance.id) if res["_shards"]["successful"] <= 1: logger.error("failed to delete Organization " + str(instance.we_vote_id)) except Exception as err: status = "DELETE_ORGANIZATION_SIGNAL, err: " + str(err) logger.error(status) # @receiver(post_save) # def save_signal(sender, **kwargs): # print("### save") # # @receiver(post_delete) # def delete_signal(sender, **kwargs): # print("### delete") # # from django.core.signals import request_finished # @receiver(request_finished) # def request_signal(sender, **kwargs): # print("> request!") # # print("Signals Up")
# search/models.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from ballot.models import BallotReturnedManager from config.base import get_environment_variable from candidate.models import CandidateCampaign from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from elasticsearch import Elasticsearch from election.models import Election from measure.models import ContestMeasure from office.models import ContestOffice from organization.models import Organization import wevote_functions.admin from wevote_functions.functions import positive_value_exists logger = wevote_functions.admin.get_logger(__name__) STATE_CODE_MAP = { 'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas', 'AS': 'American Samoa', 'AZ': 'Arizona', 'CA': 'California', 'CO': 'Colorado', 'CT': 'Connecticut', 'DC': 'District of Columbia', 'DE': 'Delaware', 'FL': 'Florida', 'GA': 'Georgia', 'GU': 'Guam', 'HI': 'Hawaii', 'IA': 'Iowa', 'ID': 'Idaho', 'IL': 'Illinois', 'IN': 'Indiana', 'KS': 'Kansas', 'KY': 'Kentucky', 'LA': 'Louisiana', 'MA': 'Massachusetts', 'MD': 'Maryland', 'ME': 'Maine', 'MI': 'Michigan', 'MN': 'Minnesota', 'MO': 'Missouri', 'MP': 'Northern Mariana Islands', 'MS': 'Mississippi', 'MT': 'Montana', 'NA': 'National', 'NC': 'North Carolina', 'ND': 'North Dakota', 'NE': 'Nebraska', 'NH': 'New Hampshire', 'NJ': 'New Jersey', 'NM': 'New Mexico', 'NV': 'Nevada', 'NY': 'New York', 'OH': 'Ohio', 'OK': 'Oklahoma', 'OR': 'Oregon', 'PA': 'Pennsylvania', 'PR': 'Puerto Rico', 'RI': 'Rhode Island', 'SC': 'South Carolina', 'SD': 'South Dakota', 'TN': 'Tennessee', 'TX': 'Texas', 'UT': 'Utah', 'VA': 'Virginia', 'VI': 'Virgin Islands', 'VT': 'Vermont', 'WA': 'Washington', 'WI': 'Wisconsin', 'WV': 'West Virginia', 'WY': 'Wyoming', } def convert_state_code_to_state_text(incoming_state_code): for state_code, state_name in STATE_CODE_MAP.items(): if incoming_state_code.lower() == state_code.lower(): return state_name else: return "" ELASTIC_SEARCH_CONNECTION_STRING = get_environment_variable("ELASTIC_SEARCH_CONNECTION_STRING") if positive_value_exists(ELASTIC_SEARCH_CONNECTION_STRING): elastic_search_object = Elasticsearch( [ELASTIC_SEARCH_CONNECTION_STRING], timeout=2, max_retries=2, retry_on_timeout=True, maxsize=100 ) # CandidateCampaign @receiver(post_save, sender=CandidateCampaign) def save_candidate_campaign_signal(sender, instance, **kwargs): # logger.debug("search.save_candidate_campaign_signal") if 'elastic_search_object' in globals(): doc = { "candidate_name": instance.candidate_name, "candidate_twitter_handle": instance.candidate_twitter_handle, "twitter_name": instance.twitter_name, "party": instance.party, "google_civic_election_id": instance.google_civic_election_id, "state_code": instance.state_code, "we_vote_id": instance.we_vote_id } try: res = elastic_search_object.index(index="candidates", doc_type='candidate', id=instance.id, body=doc) if res["_shards"]["successful"] <= 1: logger.error("failed to index CandidateCampaign " + str(instance.we_vote_id)) except Exception as err: status = "SAVE_CANDIDATE_CAMPAIGN_SIGNAL, err: " + str(err) logger.error(status) @receiver(post_delete, sender=CandidateCampaign) def delete_candidate_campaign_signal(sender, instance, **kwargs): # logger.debug("search.delete_CandidateCampaign_signal") if 'elastic_search_object' in globals(): try: res = elastic_search_object.delete(index="candidates", doc_type='candidate', id=instance.id) if res["_shards"]["successful"] <= 1: logger.error("failed to delete CandidateCampaign " + str(instance.we_vote_id)) except Exception as err: status = "DELETE_CANDIDATE_CAMPAIGN_SIGNAL, err: " + str(err) logger.error(status) # ContestMeasure @receiver(post_save, sender=ContestMeasure) def save_contest_measure_signal(sender, instance, **kwargs): # logger.debug("search.save_ContestMeasure_signal") if 'elastic_search_object' in globals(): doc = { "we_vote_id": instance.we_vote_id, "measure_subtitle": instance.measure_subtitle, "measure_text": instance.measure_text, "measure_title": instance.measure_title, "google_civic_election_id": instance.google_civic_election_id, "state_code": instance.state_code } try: res = elastic_search_object.index(index="measures", doc_type='measure', id=instance.id, body=doc) if res["_shards"]["successful"] <= 1: logger.error("failed to index ContestMeasure " + str(instance.we_vote_id)) except Exception as err: status = "SAVE_CONTEST_MEASURE_SIGNAL, err: " + str(err) logger.error(status) @receiver(post_delete, sender=ContestMeasure) def delete_contest_measure_signal(sender, instance, **kwargs): # logger.debug("search.delete_ContestMeasure_signal") if 'elastic_search_object' in globals(): try: res = elastic_search_object.delete(index="measures", doc_type='measure', id=instance.id) if res["_shards"]["successful"] <= 1: logger.error("failed to delete ContestMeasure " + str(instance.we_vote_id)) except Exception as err: status = "DELETE_CONTEST_MEASURE_SIGNAL, err: " + str(err) logger.error(status) # ContestOffice @receiver(post_save, sender=ContestOffice) def save_contest_office_signal(sender, instance, **kwargs): # logger.debug("search.save_ContestOffice_signal") if 'elastic_search_object' in globals(): doc = { "we_vote_id": instance.we_vote_id, "office_name": instance.office_name, "google_civic_election_id": instance.google_civic_election_id, "state_code": instance.state_code } try: res = elastic_search_object.index(index="offices", doc_type='office', id=instance.id, body=doc) if res["_shards"]["successful"] <= 1: logger.error("failed to index ContestOffice " + str(instance.we_vote_id)) except Exception as err: status = "SAVE_CONTEST_OFFICE_SIGNAL, err: " + str(err) logger.error(status) @receiver(post_delete, sender=ContestOffice) def delete_contest_office_signal(sender, instance, **kwargs): # logger.debug("search.delete_ContestOffice_signal") if 'elastic_search_object' in globals(): try: res = elastic_search_object.delete(index="offices", doc_type='office', id=instance.id) if res["_shards"]["successful"] <= 1: logger.error("failed to delete ContestOffice " + str(instance.we_vote_id)) except Exception as err: status = "DELETE_CONTEST_OFFICE_SIGNAL, err: " + str(err) logger.error(status) # Election @receiver(post_save, sender=Election) def save_election_signal(sender, instance, **kwargs): # logger.debug("search.save_Election_signal") if 'elastic_search_object' in globals(): ballot_returned_manager = BallotReturnedManager() if ballot_returned_manager.should_election_search_data_be_saved(instance.google_civic_election_id): doc = { "election_name": instance.election_name, "election_day_text": instance.election_day_text, "google_civic_election_id": instance.google_civic_election_id, "state_code": instance.state_code, "state_name": convert_state_code_to_state_text(instance.state_code) } try: res = elastic_search_object.index(index="elections", doc_type='election', id=instance.id, body=doc) if res["_shards"]["successful"] <= 1: logger.error("failed to index Election " + str(instance.election_name)) except Exception as err: status = "SAVE_ELECTION_SIGNAL, err: " + str(err) logger.error(status) else: try: res = elastic_search_object.delete(index="elections", doc_type='election', id=instance.id) if res["_shards"]["successful"] <= 1: logger.error("failed to delete1 Election " + str(instance.election_name)) except Exception as err: status = "DELETE_ELECTION_SIGNAL1, err: " + str(err) logger.error(status) @receiver(post_delete, sender=Election) def delete_election_signal(sender, instance, **kwargs): # logger.debug("search.delete_Election_signal") if 'elastic_search_object' in globals(): try: res = elastic_search_object.delete(index="elections", doc_type='election', id=instance.id) if res["_shards"]["successful"] <= 1: logger.error("failed to delete2 Election " + str(instance.election_name)) except Exception as err: status = "DELETE_ELECTION_SIGNAL2, err: " + str(err) logger.error(status) # Organization @receiver(post_save, sender=Organization) def save_organization_signal(sender, instance, **kwargs): # logger.debug("search.save_Organization_signal") if 'elastic_search_object' in globals(): doc = { "we_vote_id": instance.we_vote_id, "organization_name": instance.organization_name, "organization_twitter_handle": instance.organization_twitter_handle, "organization_website": instance.organization_website, "twitter_description": instance.twitter_description, "state_served_code": instance.state_served_code, } try: res = elastic_search_object.index(index="organizations", doc_type='organization', id=instance.id, body=doc) if res["_shards"]["successful"] <= 1: logger.error("failed to index Organization " + str(instance.we_vote_id)) except Exception as err: status = "SAVE_ORGANIZATION_SIGNAL, err: " + str(err) logger.error(status) @receiver(post_delete, sender=Organization) def delete_organization_signal(sender, instance, **kwargs): # logger.debug("search.delete_Organization_signal") if 'elastic_search_object' in globals(): try: res = elastic_search_object.delete(index="organizations", doc_type='organization', id=instance.id) if res["_shards"]["successful"] <= 1: logger.error("failed to delete Organization " + str(instance.we_vote_id)) except Exception as err: status = "DELETE_ORGANIZATION_SIGNAL, err: " + str(err) logger.error(status) # @receiver(post_save) # def save_signal(sender, **kwargs): # print("### save") # # @receiver(post_delete) # def delete_signal(sender, **kwargs): # print("### delete") # # from django.core.signals import request_finished # @receiver(request_finished) # def request_signal(sender, **kwargs): # print("> request!") # # print("Signals Up")
en
0.494514
# search/models.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- # CandidateCampaign # logger.debug("search.save_candidate_campaign_signal") # logger.debug("search.delete_CandidateCampaign_signal") # ContestMeasure # logger.debug("search.save_ContestMeasure_signal") # logger.debug("search.delete_ContestMeasure_signal") # ContestOffice # logger.debug("search.save_ContestOffice_signal") # logger.debug("search.delete_ContestOffice_signal") # Election # logger.debug("search.save_Election_signal") # logger.debug("search.delete_Election_signal") # Organization # logger.debug("search.save_Organization_signal") # logger.debug("search.delete_Organization_signal") # @receiver(post_save) # def save_signal(sender, **kwargs): # print("### save") # # @receiver(post_delete) # def delete_signal(sender, **kwargs): # print("### delete") # # from django.core.signals import request_finished # @receiver(request_finished) # def request_signal(sender, **kwargs): # print("> request!") # # print("Signals Up")
1.508424
2
src/crypto/algs.py
iulianPeiu6/EncryptedDatabase
0
6612746
<reponame>iulianPeiu6/EncryptedDatabase """Cryptography algorithms""" import os import random import string import pyaes as pyaes import rsa from enum import Enum from rsa import PublicKey, PrivateKey class Alg(str, Enum): """An enumeration of available encryption algorithms""" DEFAULT_ALG = "RSA" RSA = "RSA" AES_ECB = "AES_ECB" class Settings(int, Enum): """Contains settings regarding: rsa default key size(bits), aes default key size(chars)""" RSA_DEFAULT_KEY_SIZE = 2048 AES_DEFAULT_KEY_SIZE = 32 class RSA(object): """RSA algorithm: key generation, encryption and decryption""" @staticmethod def generate_keys() -> tuple[PublicKey, PrivateKey]: """Generate a tuple representing the public and private keys with the default size specified in the :py:class:`Settings` :returns: a tuple (:py:class:`rsa.PublicKey`, :py:class:`rsa.PrivateKey`) """ return rsa.newkeys(Settings.RSA_DEFAULT_KEY_SIZE) @staticmethod def encrypt(msg_bytes: bytes, key: PublicKey) -> bytes: """Encrypt a text bytes using a given key. :param msg_bytes: the text bytes that will be encrypted :param key: the public key used for encryption :return: the encrypted text bytes """ return rsa.encrypt(msg_bytes, key) @staticmethod def decrypt(msg_bytes: bytes, key: PrivateKey) -> str: """Decrypt a cypher bytes using a given key. :param msg_bytes: the cypher text bytes that will be decrypted :param key: the private key used for decryption :return: the decrypted text """ return rsa.decrypt(msg_bytes, key).decode() class AESKey(object): def __init__(self, key: str, iv: str): """Constructor :param key: key :param iv: initialization vector """ self.key = key self.iv = iv def __repr__(self): return f"AESKey(\"{self.key}\", \"{self.iv}\")" def __str__(self): return f"AESKey(\"{self.key}\", \"{self.iv}\")" class AES(object): """AES algorithm: key generation, encryption and decryption""" @staticmethod def generate_keys() -> tuple[AESKey, AESKey]: """Generate a tuple representing the public and private keys with the default size specified in the :py:class:`Settings` :returns: a tuple (:py:class:`AESKey`, :py:class:`AESKey`) """ key = "".join(random.choices(string.ascii_letters + string.digits, k=Settings.AES_DEFAULT_KEY_SIZE.value)) iv = "".join(random.choices(string.ascii_letters + string.digits, k=Settings.AES_DEFAULT_KEY_SIZE.value)) return AESKey(key, iv), AESKey(key, iv) @staticmethod def ecb_encrypt(plaintext: str, aes_key: AESKey, block_size: int = 16) -> bytes: """Encrypt a text using a given key. :param plaintext: the text bytes that will be encrypted :param aes_key: the key used for encryption :param block_size: block size (in number of chars) (default 16) :return: the encrypted text bytes """ key = aes_key.key plaintext = AES._add_padding(plaintext, block_size) blocks = [plaintext[i:i + block_size] for i in range(0, len(plaintext), block_size)] ciphertext = "" for block in blocks: cipher_block = AES._encrypt(block, key) ciphertext += cipher_block return ciphertext.encode() @staticmethod def ecb_decrypt(ciphertext: str, aes_key: AESKey, block_size: int = 16) -> str: """Decrypt a cypher using a given key. :param ciphertext: the cypher text that will be decrypted :param aes_key: the key used for decryption :param block_size: block size (in number of chars) (default 16) :return: the decrypted text """ key = aes_key.key cipher_blocks = [ciphertext[i:i + block_size] for i in range(0, len(ciphertext), block_size)] plaintext = "" for cipher_block in cipher_blocks: block = AES._decrypt(cipher_block, key) plaintext += block return plaintext.rstrip() @staticmethod def _encrypt(plaintext: str, key: str) -> str: """Encrypt a text block. :param plaintext: :param key: :return: the ciphertext """ plaintext_bytes = [ord(c) for c in plaintext] aes = pyaes.AES(key.encode()) ciphertext = aes.encrypt(plaintext_bytes) return "".join(chr(i) for i in ciphertext) @staticmethod def _decrypt(ciphertext: str, key: str) -> str: """Decrypt a text block. :param ciphertext: cypher text :param key: key :return: decrypted text """ ciphertext_bytes = [ord(c) for c in ciphertext] aes = pyaes.AES(key.encode()) plaintext = aes.decrypt(ciphertext_bytes) return "".join(chr(i) for i in plaintext) @staticmethod def _add_padding(plaintext, block_size=16): """Adds padding to a text to obtain a block of size. :param plaintext: text to pad :param block_size: block size (default 16) :return: the padded text with length of the block size """ padding = "" for space_remaining in range(len(plaintext) % block_size, (len(plaintext) // block_size + 1) * block_size): padding += " " plaintext += padding return plaintext
"""Cryptography algorithms""" import os import random import string import pyaes as pyaes import rsa from enum import Enum from rsa import PublicKey, PrivateKey class Alg(str, Enum): """An enumeration of available encryption algorithms""" DEFAULT_ALG = "RSA" RSA = "RSA" AES_ECB = "AES_ECB" class Settings(int, Enum): """Contains settings regarding: rsa default key size(bits), aes default key size(chars)""" RSA_DEFAULT_KEY_SIZE = 2048 AES_DEFAULT_KEY_SIZE = 32 class RSA(object): """RSA algorithm: key generation, encryption and decryption""" @staticmethod def generate_keys() -> tuple[PublicKey, PrivateKey]: """Generate a tuple representing the public and private keys with the default size specified in the :py:class:`Settings` :returns: a tuple (:py:class:`rsa.PublicKey`, :py:class:`rsa.PrivateKey`) """ return rsa.newkeys(Settings.RSA_DEFAULT_KEY_SIZE) @staticmethod def encrypt(msg_bytes: bytes, key: PublicKey) -> bytes: """Encrypt a text bytes using a given key. :param msg_bytes: the text bytes that will be encrypted :param key: the public key used for encryption :return: the encrypted text bytes """ return rsa.encrypt(msg_bytes, key) @staticmethod def decrypt(msg_bytes: bytes, key: PrivateKey) -> str: """Decrypt a cypher bytes using a given key. :param msg_bytes: the cypher text bytes that will be decrypted :param key: the private key used for decryption :return: the decrypted text """ return rsa.decrypt(msg_bytes, key).decode() class AESKey(object): def __init__(self, key: str, iv: str): """Constructor :param key: key :param iv: initialization vector """ self.key = key self.iv = iv def __repr__(self): return f"AESKey(\"{self.key}\", \"{self.iv}\")" def __str__(self): return f"AESKey(\"{self.key}\", \"{self.iv}\")" class AES(object): """AES algorithm: key generation, encryption and decryption""" @staticmethod def generate_keys() -> tuple[AESKey, AESKey]: """Generate a tuple representing the public and private keys with the default size specified in the :py:class:`Settings` :returns: a tuple (:py:class:`AESKey`, :py:class:`AESKey`) """ key = "".join(random.choices(string.ascii_letters + string.digits, k=Settings.AES_DEFAULT_KEY_SIZE.value)) iv = "".join(random.choices(string.ascii_letters + string.digits, k=Settings.AES_DEFAULT_KEY_SIZE.value)) return AESKey(key, iv), AESKey(key, iv) @staticmethod def ecb_encrypt(plaintext: str, aes_key: AESKey, block_size: int = 16) -> bytes: """Encrypt a text using a given key. :param plaintext: the text bytes that will be encrypted :param aes_key: the key used for encryption :param block_size: block size (in number of chars) (default 16) :return: the encrypted text bytes """ key = aes_key.key plaintext = AES._add_padding(plaintext, block_size) blocks = [plaintext[i:i + block_size] for i in range(0, len(plaintext), block_size)] ciphertext = "" for block in blocks: cipher_block = AES._encrypt(block, key) ciphertext += cipher_block return ciphertext.encode() @staticmethod def ecb_decrypt(ciphertext: str, aes_key: AESKey, block_size: int = 16) -> str: """Decrypt a cypher using a given key. :param ciphertext: the cypher text that will be decrypted :param aes_key: the key used for decryption :param block_size: block size (in number of chars) (default 16) :return: the decrypted text """ key = aes_key.key cipher_blocks = [ciphertext[i:i + block_size] for i in range(0, len(ciphertext), block_size)] plaintext = "" for cipher_block in cipher_blocks: block = AES._decrypt(cipher_block, key) plaintext += block return plaintext.rstrip() @staticmethod def _encrypt(plaintext: str, key: str) -> str: """Encrypt a text block. :param plaintext: :param key: :return: the ciphertext """ plaintext_bytes = [ord(c) for c in plaintext] aes = pyaes.AES(key.encode()) ciphertext = aes.encrypt(plaintext_bytes) return "".join(chr(i) for i in ciphertext) @staticmethod def _decrypt(ciphertext: str, key: str) -> str: """Decrypt a text block. :param ciphertext: cypher text :param key: key :return: decrypted text """ ciphertext_bytes = [ord(c) for c in ciphertext] aes = pyaes.AES(key.encode()) plaintext = aes.decrypt(ciphertext_bytes) return "".join(chr(i) for i in plaintext) @staticmethod def _add_padding(plaintext, block_size=16): """Adds padding to a text to obtain a block of size. :param plaintext: text to pad :param block_size: block size (default 16) :return: the padded text with length of the block size """ padding = "" for space_remaining in range(len(plaintext) % block_size, (len(plaintext) // block_size + 1) * block_size): padding += " " plaintext += padding return plaintext
en
0.620051
Cryptography algorithms An enumeration of available encryption algorithms Contains settings regarding: rsa default key size(bits), aes default key size(chars) RSA algorithm: key generation, encryption and decryption Generate a tuple representing the public and private keys with the default size specified in the :py:class:`Settings` :returns: a tuple (:py:class:`rsa.PublicKey`, :py:class:`rsa.PrivateKey`) Encrypt a text bytes using a given key. :param msg_bytes: the text bytes that will be encrypted :param key: the public key used for encryption :return: the encrypted text bytes Decrypt a cypher bytes using a given key. :param msg_bytes: the cypher text bytes that will be decrypted :param key: the private key used for decryption :return: the decrypted text Constructor :param key: key :param iv: initialization vector AES algorithm: key generation, encryption and decryption Generate a tuple representing the public and private keys with the default size specified in the :py:class:`Settings` :returns: a tuple (:py:class:`AESKey`, :py:class:`AESKey`) Encrypt a text using a given key. :param plaintext: the text bytes that will be encrypted :param aes_key: the key used for encryption :param block_size: block size (in number of chars) (default 16) :return: the encrypted text bytes Decrypt a cypher using a given key. :param ciphertext: the cypher text that will be decrypted :param aes_key: the key used for decryption :param block_size: block size (in number of chars) (default 16) :return: the decrypted text Encrypt a text block. :param plaintext: :param key: :return: the ciphertext Decrypt a text block. :param ciphertext: cypher text :param key: key :return: decrypted text Adds padding to a text to obtain a block of size. :param plaintext: text to pad :param block_size: block size (default 16) :return: the padded text with length of the block size
3.686283
4
src/migrations/0001_initial.py
karunpabbi/bhavcopy_bse_autoupdate_data
1
6612747
<gh_stars>1-10 # Generated by Django 3.1.2 on 2020-10-28 15:24 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Ticker', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('sc_code', models.TextField()), ('sc_name', models.TextField()), ('sc_open', models.FloatField()), ('sc_high', models.FloatField()), ('sc_low', models.FloatField()), ('sc_close', models.FloatField()), ], ), ]
# Generated by Django 3.1.2 on 2020-10-28 15:24 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Ticker', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('sc_code', models.TextField()), ('sc_name', models.TextField()), ('sc_open', models.FloatField()), ('sc_high', models.FloatField()), ('sc_low', models.FloatField()), ('sc_close', models.FloatField()), ], ), ]
en
0.805314
# Generated by Django 3.1.2 on 2020-10-28 15:24
1.774345
2
Disaster Prep.py
madelinev/Disaster-prep
0
6612748
print("Welcome to Disaster Prep! \n Disaster Prep alerts users when a natural disaster has been predicted in their area and provides users with a personalized plan and check list of necessary items to keep users safe.") def firstaid(): print("First Aid Kit:") print("Flashlight and Extra Batteries \n Nonperishable food to last 3 days (for each person) (purification tablets) \n 1 gallon of water per person per day (3 Days)") print("Plates, Cutlery, and, of course, a manual Can Opener") print ("3 days worth of Clothing for everyone in your family \n Eyeglasses/Contacts and Contact Solution \n Necessary Medicines \n Electronics and Chargers \n For Infants: diapers, formula, etc.") print("Waterproof Matches, a Whistle, and Strong Tape \n Battery operated or Crank Radio") def flood(): print("How to protect your home:") print("Board up windows \n All circuit breakers, switches, sockets, etc. should be a foot above water \n Anchor or disassemble outdoor equipment") print("Clear gutters, downspouts, and drains \n Shut off electricity") print("Never drive on flooded roads \n Drive slowly and steadily") print("Don’t drive over bridges over fast moving water unless absolutely necessary \n Watch out for downed power lines.") print("Check with your local council about local flood plans or records which detail problem areas") print("Ask authorities about relocation routes and centers \n If your area is flood prone, consider alternatives to carpets") print("Prepare an emergency kit \n Prepare a household flood plan \n Keep a list of emergency telephone numbers on display") print("Check your insurance policy to see if you are covered for flood damage \n Secure hazardous items") print("Roll up rugs, move furniture, electrical items and valuables to a higher level") print("Place important personal documents, valuables and vital medical supplies into a waterproof case in an accessible location") print("If you are relocating, take your pets with you if it is safe to do so. If not provide adequate food and water and move them to a safer place") print("Monitor Bureau of Meteorology (BoM) forecasts and warnings online and listen to your local ABC Radio") print("If rising waters threaten your home and you decide to move to a safer location, tell the police, your nearest State Emergency Service (SES) unit or your neighbors of your plans to move") print("Monitor your local radio for warnings and advice \n Pack warm clothing, essential medication, valuables and personal papers in waterproof bags along with your emergency kit") print("Raise furniture, clothing and valuables onto beds, tables and into roof space place electrical items in the highest place") print("Empty freezers and refrigerators, leaving doors open to avoid damage or loss if they float") print("Turn off power, water and gas and take your mobile phone \n Whether you leave or stay, put sand bags in the toilet bowl and over all laundry/bathroom drain holes to prevent sewage backflow") print("Lock your home and take recommended relocation routes for your area \n Do not drive into water of unknown depth and current") print("Monitor your local radio for warnings and advice \n Get to higher ground") print("Switch off electricity and gas supplies to your home \n Prepare to move vehicles, outdoor equipment, garbage, chemical and poisons to higher locations") print("Prepare for the well-being of pets") print("Raise furniture above likely flood levels \n Check your emergency kit \n Do not allow children to play in or near floodwaters") print("Avoid entering floodwaters. If you must do so, wear solid shoes and check depth and current with a stick \n Stay away from drains, culverts and water over knee deep") print("Do not use gas or electrical appliances that have been in floodwater until checked for safety") print("Do not eat food that has been in floodwaters \n Boil tap water until supplies have been declared safe") print("Secure hazardous items \n Roll up rugs, move furniture, electrical items and valuables to a higher level") print("Place important personal documents, valuables and vital medical supplies into a waterproof case in an accessible location") print("If you are relocating, take your pets with you if it is safe to do so. If not provide adequate food and water and move them to a safer place") print("Monitor Bureau of Meteorology (BoM) forecasts and warnings online and listen to your local ABC Radio") print("If rising waters threaten your home and you decide to move to a safer location:") print("Tell the police, your nearest State Emergency Service (SES) unit or your neighbors of your plans to move.") print("Monitor your local radio for warnings and advice \n Pack warm clothing, essential medication, valuables and personal papers in waterproof bags along with your emergency kit") print("Raise furniture, clothing and valuables onto beds, tables and into roof space place electrical items in the highest place") print("Empty freezers and refrigerators, leaving doors open to avoid damage or loss if they float") print("Turn off power, water and gas and take your mobile phone") print("Whether you leave or stay, put sand bags in the toilet bowl and over all laundry/bathroom drain holes to prevent sewage backflow") print("Lock your home and take recommended relocation routes for your area") print("Do not drive into water of unknown depth and current") def wildfire(): print("How to evacuate a building:") print("Check if doors handles are hot. If they are, chances are the next room has fire \n Avoid large rooms, as the oxygen will fuel the fire \n Do not use elevators.") print("Fire Plan:") print("Shut all windows and doors, leaving them unlocked \n Remove flammable window shades, curtains and close metal shutters \n Remove lightweight curtains") print("Move flammable furniture to the center of the room, away from windows and doors \n Shut off gas at the meter; turn off pilot lights") print("Leave your lights on so firefighters can see your house under smoky conditions") print("Shut off the air conditioning") print("Outside:") print("Gather up flammable items from the exterior of the house and bring them inside (patio furniture, children’s toys, door mats, trash cans, etc.) or place them in your pool") print("Turn off propane tanks") print("Move propane BBQ appliances away from structures") print("Connect garden hoses to outside water valves or spigots for use by firefighters. Fill water buckets and place them around the house") print("Don’t leave sprinklers on or water running, they can affect critical water pressure") print("Leave exterior lights on so your home is visible to firefighters in the smoke or darkness of night") print("Put your Emergency Supply Kit in your vehicle") print("Back your car into the driveway with vehicle loaded and all doors and windows closed. Carry your car keys with you") print("Have a ladder available and place it at the corner of the house for firefighters to quickly access your roof") print("Seal attic and ground vents with pre-cut plywood or commercial seals") print("Patrol your property and monitor the fire situation. Don’t wait for an evacuation order if you feel threatened") print("Check on neighbors and make sure they are preparing to leave") print("Animals:") print("Locate your pets and keep them nearby \n Prepare farm animals for transport and think about moving them to a safe location early.") def yesno(question, yess, nos): result = input(question) while (not ( result in yess)) and (not (result in nos)): result = input(question) if result in yess: return(True) else: return(False) def pets(question, dog, cat, other): result = input(question) while not((result in dog) or (result in cat) or (result in other)): result = input(question) if result in dog: return("dog") elif result in cat: return("cat") elif result in other: return ("other") else: return(result) def questionnaire(): print("Collect these items listed below to prepare beforehand for the natural disaster:") print("Water - one gallon of water per person per day for at least three days, for drinking and sanitation") print("Food - at least a three-day supply of non-perishable food") print("Battery-powered or hand crank radio and a NOAA Weather Radio with tone alert \n Flashlight \n First aid kit") print("Extra batteries \n Whistle to signal for help") print("Dust mask to help filter contaminated air and plastic sheeting and duct tape to shelter-in-place") print(" Moist towelettes, garbage bags and plastic ties for personal sanitation \n Wrench or pliers to turn off utilities") print("Manual can opener for food \n Local maps \n Cell phone with chargers and a backup battery") print("Please answer the following questionnaire to customize supplies needed.") yess = ("yes", "Yes", "Y", "y", "ye", "Ye", "YES", "YE") nos = ("No", "no", "N", "n", "naw") dog = ("dog") cat = ("cat") other = ("other") if yesno("Do you have an infant?(yes or no)", yess, nos): print("Bring: \n diapers \n formula \n other baby necessities.") if yesno("Do you have kids in your household under the age of 13?(yes or no)", yess, nos): print("Bring: \n games \n snacks.") if yesno("Do you take any necessary medicine?(yes or no)", yess, nos): meds = input("What medication do you take?") print("Bring: \n seven day supply of", meds) if yesno("Any additional supplies for your family's special needs?(yes or no)", yess, nos): stuff = input("What extra supplies do you think is necessary to bring?") print("Bring: \n ", stuff) if yesno("Are there any girls/women in your household?(yes or no)", yess, nos): print("Bring feminine supplies (ex. tampons, pads, and etc.)") if yesno("Do you have a pet?(yes or no)",yess, nos): animal = pets("Is your animal a dog, cat, or other?", dog, cat, other) if animal == "dog": print('Bring: \n dog food \n leash and/or harness \n pet carrier \n extra water \n trash bags') elif animal == "cat": print ('Bring: \n cat food \n litter box \n pet carrier \n water') elif animal == "other": other = input("What supplies does your other animal need?") print("Bring: \n", other) else: print("") rendezvous = input("Where is your safe rendezvous meeting place?") people_string = input("How many people are in your household?") while not people_string.isdigit(): people_string = input("How many people are in your household?") people = int(people_string) print("Bring enough supplies for", people) print("Meet at the", rendezvous) valid_disaster = ('wildfire', 'flood') disaster = input("What is your disaster? (wildfire or flood)") while not disaster in valid_disaster: disaster = input("What is your disaster? (wildfire or flood)") if disaster == "flood": flood() if disaster == "wildfire": wildfire() firstaid() questionnaire() print("And don't forget the can opener!")
print("Welcome to Disaster Prep! \n Disaster Prep alerts users when a natural disaster has been predicted in their area and provides users with a personalized plan and check list of necessary items to keep users safe.") def firstaid(): print("First Aid Kit:") print("Flashlight and Extra Batteries \n Nonperishable food to last 3 days (for each person) (purification tablets) \n 1 gallon of water per person per day (3 Days)") print("Plates, Cutlery, and, of course, a manual Can Opener") print ("3 days worth of Clothing for everyone in your family \n Eyeglasses/Contacts and Contact Solution \n Necessary Medicines \n Electronics and Chargers \n For Infants: diapers, formula, etc.") print("Waterproof Matches, a Whistle, and Strong Tape \n Battery operated or Crank Radio") def flood(): print("How to protect your home:") print("Board up windows \n All circuit breakers, switches, sockets, etc. should be a foot above water \n Anchor or disassemble outdoor equipment") print("Clear gutters, downspouts, and drains \n Shut off electricity") print("Never drive on flooded roads \n Drive slowly and steadily") print("Don’t drive over bridges over fast moving water unless absolutely necessary \n Watch out for downed power lines.") print("Check with your local council about local flood plans or records which detail problem areas") print("Ask authorities about relocation routes and centers \n If your area is flood prone, consider alternatives to carpets") print("Prepare an emergency kit \n Prepare a household flood plan \n Keep a list of emergency telephone numbers on display") print("Check your insurance policy to see if you are covered for flood damage \n Secure hazardous items") print("Roll up rugs, move furniture, electrical items and valuables to a higher level") print("Place important personal documents, valuables and vital medical supplies into a waterproof case in an accessible location") print("If you are relocating, take your pets with you if it is safe to do so. If not provide adequate food and water and move them to a safer place") print("Monitor Bureau of Meteorology (BoM) forecasts and warnings online and listen to your local ABC Radio") print("If rising waters threaten your home and you decide to move to a safer location, tell the police, your nearest State Emergency Service (SES) unit or your neighbors of your plans to move") print("Monitor your local radio for warnings and advice \n Pack warm clothing, essential medication, valuables and personal papers in waterproof bags along with your emergency kit") print("Raise furniture, clothing and valuables onto beds, tables and into roof space place electrical items in the highest place") print("Empty freezers and refrigerators, leaving doors open to avoid damage or loss if they float") print("Turn off power, water and gas and take your mobile phone \n Whether you leave or stay, put sand bags in the toilet bowl and over all laundry/bathroom drain holes to prevent sewage backflow") print("Lock your home and take recommended relocation routes for your area \n Do not drive into water of unknown depth and current") print("Monitor your local radio for warnings and advice \n Get to higher ground") print("Switch off electricity and gas supplies to your home \n Prepare to move vehicles, outdoor equipment, garbage, chemical and poisons to higher locations") print("Prepare for the well-being of pets") print("Raise furniture above likely flood levels \n Check your emergency kit \n Do not allow children to play in or near floodwaters") print("Avoid entering floodwaters. If you must do so, wear solid shoes and check depth and current with a stick \n Stay away from drains, culverts and water over knee deep") print("Do not use gas or electrical appliances that have been in floodwater until checked for safety") print("Do not eat food that has been in floodwaters \n Boil tap water until supplies have been declared safe") print("Secure hazardous items \n Roll up rugs, move furniture, electrical items and valuables to a higher level") print("Place important personal documents, valuables and vital medical supplies into a waterproof case in an accessible location") print("If you are relocating, take your pets with you if it is safe to do so. If not provide adequate food and water and move them to a safer place") print("Monitor Bureau of Meteorology (BoM) forecasts and warnings online and listen to your local ABC Radio") print("If rising waters threaten your home and you decide to move to a safer location:") print("Tell the police, your nearest State Emergency Service (SES) unit or your neighbors of your plans to move.") print("Monitor your local radio for warnings and advice \n Pack warm clothing, essential medication, valuables and personal papers in waterproof bags along with your emergency kit") print("Raise furniture, clothing and valuables onto beds, tables and into roof space place electrical items in the highest place") print("Empty freezers and refrigerators, leaving doors open to avoid damage or loss if they float") print("Turn off power, water and gas and take your mobile phone") print("Whether you leave or stay, put sand bags in the toilet bowl and over all laundry/bathroom drain holes to prevent sewage backflow") print("Lock your home and take recommended relocation routes for your area") print("Do not drive into water of unknown depth and current") def wildfire(): print("How to evacuate a building:") print("Check if doors handles are hot. If they are, chances are the next room has fire \n Avoid large rooms, as the oxygen will fuel the fire \n Do not use elevators.") print("Fire Plan:") print("Shut all windows and doors, leaving them unlocked \n Remove flammable window shades, curtains and close metal shutters \n Remove lightweight curtains") print("Move flammable furniture to the center of the room, away from windows and doors \n Shut off gas at the meter; turn off pilot lights") print("Leave your lights on so firefighters can see your house under smoky conditions") print("Shut off the air conditioning") print("Outside:") print("Gather up flammable items from the exterior of the house and bring them inside (patio furniture, children’s toys, door mats, trash cans, etc.) or place them in your pool") print("Turn off propane tanks") print("Move propane BBQ appliances away from structures") print("Connect garden hoses to outside water valves or spigots for use by firefighters. Fill water buckets and place them around the house") print("Don’t leave sprinklers on or water running, they can affect critical water pressure") print("Leave exterior lights on so your home is visible to firefighters in the smoke or darkness of night") print("Put your Emergency Supply Kit in your vehicle") print("Back your car into the driveway with vehicle loaded and all doors and windows closed. Carry your car keys with you") print("Have a ladder available and place it at the corner of the house for firefighters to quickly access your roof") print("Seal attic and ground vents with pre-cut plywood or commercial seals") print("Patrol your property and monitor the fire situation. Don’t wait for an evacuation order if you feel threatened") print("Check on neighbors and make sure they are preparing to leave") print("Animals:") print("Locate your pets and keep them nearby \n Prepare farm animals for transport and think about moving them to a safe location early.") def yesno(question, yess, nos): result = input(question) while (not ( result in yess)) and (not (result in nos)): result = input(question) if result in yess: return(True) else: return(False) def pets(question, dog, cat, other): result = input(question) while not((result in dog) or (result in cat) or (result in other)): result = input(question) if result in dog: return("dog") elif result in cat: return("cat") elif result in other: return ("other") else: return(result) def questionnaire(): print("Collect these items listed below to prepare beforehand for the natural disaster:") print("Water - one gallon of water per person per day for at least three days, for drinking and sanitation") print("Food - at least a three-day supply of non-perishable food") print("Battery-powered or hand crank radio and a NOAA Weather Radio with tone alert \n Flashlight \n First aid kit") print("Extra batteries \n Whistle to signal for help") print("Dust mask to help filter contaminated air and plastic sheeting and duct tape to shelter-in-place") print(" Moist towelettes, garbage bags and plastic ties for personal sanitation \n Wrench or pliers to turn off utilities") print("Manual can opener for food \n Local maps \n Cell phone with chargers and a backup battery") print("Please answer the following questionnaire to customize supplies needed.") yess = ("yes", "Yes", "Y", "y", "ye", "Ye", "YES", "YE") nos = ("No", "no", "N", "n", "naw") dog = ("dog") cat = ("cat") other = ("other") if yesno("Do you have an infant?(yes or no)", yess, nos): print("Bring: \n diapers \n formula \n other baby necessities.") if yesno("Do you have kids in your household under the age of 13?(yes or no)", yess, nos): print("Bring: \n games \n snacks.") if yesno("Do you take any necessary medicine?(yes or no)", yess, nos): meds = input("What medication do you take?") print("Bring: \n seven day supply of", meds) if yesno("Any additional supplies for your family's special needs?(yes or no)", yess, nos): stuff = input("What extra supplies do you think is necessary to bring?") print("Bring: \n ", stuff) if yesno("Are there any girls/women in your household?(yes or no)", yess, nos): print("Bring feminine supplies (ex. tampons, pads, and etc.)") if yesno("Do you have a pet?(yes or no)",yess, nos): animal = pets("Is your animal a dog, cat, or other?", dog, cat, other) if animal == "dog": print('Bring: \n dog food \n leash and/or harness \n pet carrier \n extra water \n trash bags') elif animal == "cat": print ('Bring: \n cat food \n litter box \n pet carrier \n water') elif animal == "other": other = input("What supplies does your other animal need?") print("Bring: \n", other) else: print("") rendezvous = input("Where is your safe rendezvous meeting place?") people_string = input("How many people are in your household?") while not people_string.isdigit(): people_string = input("How many people are in your household?") people = int(people_string) print("Bring enough supplies for", people) print("Meet at the", rendezvous) valid_disaster = ('wildfire', 'flood') disaster = input("What is your disaster? (wildfire or flood)") while not disaster in valid_disaster: disaster = input("What is your disaster? (wildfire or flood)") if disaster == "flood": flood() if disaster == "wildfire": wildfire() firstaid() questionnaire() print("And don't forget the can opener!")
none
1
2.981838
3
inst/python/transformer/sublayer.py
quantitative-technologies/transformer-high-level-keras-api
1
6612749
import tensorflow as tf from tensorflow.keras.layers import Layer, Dropout, LayerNormalization class TransformerSubLayer(Layer): def __init__(self, input_sublayer, input_key=None, epsilon=1e-6, dropout_rate=0.1): super(TransformerSubLayer, self).__init__() self.input_sublayer = input_sublayer self.input_key = input_key self.epsilon = epsilon self.dropout_rate = dropout_rate self.dropout = Dropout(dropout_rate) self.layernorm = LayerNormalization(epsilon=epsilon) def call(self, inputs, training=None, mask=None): if self.input_key is not None: x = inputs[self.input_key] else: x = inputs sublayer_outputs = self.input_sublayer(inputs=inputs, mask=mask) outputs = self.dropout(sublayer_outputs, training) outputs += x # Loses the mask info return self.layernorm(outputs) def compute_mask(self, inputs, mask=None): if mask is None: return None if self.input_key: return mask[self.input_key] return mask
import tensorflow as tf from tensorflow.keras.layers import Layer, Dropout, LayerNormalization class TransformerSubLayer(Layer): def __init__(self, input_sublayer, input_key=None, epsilon=1e-6, dropout_rate=0.1): super(TransformerSubLayer, self).__init__() self.input_sublayer = input_sublayer self.input_key = input_key self.epsilon = epsilon self.dropout_rate = dropout_rate self.dropout = Dropout(dropout_rate) self.layernorm = LayerNormalization(epsilon=epsilon) def call(self, inputs, training=None, mask=None): if self.input_key is not None: x = inputs[self.input_key] else: x = inputs sublayer_outputs = self.input_sublayer(inputs=inputs, mask=mask) outputs = self.dropout(sublayer_outputs, training) outputs += x # Loses the mask info return self.layernorm(outputs) def compute_mask(self, inputs, mask=None): if mask is None: return None if self.input_key: return mask[self.input_key] return mask
en
0.307865
# Loses the mask info
2.753446
3
src/currencycloud/resources/sender.py
icebotariccl/currencycloud-python
12
6612750
from currencycloud.resources.resource import Resource class Sender (Resource): """This class represents a CurrencyCloud Sender""" pass
from currencycloud.resources.resource import Resource class Sender (Resource): """This class represents a CurrencyCloud Sender""" pass
en
0.693457
This class represents a CurrencyCloud Sender
1.516762
2